File:  [gforth] / gforth / doc / gforth.ds
Revision 1.167: download - view: text, annotated - select for diffs
Thu Dec 28 14:52:19 2006 UTC (17 years, 3 months ago) by anton
Branches: MAIN
CVS tags: HEAD
added >OUTFILE ... OUTFILE<, >INFILE...INFILE< and use it in ~~

    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 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: * Files Tutorial::              
  178: * Interpretation and Compilation Semantics and Immediacy Tutorial::  
  179: * Execution Tokens Tutorial::   
  180: * Exceptions Tutorial::         
  181: * Defining Words Tutorial::     
  182: * Arrays and Records Tutorial::  
  183: * POSTPONE Tutorial::           
  184: * Literal Tutorial::            
  185: * Advanced macros Tutorial::    
  186: * Compilation Tokens Tutorial::  
  187: * Wordlists and Search Order Tutorial::  
  188: 
  189: An Introduction to ANS Forth
  190: 
  191: * Introducing the Text Interpreter::  
  192: * Stacks and Postfix notation::  
  193: * Your first definition::       
  194: * How does that work?::         
  195: * Forth is written in Forth::   
  196: * Review - elements of a Forth system::  
  197: * Where to go next::            
  198: * Exercises::                   
  199: 
  200: Forth Words
  201: 
  202: * Notation::                    
  203: * Case insensitivity::          
  204: * Comments::                    
  205: * Boolean Flags::               
  206: * Arithmetic::                  
  207: * Stack Manipulation::          
  208: * Memory::                      
  209: * Control Structures::          
  210: * Defining Words::              
  211: * Interpretation and Compilation Semantics::  
  212: * Tokens for Words::            
  213: * Compiling words::             
  214: * The Text Interpreter::        
  215: * The Input Stream::            
  216: * Word Lists::                  
  217: * Environmental Queries::       
  218: * Files::                       
  219: * Blocks::                      
  220: * Other I/O::                   
  221: * OS command line arguments::   
  222: * Locals::                      
  223: * Structures::                  
  224: * Object-oriented Forth::       
  225: * Programming Tools::           
  226: * C Interface::                 
  227: * Assembler and Code Words::    
  228: * Threading Words::             
  229: * Passing Commands to the OS::  
  230: * Keeping track of Time::       
  231: * Miscellaneous Words::         
  232: 
  233: Arithmetic
  234: 
  235: * Single precision::            
  236: * Double precision::            Double-cell integer arithmetic
  237: * Bitwise operations::          
  238: * Numeric comparison::          
  239: * Mixed precision::             Operations with single and double-cell integers
  240: * Floating Point::              
  241: 
  242: Stack Manipulation
  243: 
  244: * Data stack::                  
  245: * Floating point stack::        
  246: * Return stack::                
  247: * Locals stack::                
  248: * Stack pointer manipulation::  
  249: 
  250: Memory
  251: 
  252: * Memory model::                
  253: * Dictionary allocation::       
  254: * Heap Allocation::             
  255: * Memory Access::               
  256: * Address arithmetic::          
  257: * Memory Blocks::               
  258: 
  259: Control Structures
  260: 
  261: * Selection::                   IF ... ELSE ... ENDIF
  262: * Simple Loops::                BEGIN ...
  263: * Counted Loops::               DO
  264: * Arbitrary control structures::  
  265: * Calls and returns::           
  266: * Exception Handling::          
  267: 
  268: Defining Words
  269: 
  270: * CREATE::                      
  271: * Variables::                   Variables and user variables
  272: * Constants::                   
  273: * Values::                      Initialised variables
  274: * Colon Definitions::           
  275: * Anonymous Definitions::       Definitions without names
  276: * Supplying names::             Passing definition names as strings
  277: * User-defined Defining Words::  
  278: * Deferred words::              Allow forward references
  279: * Aliases::                     
  280: 
  281: User-defined Defining Words
  282: 
  283: * CREATE..DOES> applications::  
  284: * CREATE..DOES> details::       
  285: * Advanced does> usage example::  
  286: * Const-does>::                 
  287: 
  288: Interpretation and Compilation Semantics
  289: 
  290: * Combined words::              
  291: 
  292: Tokens for Words
  293: 
  294: * Execution token::             represents execution/interpretation semantics
  295: * Compilation token::           represents compilation semantics
  296: * Name token::                  represents named words
  297: 
  298: Compiling words
  299: 
  300: * Literals::                    Compiling data values
  301: * Macros::                      Compiling words
  302: 
  303: The Text Interpreter
  304: 
  305: * Input Sources::               
  306: * Number Conversion::           
  307: * Interpret/Compile states::    
  308: * Interpreter Directives::      
  309: 
  310: Word Lists
  311: 
  312: * Vocabularies::                
  313: * Why use word lists?::         
  314: * Word list example::           
  315: 
  316: Files
  317: 
  318: * Forth source files::          
  319: * General files::               
  320: * Redirection::                 
  321: * Search Paths::                
  322: 
  323: Search Paths
  324: 
  325: * Source Search Paths::         
  326: * General Search Paths::        
  327: 
  328: Other I/O
  329: 
  330: * Simple numeric output::       Predefined formats
  331: * Formatted numeric output::    Formatted (pictured) output
  332: * String Formats::              How Forth stores strings in memory
  333: * Displaying characters and strings::  Other stuff
  334: * Input::                       Input
  335: * Pipes::                       How to create your own pipes
  336: * Xchars and Unicode::          Non-ASCII characters
  337: 
  338: Locals
  339: 
  340: * Gforth locals::               
  341: * ANS Forth locals::            
  342: 
  343: Gforth locals
  344: 
  345: * Where are locals visible by name?::  
  346: * How long do locals live?::    
  347: * Locals programming style::    
  348: * Locals implementation::       
  349: 
  350: Structures
  351: 
  352: * Why explicit structure support?::  
  353: * Structure Usage::             
  354: * Structure Naming Convention::  
  355: * Structure Implementation::    
  356: * Structure Glossary::          
  357: 
  358: Object-oriented Forth
  359: 
  360: * Why object-oriented programming?::  
  361: * Object-Oriented Terminology::  
  362: * Objects::                     
  363: * OOF::                         
  364: * Mini-OOF::                    
  365: * Comparison with other object models::  
  366: 
  367: The @file{objects.fs} model
  368: 
  369: * Properties of the Objects model::  
  370: * Basic Objects Usage::         
  371: * The Objects base class::      
  372: * Creating objects::            
  373: * Object-Oriented Programming Style::  
  374: * Class Binding::               
  375: * Method conveniences::         
  376: * Classes and Scoping::         
  377: * Dividing classes::            
  378: * Object Interfaces::           
  379: * Objects Implementation::      
  380: * Objects Glossary::            
  381: 
  382: The @file{oof.fs} model
  383: 
  384: * Properties of the OOF model::  
  385: * Basic OOF Usage::             
  386: * The OOF base class::          
  387: * Class Declaration::           
  388: * Class Implementation::        
  389: 
  390: The @file{mini-oof.fs} model
  391: 
  392: * Basic Mini-OOF Usage::        
  393: * Mini-OOF Example::            
  394: * Mini-OOF Implementation::     
  395: 
  396: Programming Tools
  397: 
  398: * Examining::                   Data and Code.
  399: * Forgetting words::            Usually before reloading.
  400: * Debugging::                   Simple and quick.
  401: * Assertions::                  Making your programs self-checking.
  402: * Singlestep Debugger::         Executing your program word by word.
  403: 
  404: C Interface
  405: 
  406: * Calling C Functions::         
  407: * Declaring C Functions::       
  408: * Callbacks::                   
  409: * Low-Level C Interface Words::  
  410: 
  411: Assembler and Code Words
  412: 
  413: * Code and ;code::              
  414: * Common Assembler::            Assembler Syntax
  415: * Common Disassembler::         
  416: * 386 Assembler::               Deviations and special cases
  417: * Alpha Assembler::             Deviations and special cases
  418: * MIPS assembler::              Deviations and special cases
  419: * PowerPC assembler::           Deviations and special cases
  420: * Other assemblers::            How to write them
  421: 
  422: Tools
  423: 
  424: * ANS Report::                  Report the words used, sorted by wordset.
  425: * Stack depth changes::         Where does this stack item come from?
  426: 
  427: ANS conformance
  428: 
  429: * The Core Words::              
  430: * The optional Block word set::  
  431: * The optional Double Number word set::  
  432: * The optional Exception word set::  
  433: * The optional Facility word set::  
  434: * The optional File-Access word set::  
  435: * The optional Floating-Point word set::  
  436: * The optional Locals word set::  
  437: * The optional Memory-Allocation word set::  
  438: * The optional Programming-Tools word set::  
  439: * The optional Search-Order word set::  
  440: 
  441: The Core Words
  442: 
  443: * core-idef::                   Implementation Defined Options                   
  444: * core-ambcond::                Ambiguous Conditions                
  445: * core-other::                  Other System Documentation                  
  446: 
  447: The optional Block word set
  448: 
  449: * block-idef::                  Implementation Defined Options
  450: * block-ambcond::               Ambiguous Conditions               
  451: * block-other::                 Other System Documentation                 
  452: 
  453: The optional Double Number word set
  454: 
  455: * double-ambcond::              Ambiguous Conditions              
  456: 
  457: The optional Exception word set
  458: 
  459: * exception-idef::              Implementation Defined Options              
  460: 
  461: The optional Facility word set
  462: 
  463: * facility-idef::               Implementation Defined Options               
  464: * facility-ambcond::            Ambiguous Conditions            
  465: 
  466: The optional File-Access word set
  467: 
  468: * file-idef::                   Implementation Defined Options
  469: * file-ambcond::                Ambiguous Conditions                
  470: 
  471: The optional Floating-Point word set
  472: 
  473: * floating-idef::               Implementation Defined Options
  474: * floating-ambcond::            Ambiguous Conditions            
  475: 
  476: The optional Locals word set
  477: 
  478: * locals-idef::                 Implementation Defined Options                 
  479: * locals-ambcond::              Ambiguous Conditions              
  480: 
  481: The optional Memory-Allocation word set
  482: 
  483: * memory-idef::                 Implementation Defined Options                 
  484: 
  485: The optional Programming-Tools word set
  486: 
  487: * programming-idef::            Implementation Defined Options            
  488: * programming-ambcond::         Ambiguous Conditions         
  489: 
  490: The optional Search-Order word set
  491: 
  492: * search-idef::                 Implementation Defined Options                 
  493: * search-ambcond::              Ambiguous Conditions              
  494: 
  495: Emacs and Gforth
  496: 
  497: * Installing gforth.el::        Making Emacs aware of Forth.
  498: * Emacs Tags::                  Viewing the source of a word in Emacs.
  499: * Hilighting::                  Making Forth code look prettier.
  500: * Auto-Indentation::            Customizing auto-indentation.
  501: * Blocks Files::                Reading and writing blocks files.
  502: 
  503: Image Files
  504: 
  505: * Image Licensing Issues::      Distribution terms for images.
  506: * Image File Background::       Why have image files?
  507: * Non-Relocatable Image Files::  don't always work.
  508: * Data-Relocatable Image Files::  are better.
  509: * Fully Relocatable Image Files::  better yet.
  510: * Stack and Dictionary Sizes::  Setting the default sizes for an image.
  511: * Running Image Files::         @code{gforth -i @i{file}} or @i{file}.
  512: * Modifying the Startup Sequence::  and turnkey applications.
  513: 
  514: Fully Relocatable Image Files
  515: 
  516: * gforthmi::                    The normal way
  517: * cross.fs::                    The hard way
  518: 
  519: Engine
  520: 
  521: * Portability::                 
  522: * Threading::                   
  523: * Primitives::                  
  524: * Performance::                 
  525: 
  526: Threading
  527: 
  528: * Scheduling::                  
  529: * Direct or Indirect Threaded?::  
  530: * Dynamic Superinstructions::   
  531: * DOES>::                       
  532: 
  533: Primitives
  534: 
  535: * Automatic Generation::        
  536: * TOS Optimization::            
  537: * Produced code::               
  538: 
  539: Cross Compiler
  540: 
  541: * Using the Cross Compiler::    
  542: * How the Cross Compiler Works::  
  543: 
  544: Licenses
  545: 
  546: * GNU Free Documentation License::  License for copying this manual.
  547: * Copying::                         GPL (for copying this software).
  548: 
  549: @end detailmenu
  550: @end menu
  551: 
  552: @c ----------------------------------------------------------
  553: @iftex
  554: @unnumbered Preface
  555: @cindex Preface
  556: This manual documents Gforth. Some introductory material is provided for
  557: readers who are unfamiliar with Forth or who are migrating to Gforth
  558: from other Forth compilers. However, this manual is primarily a
  559: reference manual.
  560: @end iftex
  561: 
  562: @comment TODO much more blurb here.
  563: 
  564: @c ******************************************************************
  565: @node Goals, Gforth Environment, Top, Top
  566: @comment node-name,     next,           previous, up
  567: @chapter Goals of Gforth
  568: @cindex goals of the Gforth project
  569: The goal of the Gforth Project is to develop a standard model for
  570: ANS Forth. This can be split into several subgoals:
  571: 
  572: @itemize @bullet
  573: @item
  574: Gforth should conform to the ANS Forth Standard.
  575: @item
  576: It should be a model, i.e. it should define all the
  577: implementation-dependent things.
  578: @item
  579: It should become standard, i.e. widely accepted and used. This goal
  580: is the most difficult one.
  581: @end itemize
  582: 
  583: To achieve these goals Gforth should be
  584: @itemize @bullet
  585: @item
  586: Similar to previous models (fig-Forth, F83)
  587: @item
  588: Powerful. It should provide for all the things that are considered
  589: necessary today and even some that are not yet considered necessary.
  590: @item
  591: Efficient. It should not get the reputation of being exceptionally
  592: slow.
  593: @item
  594: Free.
  595: @item
  596: Available on many machines/easy to port.
  597: @end itemize
  598: 
  599: Have we achieved these goals? Gforth conforms to the ANS Forth
  600: standard. It may be considered a model, but we have not yet documented
  601: which parts of the model are stable and which parts we are likely to
  602: change. It certainly has not yet become a de facto standard, but it
  603: appears to be quite popular. It has some similarities to and some
  604: differences from previous models. It has some powerful features, but not
  605: yet everything that we envisioned. We certainly have achieved our
  606: execution speed goals (@pxref{Performance})@footnote{However, in 1998
  607: the bar was raised when the major commercial Forth vendors switched to
  608: native code compilers.}.  It is free and available on many machines.
  609: 
  610: @c ******************************************************************
  611: @node Gforth Environment, Tutorial, Goals, Top
  612: @chapter Gforth Environment
  613: @cindex Gforth environment
  614: 
  615: Note: ultimately, the Gforth man page will be auto-generated from the
  616: material in this chapter.
  617: 
  618: @menu
  619: * Invoking Gforth::             Getting in
  620: * Leaving Gforth::              Getting out
  621: * Command-line editing::        
  622: * Environment variables::       that affect how Gforth starts up
  623: * Gforth Files::                What gets installed and where
  624: * Gforth in pipes::             
  625: * Startup speed::               When 35ms is not fast enough ...
  626: @end menu
  627: 
  628: For related information about the creation of images see @ref{Image Files}.
  629: 
  630: @comment ----------------------------------------------
  631: @node Invoking Gforth, Leaving Gforth, Gforth Environment, Gforth Environment
  632: @section Invoking Gforth
  633: @cindex invoking Gforth
  634: @cindex running Gforth
  635: @cindex command-line options
  636: @cindex options on the command line
  637: @cindex flags on the command line
  638: 
  639: Gforth is made up of two parts; an executable ``engine'' (named
  640: @command{gforth} or @command{gforth-fast}) and an image file. To start it, you
  641: will usually just say @code{gforth} -- this automatically loads the
  642: default image file @file{gforth.fi}. In many other cases the default
  643: Gforth image will be invoked like this:
  644: @example
  645: gforth [file | -e forth-code] ...
  646: @end example
  647: @noindent
  648: This interprets the contents of the files and the Forth code in the order they
  649: are given.
  650: 
  651: In addition to the @command{gforth} engine, there is also an engine
  652: called @command{gforth-fast}, which is faster, but gives less
  653: informative error messages (@pxref{Error messages}) and may catch some
  654: errors (in particular, stack underflows and integer division errors)
  655: later or not at all.  You should use it for debugged,
  656: performance-critical programs.
  657: 
  658: Moreover, there is an engine called @command{gforth-itc}, which is
  659: useful in some backwards-compatibility situations (@pxref{Direct or
  660: Indirect Threaded?}).
  661: 
  662: In general, the command line looks like this:
  663: 
  664: @example
  665: gforth[-fast] [engine options] [image options]
  666: @end example
  667: 
  668: The engine options must come before the rest of the command
  669: line. They are:
  670: 
  671: @table @code
  672: @cindex -i, command-line option
  673: @cindex --image-file, command-line option
  674: @item --image-file @i{file}
  675: @itemx -i @i{file}
  676: Loads the Forth image @i{file} instead of the default
  677: @file{gforth.fi} (@pxref{Image Files}).
  678: 
  679: @cindex --appl-image, command-line option
  680: @item --appl-image @i{file}
  681: Loads the image @i{file} and leaves all further command-line arguments
  682: to the image (instead of processing them as engine options).  This is
  683: useful for building executable application images on Unix, built with
  684: @code{gforthmi --application ...}.
  685: 
  686: @cindex --path, command-line option
  687: @cindex -p, command-line option
  688: @item --path @i{path}
  689: @itemx -p @i{path}
  690: Uses @i{path} for searching the image file and Forth source code files
  691: instead of the default in the environment variable @code{GFORTHPATH} or
  692: the path specified at installation time (e.g.,
  693: @file{/usr/local/share/gforth/0.2.0:.}). A path is given as a list of
  694: directories, separated by @samp{:} (on Unix) or @samp{;} (on other OSs).
  695: 
  696: @cindex --dictionary-size, command-line option
  697: @cindex -m, command-line option
  698: @cindex @i{size} parameters for command-line options
  699: @cindex size of the dictionary and the stacks
  700: @item --dictionary-size @i{size}
  701: @itemx -m @i{size}
  702: Allocate @i{size} space for the Forth dictionary space instead of
  703: using the default specified in the image (typically 256K). The
  704: @i{size} specification for this and subsequent options consists of
  705: an integer and a unit (e.g.,
  706: @code{4M}). The unit can be one of @code{b} (bytes), @code{e} (element
  707: size, in this case Cells), @code{k} (kilobytes), @code{M} (Megabytes),
  708: @code{G} (Gigabytes), and @code{T} (Terabytes). If no unit is specified,
  709: @code{e} is used.
  710: 
  711: @cindex --data-stack-size, command-line option
  712: @cindex -d, command-line option
  713: @item --data-stack-size @i{size}
  714: @itemx -d @i{size}
  715: Allocate @i{size} space for the data stack instead of using the
  716: default specified in the image (typically 16K).
  717: 
  718: @cindex --return-stack-size, command-line option
  719: @cindex -r, command-line option
  720: @item --return-stack-size @i{size}
  721: @itemx -r @i{size}
  722: Allocate @i{size} space for the return stack instead of using the
  723: default specified in the image (typically 15K).
  724: 
  725: @cindex --fp-stack-size, command-line option
  726: @cindex -f, command-line option
  727: @item --fp-stack-size @i{size}
  728: @itemx -f @i{size}
  729: Allocate @i{size} space for the floating point stack instead of
  730: using the default specified in the image (typically 15.5K). In this case
  731: the unit specifier @code{e} refers to floating point numbers.
  732: 
  733: @cindex --locals-stack-size, command-line option
  734: @cindex -l, command-line option
  735: @item --locals-stack-size @i{size}
  736: @itemx -l @i{size}
  737: Allocate @i{size} space for the locals stack instead of using the
  738: default specified in the image (typically 14.5K).
  739: 
  740: @cindex -h, command-line option
  741: @cindex --help, command-line option
  742: @item --help
  743: @itemx -h
  744: Print a message about the command-line options
  745: 
  746: @cindex -v, command-line option
  747: @cindex --version, command-line option
  748: @item --version
  749: @itemx -v
  750: Print version and exit
  751: 
  752: @cindex --debug, command-line option
  753: @item --debug
  754: Print some information useful for debugging on startup.
  755: 
  756: @cindex --offset-image, command-line option
  757: @item --offset-image
  758: Start the dictionary at a slightly different position than would be used
  759: otherwise (useful for creating data-relocatable images,
  760: @pxref{Data-Relocatable Image Files}).
  761: 
  762: @cindex --no-offset-im, command-line option
  763: @item --no-offset-im
  764: Start the dictionary at the normal position.
  765: 
  766: @cindex --clear-dictionary, command-line option
  767: @item --clear-dictionary
  768: Initialize all bytes in the dictionary to 0 before loading the image
  769: (@pxref{Data-Relocatable Image Files}).
  770: 
  771: @cindex --die-on-signal, command-line-option
  772: @item --die-on-signal
  773: Normally Gforth handles most signals (e.g., the user interrupt SIGINT,
  774: or the segmentation violation SIGSEGV) by translating it into a Forth
  775: @code{THROW}. With this option, Gforth exits if it receives such a
  776: signal. This option is useful when the engine and/or the image might be
  777: severely broken (such that it causes another signal before recovering
  778: from the first); this option avoids endless loops in such cases.
  779: 
  780: @cindex --no-dynamic, command-line option
  781: @cindex --dynamic, command-line option
  782: @item --no-dynamic
  783: @item --dynamic
  784: Disable or enable dynamic superinstructions with replication
  785: (@pxref{Dynamic Superinstructions}).
  786: 
  787: @cindex --no-super, command-line option
  788: @item --no-super
  789: Disable dynamic superinstructions, use just dynamic replication; this is
  790: useful if you want to patch threaded code (@pxref{Dynamic
  791: Superinstructions}).
  792: 
  793: @cindex --ss-number, command-line option
  794: @item --ss-number=@var{N}
  795: Use only the first @var{N} static superinstructions compiled into the
  796: engine (default: use them all; note that only @code{gforth-fast} has
  797: any).  This option is useful for measuring the performance impact of
  798: static superinstructions.
  799: 
  800: @cindex --ss-min-..., command-line options
  801: @item --ss-min-codesize
  802: @item --ss-min-ls
  803: @item --ss-min-lsu
  804: @item --ss-min-nexts
  805: Use specified metric for determining the cost of a primitive or static
  806: superinstruction for static superinstruction selection.  @code{Codesize}
  807: is the native code size of the primive or static superinstruction,
  808: @code{ls} is the number of loads and stores, @code{lsu} is the number of
  809: loads, stores, and updates, and @code{nexts} is the number of dispatches
  810: (not taking dynamic superinstructions into account), i.e. every
  811: primitive or static superinstruction has cost 1. Default:
  812: @code{codesize} if you use dynamic code generation, otherwise
  813: @code{nexts}.
  814: 
  815: @cindex --ss-greedy, command-line option
  816: @item --ss-greedy
  817: This option is useful for measuring the performance impact of static
  818: superinstructions.  By default, an optimal shortest-path algorithm is
  819: used for selecting static superinstructions.  With @option{--ss-greedy}
  820: this algorithm is modified to assume that anything after the static
  821: superinstruction currently under consideration is not combined into
  822: static superinstructions.  With @option{--ss-min-nexts} this produces
  823: the same result as a greedy algorithm that always selects the longest
  824: superinstruction available at the moment.  E.g., if there are
  825: superinstructions AB and BCD, then for the sequence A B C D the optimal
  826: algorithm will select A BCD and the greedy algorithm will select AB C D.
  827: 
  828: @cindex --print-metrics, command-line option
  829: @item --print-metrics
  830: Prints some metrics used during static superinstruction selection:
  831: @code{code size} is the actual size of the dynamically generated code.
  832: @code{Metric codesize} is the sum of the codesize metrics as seen by
  833: static superinstruction selection; there is a difference from @code{code
  834: size}, because not all primitives and static superinstructions are
  835: compiled into dynamically generated code, and because of markers.  The
  836: other metrics correspond to the @option{ss-min-...} options.  This
  837: option is useful for evaluating the effects of the @option{--ss-...}
  838: options.
  839: 
  840: @end table
  841: 
  842: @cindex loading files at startup
  843: @cindex executing code on startup
  844: @cindex batch processing with Gforth
  845: As explained above, the image-specific command-line arguments for the
  846: default image @file{gforth.fi} consist of a sequence of filenames and
  847: @code{-e @var{forth-code}} options that are interpreted in the sequence
  848: in which they are given. The @code{-e @var{forth-code}} or
  849: @code{--evaluate @var{forth-code}} option evaluates the Forth code. This
  850: option takes only one argument; if you want to evaluate more Forth
  851: words, you have to quote them or use @code{-e} several times. To exit
  852: after processing the command line (instead of entering interactive mode)
  853: append @code{-e bye} to the command line.  You can also process the
  854: command-line arguments with a Forth program (@pxref{OS command line
  855: arguments}).
  856: 
  857: @cindex versions, invoking other versions of Gforth
  858: If you have several versions of Gforth installed, @code{gforth} will
  859: invoke the version that was installed last. @code{gforth-@i{version}}
  860: invokes a specific version. If your environment contains the variable
  861: @code{GFORTHPATH}, you may want to override it by using the
  862: @code{--path} option.
  863: 
  864: Not yet implemented:
  865: On startup the system first executes the system initialization file
  866: (unless the option @code{--no-init-file} is given; note that the system
  867: resulting from using this option may not be ANS Forth conformant). Then
  868: the user initialization file @file{.gforth.fs} is executed, unless the
  869: option @code{--no-rc} is given; this file is searched for in @file{.},
  870: then in @file{~}, then in the normal path (see above).
  871: 
  872: 
  873: 
  874: @comment ----------------------------------------------
  875: @node Leaving Gforth, Command-line editing, Invoking Gforth, Gforth Environment
  876: @section Leaving Gforth
  877: @cindex Gforth - leaving
  878: @cindex leaving Gforth
  879: 
  880: You can leave Gforth by typing @code{bye} or @kbd{Ctrl-d} (at the start
  881: of a line) or (if you invoked Gforth with the @code{--die-on-signal}
  882: option) @kbd{Ctrl-c}. When you leave Gforth, all of your definitions and
  883: data are discarded.  For ways of saving the state of the system before
  884: leaving Gforth see @ref{Image Files}.
  885: 
  886: doc-bye
  887: 
  888: 
  889: @comment ----------------------------------------------
  890: @node Command-line editing, Environment variables, Leaving Gforth, Gforth Environment
  891: @section Command-line editing
  892: @cindex command-line editing
  893: 
  894: Gforth maintains a history file that records every line that you type to
  895: the text interpreter. This file is preserved between sessions, and is
  896: used to provide a command-line recall facility; if you type @kbd{Ctrl-P}
  897: repeatedly you can recall successively older commands from this (or
  898: previous) session(s). The full list of command-line editing facilities is:
  899: 
  900: @itemize @bullet
  901: @item
  902: @kbd{Ctrl-p} (``previous'') (or up-arrow) to recall successively older
  903: commands from the history buffer.
  904: @item
  905: @kbd{Ctrl-n} (``next'') (or down-arrow) to recall successively newer commands
  906: from the history buffer.
  907: @item
  908: @kbd{Ctrl-f} (or right-arrow) to move the cursor right, non-destructively.
  909: @item
  910: @kbd{Ctrl-b} (or left-arrow) to move the cursor left, non-destructively.
  911: @item
  912: @kbd{Ctrl-h} (backspace) to delete the character to the left of the cursor,
  913: closing up the line.
  914: @item
  915: @kbd{Ctrl-k} to delete (``kill'') from the cursor to the end of the line.
  916: @item
  917: @kbd{Ctrl-a} to move the cursor to the start of the line.
  918: @item
  919: @kbd{Ctrl-e} to move the cursor to the end of the line.
  920: @item
  921: @key{RET} (@kbd{Ctrl-m}) or @key{LFD} (@kbd{Ctrl-j}) to submit the current
  922: line.
  923: @item
  924: @key{TAB} to step through all possible full-word completions of the word
  925: currently being typed.
  926: @item
  927: @kbd{Ctrl-d} on an empty line line to terminate Gforth (gracefully,
  928: using @code{bye}). 
  929: @item
  930: @kbd{Ctrl-x} (or @code{Ctrl-d} on a non-empty line) to delete the
  931: character under the cursor.
  932: @end itemize
  933: 
  934: When editing, displayable characters are inserted to the left of the
  935: cursor position; the line is always in ``insert'' (as opposed to
  936: ``overstrike'') mode.
  937: 
  938: @cindex history file
  939: @cindex @file{.gforth-history}
  940: On Unix systems, the history file is @file{~/.gforth-history} by
  941: default@footnote{i.e. it is stored in the user's home directory.}. You
  942: can find out the name and location of your history file using:
  943: 
  944: @example 
  945: history-file type \ Unix-class systems
  946: 
  947: history-file type \ Other systems
  948: history-dir  type
  949: @end example
  950: 
  951: If you enter long definitions by hand, you can use a text editor to
  952: paste them out of the history file into a Forth source file for reuse at
  953: a later time.
  954: 
  955: Gforth never trims the size of the history file, so you should do this
  956: periodically, if necessary.
  957: 
  958: @comment this is all defined in history.fs
  959: @comment NAC TODO the ctrl-D behaviour can either do a bye or a beep.. how is that option
  960: @comment chosen?
  961: 
  962: 
  963: @comment ----------------------------------------------
  964: @node Environment variables, Gforth Files, Command-line editing, Gforth Environment
  965: @section Environment variables
  966: @cindex environment variables
  967: 
  968: Gforth uses these environment variables:
  969: 
  970: @itemize @bullet
  971: @item
  972: @cindex @code{GFORTHHIST} -- environment variable
  973: @code{GFORTHHIST} -- (Unix systems only) specifies the directory in which to
  974: open/create the history file, @file{.gforth-history}. Default:
  975: @code{$HOME}.
  976: 
  977: @item
  978: @cindex @code{GFORTHPATH} -- environment variable
  979: @code{GFORTHPATH} -- specifies the path used when searching for the gforth image file and
  980: for Forth source-code files.
  981: 
  982: @item
  983: @cindex @code{LANG} -- environment variable
  984: @code{LANG} -- see @code{LC_CTYPE}
  985: 
  986: @item
  987: @cindex @code{LC_ALL} -- environment variable
  988: @code{LC_ALL} -- see @code{LC_CTYPE}
  989: 
  990: @item
  991: @cindex @code{LC_CTYPE} -- environment variable
  992: @code{LC_CTYPE} -- If this variable contains ``UTF-8'' on Gforth
  993: startup, Gforth uses the UTF-8 encoding for strings internally and
  994: expects its input and produces its output in UTF-8 encoding, otherwise
  995: the encoding is 8bit (see @pxref{Xchars and Unicode}).  If this
  996: environment variable is unset, Gforth looks in @code{LC_ALL}, and if
  997: that is unset, in @code{LANG}.
  998: 
  999: @item
 1000: @cindex @code{GFORTHSYSTEMPREFIX} -- environment variable
 1001: 
 1002: @code{GFORTHSYSTEMPREFIX} -- specifies what to prepend to the argument
 1003: of @code{system} before passing it to C's @code{system()}.  Default:
 1004: @code{"./$COMSPEC /c "} on Windows, @code{""} on other OSs.  The prefix
 1005: and the command are directly concatenated, so if a space between them is
 1006: necessary, append it to the prefix.
 1007: 
 1008: @item
 1009: @cindex @code{GFORTH} -- environment variable
 1010: @code{GFORTH} -- used by @file{gforthmi}, @xref{gforthmi}.
 1011: 
 1012: @item
 1013: @cindex @code{GFORTHD} -- environment variable
 1014: @code{GFORTHD} -- used by @file{gforthmi}, @xref{gforthmi}.
 1015: 
 1016: @item
 1017: @cindex @code{TMP}, @code{TEMP} - environment variable
 1018: @code{TMP}, @code{TEMP} - (non-Unix systems only) used as a potential
 1019: location for the history file.
 1020: @end itemize
 1021: 
 1022: @comment also POSIXELY_CORRECT LINES COLUMNS HOME but no interest in
 1023: @comment mentioning these.
 1024: 
 1025: All the Gforth environment variables default to sensible values if they
 1026: are not set.
 1027: 
 1028: 
 1029: @comment ----------------------------------------------
 1030: @node Gforth Files, Gforth in pipes, Environment variables, Gforth Environment
 1031: @section Gforth files
 1032: @cindex Gforth files
 1033: 
 1034: When you install Gforth on a Unix system, it installs files in these
 1035: locations by default:
 1036: 
 1037: @itemize @bullet
 1038: @item
 1039: @file{/usr/local/bin/gforth}
 1040: @item
 1041: @file{/usr/local/bin/gforthmi}
 1042: @item
 1043: @file{/usr/local/man/man1/gforth.1} - man page.
 1044: @item
 1045: @file{/usr/local/info} - the Info version of this manual.
 1046: @item
 1047: @file{/usr/local/lib/gforth/<version>/...} - Gforth @file{.fi} files.
 1048: @item
 1049: @file{/usr/local/share/gforth/<version>/TAGS} - Emacs TAGS file.
 1050: @item
 1051: @file{/usr/local/share/gforth/<version>/...} - Gforth source files.
 1052: @item
 1053: @file{.../emacs/site-lisp/gforth.el} - Emacs gforth mode.
 1054: @end itemize
 1055: 
 1056: You can select different places for installation by using
 1057: @code{configure} options (listed with @code{configure --help}).
 1058: 
 1059: @comment ----------------------------------------------
 1060: @node Gforth in pipes, Startup speed, Gforth Files, Gforth Environment
 1061: @section Gforth in pipes
 1062: @cindex pipes, Gforth as part of
 1063: 
 1064: Gforth can be used in pipes created elsewhere (described here).  It can
 1065: also create pipes on its own (@pxref{Pipes}).
 1066: 
 1067: @cindex input from pipes
 1068: If you pipe into Gforth, your program should read with @code{read-file}
 1069: or @code{read-line} from @code{stdin} (@pxref{General files}).
 1070: @code{Key} does not recognize the end of input.  Words like
 1071: @code{accept} echo the input and are therefore usually not useful for
 1072: reading from a pipe.  You have to invoke the Forth program with an OS
 1073: command-line option, as you have no chance to use the Forth command line
 1074: (the text interpreter would try to interpret the pipe input).
 1075: 
 1076: @cindex output in pipes
 1077: You can output to a pipe with @code{type}, @code{emit}, @code{cr} etc.
 1078: 
 1079: @cindex silent exiting from Gforth
 1080: When you write to a pipe that has been closed at the other end, Gforth
 1081: receives a SIGPIPE signal (``pipe broken'').  Gforth translates this
 1082: into the exception @code{broken-pipe-error}.  If your application does
 1083: not catch that exception, the system catches it and exits, usually
 1084: silently (unless you were working on the Forth command line; then it
 1085: prints an error message and exits).  This is usually the desired
 1086: behaviour.
 1087: 
 1088: If you do not like this behaviour, you have to catch the exception
 1089: yourself, and react to it.
 1090: 
 1091: Here's an example of an invocation of Gforth that is usable in a pipe:
 1092: 
 1093: @example
 1094: gforth -e ": foo begin pad dup 10 stdin read-file throw dup while \
 1095:  type repeat ; foo bye"
 1096: @end example
 1097: 
 1098: This example just copies the input verbatim to the output.  A very
 1099: simple pipe containing this example looks like this:
 1100: 
 1101: @example
 1102: cat startup.fs |
 1103: gforth -e ": foo begin pad dup 80 stdin read-file throw dup while \
 1104:  type repeat ; foo bye"|
 1105: head
 1106: @end example
 1107: 
 1108: @cindex stderr and pipes
 1109: Pipes involving Gforth's @code{stderr} output do not work.
 1110: 
 1111: @comment ----------------------------------------------
 1112: @node Startup speed,  , Gforth in pipes, Gforth Environment
 1113: @section Startup speed
 1114: @cindex Startup speed
 1115: @cindex speed, startup
 1116: 
 1117: If Gforth is used for CGI scripts or in shell scripts, its startup
 1118: speed may become a problem.  On a 300MHz 21064a under Linux-2.2.13 with
 1119: glibc-2.0.7, @code{gforth -e bye} takes about 24.6ms user and 11.3ms
 1120: system time.
 1121: 
 1122: If startup speed is a problem, you may consider the following ways to
 1123: improve it; or you may consider ways to reduce the number of startups
 1124: (for example, by using Fast-CGI).
 1125: 
 1126: An easy step that influences Gforth startup speed is the use of the
 1127: @option{--no-dynamic} option; this decreases image loading speed, but
 1128: increases compile-time and run-time.
 1129: 
 1130: Another step to improve startup speed is to statically link Gforth, by
 1131: building it with @code{XLDFLAGS=-static}.  This requires more memory for
 1132: the code and will therefore slow down the first invocation, but
 1133: subsequent invocations avoid the dynamic linking overhead.  Another
 1134: disadvantage is that Gforth won't profit from library upgrades.  As a
 1135: result, @code{gforth-static -e bye} takes about 17.1ms user and
 1136: 8.2ms system time.
 1137: 
 1138: The next step to improve startup speed is to use a non-relocatable image
 1139: (@pxref{Non-Relocatable Image Files}).  You can create this image with
 1140: @code{gforth -e "savesystem gforthnr.fi bye"} and later use it with
 1141: @code{gforth -i gforthnr.fi ...}.  This avoids the relocation overhead
 1142: and a part of the copy-on-write overhead.  The disadvantage is that the
 1143: non-relocatable image does not work if the OS gives Gforth a different
 1144: address for the dictionary, for whatever reason; so you better provide a
 1145: fallback on a relocatable image.  @code{gforth-static -i gforthnr.fi -e
 1146: bye} takes about 15.3ms user and 7.5ms system time.
 1147: 
 1148: The final step is to disable dictionary hashing in Gforth.  Gforth
 1149: builds the hash table on startup, which takes much of the startup
 1150: overhead. You can do this by commenting out the @code{include hash.fs}
 1151: in @file{startup.fs} and everything that requires @file{hash.fs} (at the
 1152: moment @file{table.fs} and @file{ekey.fs}) and then doing @code{make}.
 1153: The disadvantages are that functionality like @code{table} and
 1154: @code{ekey} is missing and that text interpretation (e.g., compiling)
 1155: now takes much longer. So, you should only use this method if there is
 1156: no significant text interpretation to perform (the script should be
 1157: compiled into the image, amongst other things).  @code{gforth-static -i
 1158: gforthnrnh.fi -e bye} takes about 2.1ms user and 6.1ms system time.
 1159: 
 1160: @c ******************************************************************
 1161: @node Tutorial, Introduction, Gforth Environment, Top
 1162: @chapter Forth Tutorial
 1163: @cindex Tutorial
 1164: @cindex Forth Tutorial
 1165: 
 1166: @c Topics from nac's Introduction that could be mentioned:
 1167: @c press <ret> after each line
 1168: @c Prompt
 1169: @c numbers vs. words in dictionary on text interpretation
 1170: @c what happens on redefinition
 1171: @c parsing words (in particular, defining words)
 1172: 
 1173: The difference of this chapter from the Introduction
 1174: (@pxref{Introduction}) is that this tutorial is more fast-paced, should
 1175: be used while sitting in front of a computer, and covers much more
 1176: material, but does not explain how the Forth system works.
 1177: 
 1178: This tutorial can be used with any ANS-compliant Forth; any
 1179: Gforth-specific features are marked as such and you can skip them if you
 1180: work with another Forth.  This tutorial does not explain all features of
 1181: Forth, just enough to get you started and give you some ideas about the
 1182: facilities available in Forth.  Read the rest of the manual and the
 1183: standard when you are through this.
 1184: 
 1185: The intended way to use this tutorial is that you work through it while
 1186: sitting in front of the console, take a look at the examples and predict
 1187: what they will do, then try them out; if the outcome is not as expected,
 1188: find out why (e.g., by trying out variations of the example), so you
 1189: understand what's going on.  There are also some assignments that you
 1190: should solve.
 1191: 
 1192: This tutorial assumes that you have programmed before and know what,
 1193: e.g., a loop is.
 1194: 
 1195: @c !! explain compat library
 1196: 
 1197: @menu
 1198: * Starting Gforth Tutorial::    
 1199: * Syntax Tutorial::             
 1200: * Crash Course Tutorial::       
 1201: * Stack Tutorial::              
 1202: * Arithmetics Tutorial::        
 1203: * Stack Manipulation Tutorial::  
 1204: * Using files for Forth code Tutorial::  
 1205: * Comments Tutorial::           
 1206: * Colon Definitions Tutorial::  
 1207: * Decompilation Tutorial::      
 1208: * Stack-Effect Comments Tutorial::  
 1209: * Types Tutorial::              
 1210: * Factoring Tutorial::          
 1211: * Designing the stack effect Tutorial::  
 1212: * Local Variables Tutorial::    
 1213: * Conditional execution Tutorial::  
 1214: * Flags and Comparisons Tutorial::  
 1215: * General Loops Tutorial::      
 1216: * Counted loops Tutorial::      
 1217: * Recursion Tutorial::          
 1218: * Leaving definitions or loops Tutorial::  
 1219: * Return Stack Tutorial::       
 1220: * Memory Tutorial::             
 1221: * Characters and Strings Tutorial::  
 1222: * Alignment Tutorial::          
 1223: * Files Tutorial::              
 1224: * Interpretation and Compilation Semantics and Immediacy Tutorial::  
 1225: * Execution Tokens Tutorial::   
 1226: * Exceptions Tutorial::         
 1227: * Defining Words Tutorial::     
 1228: * Arrays and Records Tutorial::  
 1229: * POSTPONE Tutorial::           
 1230: * Literal Tutorial::            
 1231: * Advanced macros Tutorial::    
 1232: * Compilation Tokens Tutorial::  
 1233: * Wordlists and Search Order Tutorial::  
 1234: @end menu
 1235: 
 1236: @node Starting Gforth Tutorial, Syntax Tutorial, Tutorial, Tutorial
 1237: @section Starting Gforth
 1238: @cindex starting Gforth tutorial
 1239: You can start Gforth by typing its name:
 1240: 
 1241: @example
 1242: gforth
 1243: @end example
 1244: 
 1245: That puts you into interactive mode; you can leave Gforth by typing
 1246: @code{bye}.  While in Gforth, you can edit the command line and access
 1247: the command line history with cursor keys, similar to bash.
 1248: 
 1249: 
 1250: @node Syntax Tutorial, Crash Course Tutorial, Starting Gforth Tutorial, Tutorial
 1251: @section Syntax
 1252: @cindex syntax tutorial
 1253: 
 1254: A @dfn{word} is a sequence of arbitrary characters (expcept white
 1255: space).  Words are separated by white space.  E.g., each of the
 1256: following lines contains exactly one word:
 1257: 
 1258: @example
 1259: word
 1260: !@@#$%^&*()
 1261: 1234567890
 1262: 5!a
 1263: @end example
 1264: 
 1265: A frequent beginner's error is to leave away necessary white space,
 1266: resulting in an error like @samp{Undefined word}; so if you see such an
 1267: error, check if you have put spaces wherever necessary.
 1268: 
 1269: @example
 1270: ." hello, world" \ correct
 1271: ."hello, world"  \ gives an "Undefined word" error
 1272: @end example
 1273: 
 1274: Gforth and most other Forth systems ignore differences in case (they are
 1275: case-insensitive), i.e., @samp{word} is the same as @samp{Word}.  If
 1276: your system is case-sensitive, you may have to type all the examples
 1277: given here in upper case.
 1278: 
 1279: 
 1280: @node Crash Course Tutorial, Stack Tutorial, Syntax Tutorial, Tutorial
 1281: @section Crash Course
 1282: 
 1283: Type
 1284: 
 1285: @example
 1286: 0 0 !
 1287: here execute
 1288: ' catch >body 20 erase abort
 1289: ' (quit) >body 20 erase
 1290: @end example
 1291: 
 1292: The last two examples are guaranteed to destroy parts of Gforth (and
 1293: most other systems), so you better leave Gforth afterwards (if it has
 1294: not finished by itself).  On some systems you may have to kill gforth
 1295: from outside (e.g., in Unix with @code{kill}).
 1296: 
 1297: Now that you know how to produce crashes (and that there's not much to
 1298: them), let's learn how to produce meaningful programs.
 1299: 
 1300: 
 1301: @node Stack Tutorial, Arithmetics Tutorial, Crash Course Tutorial, Tutorial
 1302: @section Stack
 1303: @cindex stack tutorial
 1304: 
 1305: The most obvious feature of Forth is the stack.  When you type in a
 1306: number, it is pushed on the stack.  You can display the content of the
 1307: stack with @code{.s}.
 1308: 
 1309: @example
 1310: 1 2 .s
 1311: 3 .s
 1312: @end example
 1313: 
 1314: @code{.s} displays the top-of-stack to the right, i.e., the numbers
 1315: appear in @code{.s} output as they appeared in the input.
 1316: 
 1317: You can print the top of stack element with @code{.}.
 1318: 
 1319: @example
 1320: 1 2 3 . . .
 1321: @end example
 1322: 
 1323: In general, words consume their stack arguments (@code{.s} is an
 1324: exception).
 1325: 
 1326: @quotation Assignment
 1327: What does the stack contain after @code{5 6 7 .}?
 1328: @end quotation
 1329: 
 1330: 
 1331: @node Arithmetics Tutorial, Stack Manipulation Tutorial, Stack Tutorial, Tutorial
 1332: @section Arithmetics
 1333: @cindex arithmetics tutorial
 1334: 
 1335: The words @code{+}, @code{-}, @code{*}, @code{/}, and @code{mod} always
 1336: operate on the top two stack items:
 1337: 
 1338: @example
 1339: 2 2 .s
 1340: + .s
 1341: .
 1342: 2 1 - .
 1343: 7 3 mod .
 1344: @end example
 1345: 
 1346: The operands of @code{-}, @code{/}, and @code{mod} are in the same order
 1347: as in the corresponding infix expression (this is generally the case in
 1348: Forth).
 1349: 
 1350: Parentheses are superfluous (and not available), because the order of
 1351: the words unambiguously determines the order of evaluation and the
 1352: operands:
 1353: 
 1354: @example
 1355: 3 4 + 5 * .
 1356: 3 4 5 * + .
 1357: @end example
 1358: 
 1359: @quotation Assignment
 1360: What are the infix expressions corresponding to the Forth code above?
 1361: Write @code{6-7*8+9} in Forth notation@footnote{This notation is also
 1362: known as Postfix or RPN (Reverse Polish Notation).}.
 1363: @end quotation
 1364: 
 1365: To change the sign, use @code{negate}:
 1366: 
 1367: @example
 1368: 2 negate .
 1369: @end example
 1370: 
 1371: @quotation Assignment
 1372: Convert -(-3)*4-5 to Forth.
 1373: @end quotation
 1374: 
 1375: @code{/mod} performs both @code{/} and @code{mod}.
 1376: 
 1377: @example
 1378: 7 3 /mod . .
 1379: @end example
 1380: 
 1381: Reference: @ref{Arithmetic}.
 1382: 
 1383: 
 1384: @node Stack Manipulation Tutorial, Using files for Forth code Tutorial, Arithmetics Tutorial, Tutorial
 1385: @section Stack Manipulation
 1386: @cindex stack manipulation tutorial
 1387: 
 1388: Stack manipulation words rearrange the data on the stack.
 1389: 
 1390: @example
 1391: 1 .s drop .s
 1392: 1 .s dup .s drop drop .s
 1393: 1 2 .s over .s drop drop drop
 1394: 1 2 .s swap .s drop drop
 1395: 1 2 3 .s rot .s drop drop drop
 1396: @end example
 1397: 
 1398: These are the most important stack manipulation words.  There are also
 1399: variants that manipulate twice as many stack items:
 1400: 
 1401: @example
 1402: 1 2 3 4 .s 2swap .s 2drop 2drop
 1403: @end example
 1404: 
 1405: Two more stack manipulation words are:
 1406: 
 1407: @example
 1408: 1 2 .s nip .s drop
 1409: 1 2 .s tuck .s 2drop drop
 1410: @end example
 1411: 
 1412: @quotation Assignment
 1413: Replace @code{nip} and @code{tuck} with combinations of other stack
 1414: manipulation words.
 1415: 
 1416: @example
 1417: Given:          How do you get:
 1418: 1 2 3           3 2 1           
 1419: 1 2 3           1 2 3 2                 
 1420: 1 2 3           1 2 3 3                 
 1421: 1 2 3           1 3 3           
 1422: 1 2 3           2 1 3           
 1423: 1 2 3 4         4 3 2 1         
 1424: 1 2 3           1 2 3 1 2 3             
 1425: 1 2 3 4         1 2 3 4 1 2             
 1426: 1 2 3
 1427: 1 2 3           1 2 3 4                 
 1428: 1 2 3           1 3             
 1429: @end example
 1430: @end quotation
 1431: 
 1432: @example
 1433: 5 dup * .
 1434: @end example
 1435: 
 1436: @quotation Assignment
 1437: Write 17^3 and 17^4 in Forth, without writing @code{17} more than once.
 1438: Write a piece of Forth code that expects two numbers on the stack
 1439: (@var{a} and @var{b}, with @var{b} on top) and computes
 1440: @code{(a-b)(a+1)}.
 1441: @end quotation
 1442: 
 1443: Reference: @ref{Stack Manipulation}.
 1444: 
 1445: 
 1446: @node Using files for Forth code Tutorial, Comments Tutorial, Stack Manipulation Tutorial, Tutorial
 1447: @section Using files for Forth code
 1448: @cindex loading Forth code, tutorial
 1449: @cindex files containing Forth code, tutorial
 1450: 
 1451: While working at the Forth command line is convenient for one-line
 1452: examples and short one-off code, you probably want to store your source
 1453: code in files for convenient editing and persistence.  You can use your
 1454: favourite editor (Gforth includes Emacs support, @pxref{Emacs and
 1455: Gforth}) to create @var{file.fs} and use
 1456: 
 1457: @example
 1458: s" @var{file.fs}" included
 1459: @end example
 1460: 
 1461: to load it into your Forth system.  The file name extension I use for
 1462: Forth files is @samp{.fs}.
 1463: 
 1464: You can easily start Gforth with some files loaded like this:
 1465: 
 1466: @example
 1467: gforth @var{file1.fs} @var{file2.fs}
 1468: @end example
 1469: 
 1470: If an error occurs during loading these files, Gforth terminates,
 1471: whereas an error during @code{INCLUDED} within Gforth usually gives you
 1472: a Gforth command line.  Starting the Forth system every time gives you a
 1473: clean start every time, without interference from the results of earlier
 1474: tries.
 1475: 
 1476: I often put all the tests in a file, then load the code and run the
 1477: tests with
 1478: 
 1479: @example
 1480: gforth @var{code.fs} @var{tests.fs} -e bye
 1481: @end example
 1482: 
 1483: (often by performing this command with @kbd{C-x C-e} in Emacs).  The
 1484: @code{-e bye} ensures that Gforth terminates afterwards so that I can
 1485: restart this command without ado.
 1486: 
 1487: The advantage of this approach is that the tests can be repeated easily
 1488: every time the program ist changed, making it easy to catch bugs
 1489: introduced by the change.
 1490: 
 1491: Reference: @ref{Forth source files}.
 1492: 
 1493: 
 1494: @node Comments Tutorial, Colon Definitions Tutorial, Using files for Forth code Tutorial, Tutorial
 1495: @section Comments
 1496: @cindex comments tutorial
 1497: 
 1498: @example
 1499: \ That's a comment; it ends at the end of the line
 1500: ( Another comment; it ends here: )  .s
 1501: @end example
 1502: 
 1503: @code{\} and @code{(} are ordinary Forth words and therefore have to be
 1504: separated with white space from the following text.
 1505: 
 1506: @example
 1507: \This gives an "Undefined word" error
 1508: @end example
 1509: 
 1510: The first @code{)} ends a comment started with @code{(}, so you cannot
 1511: nest @code{(}-comments; and you cannot comment out text containing a
 1512: @code{)} with @code{( ... )}@footnote{therefore it's a good idea to
 1513: avoid @code{)} in word names.}.
 1514: 
 1515: I use @code{\}-comments for descriptive text and for commenting out code
 1516: of one or more line; I use @code{(}-comments for describing the stack
 1517: effect, the stack contents, or for commenting out sub-line pieces of
 1518: code.
 1519: 
 1520: The Emacs mode @file{gforth.el} (@pxref{Emacs and Gforth}) supports
 1521: these uses by commenting out a region with @kbd{C-x \}, uncommenting a
 1522: region with @kbd{C-u C-x \}, and filling a @code{\}-commented region
 1523: with @kbd{M-q}.
 1524: 
 1525: Reference: @ref{Comments}.
 1526: 
 1527: 
 1528: @node Colon Definitions Tutorial, Decompilation Tutorial, Comments Tutorial, Tutorial
 1529: @section Colon Definitions
 1530: @cindex colon definitions, tutorial
 1531: @cindex definitions, tutorial
 1532: @cindex procedures, tutorial
 1533: @cindex functions, tutorial
 1534: 
 1535: are similar to procedures and functions in other programming languages.
 1536: 
 1537: @example
 1538: : squared ( n -- n^2 )
 1539:    dup * ;
 1540: 5 squared .
 1541: 7 squared .
 1542: @end example
 1543: 
 1544: @code{:} starts the colon definition; its name is @code{squared}.  The
 1545: following comment describes its stack effect.  The words @code{dup *}
 1546: are not executed, but compiled into the definition.  @code{;} ends the
 1547: colon definition.
 1548: 
 1549: The newly-defined word can be used like any other word, including using
 1550: it in other definitions:
 1551: 
 1552: @example
 1553: : cubed ( n -- n^3 )
 1554:    dup squared * ;
 1555: -5 cubed .
 1556: : fourth-power ( n -- n^4 )
 1557:    squared squared ;
 1558: 3 fourth-power .
 1559: @end example
 1560: 
 1561: @quotation Assignment
 1562: Write colon definitions for @code{nip}, @code{tuck}, @code{negate}, and
 1563: @code{/mod} in terms of other Forth words, and check if they work (hint:
 1564: test your tests on the originals first).  Don't let the
 1565: @samp{redefined}-Messages spook you, they are just warnings.
 1566: @end quotation
 1567: 
 1568: Reference: @ref{Colon Definitions}.
 1569: 
 1570: 
 1571: @node Decompilation Tutorial, Stack-Effect Comments Tutorial, Colon Definitions Tutorial, Tutorial
 1572: @section Decompilation
 1573: @cindex decompilation tutorial
 1574: @cindex see tutorial
 1575: 
 1576: You can decompile colon definitions with @code{see}:
 1577: 
 1578: @example
 1579: see squared
 1580: see cubed
 1581: @end example
 1582: 
 1583: In Gforth @code{see} shows you a reconstruction of the source code from
 1584: the executable code.  Informations that were present in the source, but
 1585: not in the executable code, are lost (e.g., comments).
 1586: 
 1587: You can also decompile the predefined words:
 1588: 
 1589: @example
 1590: see .
 1591: see +
 1592: @end example
 1593: 
 1594: 
 1595: @node Stack-Effect Comments Tutorial, Types Tutorial, Decompilation Tutorial, Tutorial
 1596: @section Stack-Effect Comments
 1597: @cindex stack-effect comments, tutorial
 1598: @cindex --, tutorial
 1599: By convention the comment after the name of a definition describes the
 1600: stack effect: The part in from of the @samp{--} describes the state of
 1601: the stack before the execution of the definition, i.e., the parameters
 1602: that are passed into the colon definition; the part behind the @samp{--}
 1603: is the state of the stack after the execution of the definition, i.e.,
 1604: the results of the definition.  The stack comment only shows the top
 1605: stack items that the definition accesses and/or changes.
 1606: 
 1607: You should put a correct stack effect on every definition, even if it is
 1608: just @code{( -- )}.  You should also add some descriptive comment to
 1609: more complicated words (I usually do this in the lines following
 1610: @code{:}).  If you don't do this, your code becomes unreadable (because
 1611: you have to work through every definition before you can understand
 1612: any).
 1613: 
 1614: @quotation Assignment
 1615: The stack effect of @code{swap} can be written like this: @code{x1 x2 --
 1616: x2 x1}.  Describe the stack effect of @code{-}, @code{drop}, @code{dup},
 1617: @code{over}, @code{rot}, @code{nip}, and @code{tuck}.  Hint: When you
 1618: are done, you can compare your stack effects to those in this manual
 1619: (@pxref{Word Index}).
 1620: @end quotation
 1621: 
 1622: Sometimes programmers put comments at various places in colon
 1623: definitions that describe the contents of the stack at that place (stack
 1624: comments); i.e., they are like the first part of a stack-effect
 1625: comment. E.g.,
 1626: 
 1627: @example
 1628: : cubed ( n -- n^3 )
 1629:    dup squared  ( n n^2 ) * ;
 1630: @end example
 1631: 
 1632: In this case the stack comment is pretty superfluous, because the word
 1633: is simple enough.  If you think it would be a good idea to add such a
 1634: comment to increase readability, you should also consider factoring the
 1635: word into several simpler words (@pxref{Factoring Tutorial,,
 1636: Factoring}), which typically eliminates the need for the stack comment;
 1637: however, if you decide not to refactor it, then having such a comment is
 1638: better than not having it.
 1639: 
 1640: The names of the stack items in stack-effect and stack comments in the
 1641: standard, in this manual, and in many programs specify the type through
 1642: a type prefix, similar to Fortran and Hungarian notation.  The most
 1643: frequent prefixes are:
 1644: 
 1645: @table @code
 1646: @item n
 1647: signed integer
 1648: @item u
 1649: unsigned integer
 1650: @item c
 1651: character
 1652: @item f
 1653: Boolean flags, i.e. @code{false} or @code{true}.
 1654: @item a-addr,a-
 1655: Cell-aligned address
 1656: @item c-addr,c-
 1657: Char-aligned address (note that a Char may have two bytes in Windows NT)
 1658: @item xt
 1659: Execution token, same size as Cell
 1660: @item w,x
 1661: Cell, can contain an integer or an address.  It usually takes 32, 64 or
 1662: 16 bits (depending on your platform and Forth system). A cell is more
 1663: commonly known as machine word, but the term @emph{word} already means
 1664: something different in Forth.
 1665: @item d
 1666: signed double-cell integer
 1667: @item ud
 1668: unsigned double-cell integer
 1669: @item r
 1670: Float (on the FP stack)
 1671: @end table
 1672: 
 1673: You can find a more complete list in @ref{Notation}.
 1674: 
 1675: @quotation Assignment
 1676: Write stack-effect comments for all definitions you have written up to
 1677: now.
 1678: @end quotation
 1679: 
 1680: 
 1681: @node Types Tutorial, Factoring Tutorial, Stack-Effect Comments Tutorial, Tutorial
 1682: @section Types
 1683: @cindex types tutorial
 1684: 
 1685: In Forth the names of the operations are not overloaded; so similar
 1686: operations on different types need different names; e.g., @code{+} adds
 1687: integers, and you have to use @code{f+} to add floating-point numbers.
 1688: The following prefixes are often used for related operations on
 1689: different types:
 1690: 
 1691: @table @code
 1692: @item (none)
 1693: signed integer
 1694: @item u
 1695: unsigned integer
 1696: @item c
 1697: character
 1698: @item d
 1699: signed double-cell integer
 1700: @item ud, du
 1701: unsigned double-cell integer
 1702: @item 2
 1703: two cells (not-necessarily double-cell numbers)
 1704: @item m, um
 1705: mixed single-cell and double-cell operations
 1706: @item f
 1707: floating-point (note that in stack comments @samp{f} represents flags,
 1708: and @samp{r} represents FP numbers).
 1709: @end table
 1710: 
 1711: If there are no differences between the signed and the unsigned variant
 1712: (e.g., for @code{+}), there is only the prefix-less variant.
 1713: 
 1714: Forth does not perform type checking, neither at compile time, nor at
 1715: run time.  If you use the wrong oeration, the data are interpreted
 1716: incorrectly:
 1717: 
 1718: @example
 1719: -1 u.
 1720: @end example
 1721: 
 1722: If you have only experience with type-checked languages until now, and
 1723: have heard how important type-checking is, don't panic!  In my
 1724: experience (and that of other Forthers), type errors in Forth code are
 1725: usually easy to find (once you get used to it), the increased vigilance
 1726: of the programmer tends to catch some harder errors in addition to most
 1727: type errors, and you never have to work around the type system, so in
 1728: most situations the lack of type-checking seems to be a win (projects to
 1729: add type checking to Forth have not caught on).
 1730: 
 1731: 
 1732: @node Factoring Tutorial, Designing the stack effect Tutorial, Types Tutorial, Tutorial
 1733: @section Factoring
 1734: @cindex factoring tutorial
 1735: 
 1736: If you try to write longer definitions, you will soon find it hard to
 1737: keep track of the stack contents.  Therefore, good Forth programmers
 1738: tend to write only short definitions (e.g., three lines).  The art of
 1739: finding meaningful short definitions is known as factoring (as in
 1740: factoring polynomials).
 1741: 
 1742: Well-factored programs offer additional advantages: smaller, more
 1743: general words, are easier to test and debug and can be reused more and
 1744: better than larger, specialized words.
 1745: 
 1746: So, if you run into difficulties with stack management, when writing
 1747: code, try to define meaningful factors for the word, and define the word
 1748: in terms of those.  Even if a factor contains only two words, it is
 1749: often helpful.
 1750: 
 1751: Good factoring is not easy, and it takes some practice to get the knack
 1752: for it; but even experienced Forth programmers often don't find the
 1753: right solution right away, but only when rewriting the program.  So, if
 1754: you don't come up with a good solution immediately, keep trying, don't
 1755: despair.
 1756: 
 1757: @c example !!
 1758: 
 1759: 
 1760: @node Designing the stack effect Tutorial, Local Variables Tutorial, Factoring Tutorial, Tutorial
 1761: @section Designing the stack effect
 1762: @cindex Stack effect design, tutorial
 1763: @cindex design of stack effects, tutorial
 1764: 
 1765: In other languages you can use an arbitrary order of parameters for a
 1766: function; and since there is only one result, you don't have to deal with
 1767: the order of results, either.
 1768: 
 1769: In Forth (and other stack-based languages, e.g., PostScript) the
 1770: parameter and result order of a definition is important and should be
 1771: designed well.  The general guideline is to design the stack effect such
 1772: that the word is simple to use in most cases, even if that complicates
 1773: the implementation of the word.  Some concrete rules are:
 1774: 
 1775: @itemize @bullet
 1776: 
 1777: @item
 1778: Words consume all of their parameters (e.g., @code{.}).
 1779: 
 1780: @item
 1781: If there is a convention on the order of parameters (e.g., from
 1782: mathematics or another programming language), stick with it (e.g.,
 1783: @code{-}).
 1784: 
 1785: @item
 1786: If one parameter usually requires only a short computation (e.g., it is
 1787: a constant), pass it on the top of the stack.  Conversely, parameters
 1788: that usually require a long sequence of code to compute should be passed
 1789: as the bottom (i.e., first) parameter.  This makes the code easier to
 1790: read, because reader does not need to keep track of the bottom item
 1791: through a long sequence of code (or, alternatively, through stack
 1792: manipulations). E.g., @code{!} (store, @pxref{Memory}) expects the
 1793: address on top of the stack because it is usually simpler to compute
 1794: than the stored value (often the address is just a variable).
 1795: 
 1796: @item
 1797: Similarly, results that are usually consumed quickly should be returned
 1798: on the top of stack, whereas a result that is often used in long
 1799: computations should be passed as bottom result.  E.g., the file words
 1800: like @code{open-file} return the error code on the top of stack, because
 1801: it is usually consumed quickly by @code{throw}; moreover, the error code
 1802: has to be checked before doing anything with the other results.
 1803: 
 1804: @end itemize
 1805: 
 1806: These rules are just general guidelines, don't lose sight of the overall
 1807: goal to make the words easy to use.  E.g., if the convention rule
 1808: conflicts with the computation-length rule, you might decide in favour
 1809: of the convention if the word will be used rarely, and in favour of the
 1810: computation-length rule if the word will be used frequently (because
 1811: with frequent use the cost of breaking the computation-length rule would
 1812: be quite high, and frequent use makes it easier to remember an
 1813: unconventional order).
 1814: 
 1815: @c example !! structure package
 1816: 
 1817: 
 1818: @node Local Variables Tutorial, Conditional execution Tutorial, Designing the stack effect Tutorial, Tutorial
 1819: @section Local Variables
 1820: @cindex local variables, tutorial
 1821: 
 1822: You can define local variables (@emph{locals}) in a colon definition:
 1823: 
 1824: @example
 1825: : swap @{ a b -- b a @}
 1826:   b a ;
 1827: 1 2 swap .s 2drop
 1828: @end example
 1829: 
 1830: (If your Forth system does not support this syntax, include
 1831: @file{compat/anslocals.fs} first).
 1832: 
 1833: In this example @code{@{ a b -- b a @}} is the locals definition; it
 1834: takes two cells from the stack, puts the top of stack in @code{b} and
 1835: the next stack element in @code{a}.  @code{--} starts a comment ending
 1836: with @code{@}}.  After the locals definition, using the name of the
 1837: local will push its value on the stack.  You can leave the comment
 1838: part (@code{-- b a}) away:
 1839: 
 1840: @example
 1841: : swap ( x1 x2 -- x2 x1 )
 1842:   @{ a b @} b a ;
 1843: @end example
 1844: 
 1845: In Gforth you can have several locals definitions, anywhere in a colon
 1846: definition; in contrast, in a standard program you can have only one
 1847: locals definition per colon definition, and that locals definition must
 1848: be outside any control structure.
 1849: 
 1850: With locals you can write slightly longer definitions without running
 1851: into stack trouble.  However, I recommend trying to write colon
 1852: definitions without locals for exercise purposes to help you gain the
 1853: essential factoring skills.
 1854: 
 1855: @quotation Assignment
 1856: Rewrite your definitions until now with locals
 1857: @end quotation
 1858: 
 1859: Reference: @ref{Locals}.
 1860: 
 1861: 
 1862: @node Conditional execution Tutorial, Flags and Comparisons Tutorial, Local Variables Tutorial, Tutorial
 1863: @section Conditional execution
 1864: @cindex conditionals, tutorial
 1865: @cindex if, tutorial
 1866: 
 1867: In Forth you can use control structures only inside colon definitions.
 1868: An @code{if}-structure looks like this:
 1869: 
 1870: @example
 1871: : abs ( n1 -- +n2 )
 1872:     dup 0 < if
 1873:         negate
 1874:     endif ;
 1875: 5 abs .
 1876: -5 abs .
 1877: @end example
 1878: 
 1879: @code{if} takes a flag from the stack.  If the flag is non-zero (true),
 1880: the following code is performed, otherwise execution continues after the
 1881: @code{endif} (or @code{else}).  @code{<} compares the top two stack
 1882: elements and prioduces a flag:
 1883: 
 1884: @example
 1885: 1 2 < .
 1886: 2 1 < .
 1887: 1 1 < .
 1888: @end example
 1889: 
 1890: Actually the standard name for @code{endif} is @code{then}.  This
 1891: tutorial presents the examples using @code{endif}, because this is often
 1892: less confusing for people familiar with other programming languages
 1893: where @code{then} has a different meaning.  If your system does not have
 1894: @code{endif}, define it with
 1895: 
 1896: @example
 1897: : endif postpone then ; immediate
 1898: @end example
 1899: 
 1900: You can optionally use an @code{else}-part:
 1901: 
 1902: @example
 1903: : min ( n1 n2 -- n )
 1904:   2dup < if
 1905:     drop
 1906:   else
 1907:     nip
 1908:   endif ;
 1909: 2 3 min .
 1910: 3 2 min .
 1911: @end example
 1912: 
 1913: @quotation Assignment
 1914: Write @code{min} without @code{else}-part (hint: what's the definition
 1915: of @code{nip}?).
 1916: @end quotation
 1917: 
 1918: Reference: @ref{Selection}.
 1919: 
 1920: 
 1921: @node Flags and Comparisons Tutorial, General Loops Tutorial, Conditional execution Tutorial, Tutorial
 1922: @section Flags and Comparisons
 1923: @cindex flags tutorial
 1924: @cindex comparison tutorial
 1925: 
 1926: In a false-flag all bits are clear (0 when interpreted as integer).  In
 1927: a canonical true-flag all bits are set (-1 as a twos-complement signed
 1928: integer); in many contexts (e.g., @code{if}) any non-zero value is
 1929: treated as true flag.
 1930: 
 1931: @example
 1932: false .
 1933: true .
 1934: true hex u. decimal
 1935: @end example
 1936: 
 1937: Comparison words produce canonical flags:
 1938: 
 1939: @example
 1940: 1 1 = .
 1941: 1 0= .
 1942: 0 1 < .
 1943: 0 0 < .
 1944: -1 1 u< . \ type error, u< interprets -1 as large unsigned number
 1945: -1 1 < .
 1946: @end example
 1947: 
 1948: Gforth supports all combinations of the prefixes @code{0 u d d0 du f f0}
 1949: (or none) and the comparisons @code{= <> < > <= >=}.  Only a part of
 1950: these combinations are standard (for details see the standard,
 1951: @ref{Numeric comparison}, @ref{Floating Point} or @ref{Word Index}).
 1952: 
 1953: You can use @code{and or xor invert} can be used as operations on
 1954: canonical flags.  Actually they are bitwise operations:
 1955: 
 1956: @example
 1957: 1 2 and .
 1958: 1 2 or .
 1959: 1 3 xor .
 1960: 1 invert .
 1961: @end example
 1962: 
 1963: You can convert a zero/non-zero flag into a canonical flag with
 1964: @code{0<>} (and complement it on the way with @code{0=}).
 1965: 
 1966: @example
 1967: 1 0= .
 1968: 1 0<> .
 1969: @end example
 1970: 
 1971: You can use the all-bits-set feature of canonical flags and the bitwise
 1972: operation of the Boolean operations to avoid @code{if}s:
 1973: 
 1974: @example
 1975: : foo ( n1 -- n2 )
 1976:   0= if
 1977:     14
 1978:   else
 1979:     0
 1980:   endif ;
 1981: 0 foo .
 1982: 1 foo .
 1983: 
 1984: : foo ( n1 -- n2 )
 1985:   0= 14 and ;
 1986: 0 foo .
 1987: 1 foo .
 1988: @end example
 1989: 
 1990: @quotation Assignment
 1991: Write @code{min} without @code{if}.
 1992: @end quotation
 1993: 
 1994: For reference, see @ref{Boolean Flags}, @ref{Numeric comparison}, and
 1995: @ref{Bitwise operations}.
 1996: 
 1997: 
 1998: @node General Loops Tutorial, Counted loops Tutorial, Flags and Comparisons Tutorial, Tutorial
 1999: @section General Loops
 2000: @cindex loops, indefinite, tutorial
 2001: 
 2002: The endless loop is the most simple one:
 2003: 
 2004: @example
 2005: : endless ( -- )
 2006:   0 begin
 2007:     dup . 1+
 2008:   again ;
 2009: endless
 2010: @end example
 2011: 
 2012: Terminate this loop by pressing @kbd{Ctrl-C} (in Gforth).  @code{begin}
 2013: does nothing at run-time, @code{again} jumps back to @code{begin}.
 2014: 
 2015: A loop with one exit at any place looks like this:
 2016: 
 2017: @example
 2018: : log2 ( +n1 -- n2 )
 2019: \ logarithmus dualis of n1>0, rounded down to the next integer
 2020:   assert( dup 0> )
 2021:   2/ 0 begin
 2022:     over 0> while
 2023:       1+ swap 2/ swap
 2024:   repeat
 2025:   nip ;
 2026: 7 log2 .
 2027: 8 log2 .
 2028: @end example
 2029: 
 2030: At run-time @code{while} consumes a flag; if it is 0, execution
 2031: continues behind the @code{repeat}; if the flag is non-zero, execution
 2032: continues behind the @code{while}.  @code{Repeat} jumps back to
 2033: @code{begin}, just like @code{again}.
 2034: 
 2035: In Forth there are many combinations/abbreviations, like @code{1+}.
 2036: However, @code{2/} is not one of them; it shifts its argument right by
 2037: one bit (arithmetic shift right):
 2038: 
 2039: @example
 2040: -5 2 / .
 2041: -5 2/ .
 2042: @end example
 2043: 
 2044: @code{assert(} is no standard word, but you can get it on systems other
 2045: then Gforth by including @file{compat/assert.fs}.  You can see what it
 2046: does by trying
 2047: 
 2048: @example
 2049: 0 log2 .
 2050: @end example
 2051: 
 2052: Here's a loop with an exit at the end:
 2053: 
 2054: @example
 2055: : log2 ( +n1 -- n2 )
 2056: \ logarithmus dualis of n1>0, rounded down to the next integer
 2057:   assert( dup 0 > )
 2058:   -1 begin
 2059:     1+ swap 2/ swap
 2060:     over 0 <=
 2061:   until
 2062:   nip ;
 2063: @end example
 2064: 
 2065: @code{Until} consumes a flag; if it is non-zero, execution continues at
 2066: the @code{begin}, otherwise after the @code{until}.
 2067: 
 2068: @quotation Assignment
 2069: Write a definition for computing the greatest common divisor.
 2070: @end quotation
 2071: 
 2072: Reference: @ref{Simple Loops}.
 2073: 
 2074: 
 2075: @node Counted loops Tutorial, Recursion Tutorial, General Loops Tutorial, Tutorial
 2076: @section Counted loops
 2077: @cindex loops, counted, tutorial
 2078: 
 2079: @example
 2080: : ^ ( n1 u -- n )
 2081: \ n = the uth power of u1
 2082:   1 swap 0 u+do
 2083:     over *
 2084:   loop
 2085:   nip ;
 2086: 3 2 ^ .
 2087: 4 3 ^ .
 2088: @end example
 2089: 
 2090: @code{U+do} (from @file{compat/loops.fs}, if your Forth system doesn't
 2091: have it) takes two numbers of the stack @code{( u3 u4 -- )}, and then
 2092: performs the code between @code{u+do} and @code{loop} for @code{u3-u4}
 2093: times (or not at all, if @code{u3-u4<0}).
 2094: 
 2095: You can see the stack effect design rules at work in the stack effect of
 2096: the loop start words: Since the start value of the loop is more
 2097: frequently constant than the end value, the start value is passed on
 2098: the top-of-stack.
 2099: 
 2100: You can access the counter of a counted loop with @code{i}:
 2101: 
 2102: @example
 2103: : fac ( u -- u! )
 2104:   1 swap 1+ 1 u+do
 2105:     i *
 2106:   loop ;
 2107: 5 fac .
 2108: 7 fac .
 2109: @end example
 2110: 
 2111: There is also @code{+do}, which expects signed numbers (important for
 2112: deciding whether to enter the loop).
 2113: 
 2114: @quotation Assignment
 2115: Write a definition for computing the nth Fibonacci number.
 2116: @end quotation
 2117: 
 2118: You can also use increments other than 1:
 2119: 
 2120: @example
 2121: : up2 ( n1 n2 -- )
 2122:   +do
 2123:     i .
 2124:   2 +loop ;
 2125: 10 0 up2
 2126: 
 2127: : down2 ( n1 n2 -- )
 2128:   -do
 2129:     i .
 2130:   2 -loop ;
 2131: 0 10 down2
 2132: @end example
 2133: 
 2134: Reference: @ref{Counted Loops}.
 2135: 
 2136: 
 2137: @node Recursion Tutorial, Leaving definitions or loops Tutorial, Counted loops Tutorial, Tutorial
 2138: @section Recursion
 2139: @cindex recursion tutorial
 2140: 
 2141: Usually the name of a definition is not visible in the definition; but
 2142: earlier definitions are usually visible:
 2143: 
 2144: @example
 2145: 1 0 / . \ "Floating-point unidentified fault" in Gforth on some platforms
 2146: : / ( n1 n2 -- n )
 2147:   dup 0= if
 2148:     -10 throw \ report division by zero
 2149:   endif
 2150:   /           \ old version
 2151: ;
 2152: 1 0 /
 2153: @end example
 2154: 
 2155: For recursive definitions you can use @code{recursive} (non-standard) or
 2156: @code{recurse}:
 2157: 
 2158: @example
 2159: : fac1 ( n -- n! ) recursive
 2160:  dup 0> if
 2161:    dup 1- fac1 *
 2162:  else
 2163:    drop 1
 2164:  endif ;
 2165: 7 fac1 .
 2166: 
 2167: : fac2 ( n -- n! )
 2168:  dup 0> if
 2169:    dup 1- recurse *
 2170:  else
 2171:    drop 1
 2172:  endif ;
 2173: 8 fac2 .
 2174: @end example
 2175: 
 2176: @quotation Assignment
 2177: Write a recursive definition for computing the nth Fibonacci number.
 2178: @end quotation
 2179: 
 2180: Reference (including indirect recursion): @xref{Calls and returns}.
 2181: 
 2182: 
 2183: @node Leaving definitions or loops Tutorial, Return Stack Tutorial, Recursion Tutorial, Tutorial
 2184: @section Leaving definitions or loops
 2185: @cindex leaving definitions, tutorial
 2186: @cindex leaving loops, tutorial
 2187: 
 2188: @code{EXIT} exits the current definition right away.  For every counted
 2189: loop that is left in this way, an @code{UNLOOP} has to be performed
 2190: before the @code{EXIT}:
 2191: 
 2192: @c !! real examples
 2193: @example
 2194: : ...
 2195:  ... u+do
 2196:    ... if
 2197:      ... unloop exit
 2198:    endif
 2199:    ...
 2200:  loop
 2201:  ... ;
 2202: @end example
 2203: 
 2204: @code{LEAVE} leaves the innermost counted loop right away:
 2205: 
 2206: @example
 2207: : ...
 2208:  ... u+do
 2209:    ... if
 2210:      ... leave
 2211:    endif
 2212:    ...
 2213:  loop
 2214:  ... ;
 2215: @end example
 2216: 
 2217: @c !! example
 2218: 
 2219: Reference: @ref{Calls and returns}, @ref{Counted Loops}.
 2220: 
 2221: 
 2222: @node Return Stack Tutorial, Memory Tutorial, Leaving definitions or loops Tutorial, Tutorial
 2223: @section Return Stack
 2224: @cindex return stack tutorial
 2225: 
 2226: In addition to the data stack Forth also has a second stack, the return
 2227: stack; most Forth systems store the return addresses of procedure calls
 2228: there (thus its name).  Programmers can also use this stack:
 2229: 
 2230: @example
 2231: : foo ( n1 n2 -- )
 2232:  .s
 2233:  >r .s
 2234:  r@@ .
 2235:  >r .s
 2236:  r@@ .
 2237:  r> .
 2238:  r@@ .
 2239:  r> . ;
 2240: 1 2 foo
 2241: @end example
 2242: 
 2243: @code{>r} takes an element from the data stack and pushes it onto the
 2244: return stack; conversely, @code{r>} moves an elementm from the return to
 2245: the data stack; @code{r@@} pushes a copy of the top of the return stack
 2246: on the data stack.
 2247: 
 2248: Forth programmers usually use the return stack for storing data
 2249: temporarily, if using the data stack alone would be too complex, and
 2250: factoring and locals are not an option:
 2251: 
 2252: @example
 2253: : 2swap ( x1 x2 x3 x4 -- x3 x4 x1 x2 )
 2254:  rot >r rot r> ;
 2255: @end example
 2256: 
 2257: The return address of the definition and the loop control parameters of
 2258: counted loops usually reside on the return stack, so you have to take
 2259: all items, that you have pushed on the return stack in a colon
 2260: definition or counted loop, from the return stack before the definition
 2261: or loop ends.  You cannot access items that you pushed on the return
 2262: stack outside some definition or loop within the definition of loop.
 2263: 
 2264: If you miscount the return stack items, this usually ends in a crash:
 2265: 
 2266: @example
 2267: : crash ( n -- )
 2268:   >r ;
 2269: 5 crash
 2270: @end example
 2271: 
 2272: You cannot mix using locals and using the return stack (according to the
 2273: standard; Gforth has no problem).  However, they solve the same
 2274: problems, so this shouldn't be an issue.
 2275: 
 2276: @quotation Assignment
 2277: Can you rewrite any of the definitions you wrote until now in a better
 2278: way using the return stack?
 2279: @end quotation
 2280: 
 2281: Reference: @ref{Return stack}.
 2282: 
 2283: 
 2284: @node Memory Tutorial, Characters and Strings Tutorial, Return Stack Tutorial, Tutorial
 2285: @section Memory
 2286: @cindex memory access/allocation tutorial
 2287: 
 2288: You can create a global variable @code{v} with
 2289: 
 2290: @example
 2291: variable v ( -- addr )
 2292: @end example
 2293: 
 2294: @code{v} pushes the address of a cell in memory on the stack.  This cell
 2295: was reserved by @code{variable}.  You can use @code{!} (store) to store
 2296: values into this cell and @code{@@} (fetch) to load the value from the
 2297: stack into memory:
 2298: 
 2299: @example
 2300: v .
 2301: 5 v ! .s
 2302: v @@ .
 2303: @end example
 2304: 
 2305: You can see a raw dump of memory with @code{dump}:
 2306: 
 2307: @example
 2308: v 1 cells .s dump
 2309: @end example
 2310: 
 2311: @code{Cells ( n1 -- n2 )} gives you the number of bytes (or, more
 2312: generally, address units (aus)) that @code{n1 cells} occupy.  You can
 2313: also reserve more memory:
 2314: 
 2315: @example
 2316: create v2 20 cells allot
 2317: v2 20 cells dump
 2318: @end example
 2319: 
 2320: creates a word @code{v2} and reserves 20 uninitialized cells; the
 2321: address pushed by @code{v2} points to the start of these 20 cells.  You
 2322: can use address arithmetic to access these cells:
 2323: 
 2324: @example
 2325: 3 v2 5 cells + !
 2326: v2 20 cells dump
 2327: @end example
 2328: 
 2329: You can reserve and initialize memory with @code{,}:
 2330: 
 2331: @example
 2332: create v3
 2333:   5 , 4 , 3 , 2 , 1 ,
 2334: v3 @@ .
 2335: v3 cell+ @@ .
 2336: v3 2 cells + @@ .
 2337: v3 5 cells dump
 2338: @end example
 2339: 
 2340: @quotation Assignment
 2341: Write a definition @code{vsum ( addr u -- n )} that computes the sum of
 2342: @code{u} cells, with the first of these cells at @code{addr}, the next
 2343: one at @code{addr cell+} etc.
 2344: @end quotation
 2345: 
 2346: You can also reserve memory without creating a new word:
 2347: 
 2348: @example
 2349: here 10 cells allot .
 2350: here .
 2351: @end example
 2352: 
 2353: @code{Here} pushes the start address of the memory area.  You should
 2354: store it somewhere, or you will have a hard time finding the memory area
 2355: again.
 2356: 
 2357: @code{Allot} manages dictionary memory.  The dictionary memory contains
 2358: the system's data structures for words etc. on Gforth and most other
 2359: Forth systems.  It is managed like a stack: You can free the memory that
 2360: you have just @code{allot}ed with
 2361: 
 2362: @example
 2363: -10 cells allot
 2364: here .
 2365: @end example
 2366: 
 2367: Note that you cannot do this if you have created a new word in the
 2368: meantime (because then your @code{allot}ed memory is no longer on the
 2369: top of the dictionary ``stack'').
 2370: 
 2371: Alternatively, you can use @code{allocate} and @code{free} which allow
 2372: freeing memory in any order:
 2373: 
 2374: @example
 2375: 10 cells allocate throw .s
 2376: 20 cells allocate throw .s
 2377: swap
 2378: free throw
 2379: free throw
 2380: @end example
 2381: 
 2382: The @code{throw}s deal with errors (e.g., out of memory).
 2383: 
 2384: And there is also a
 2385: @uref{http://www.complang.tuwien.ac.at/forth/garbage-collection.zip,
 2386: garbage collector}, which eliminates the need to @code{free} memory
 2387: explicitly.
 2388: 
 2389: Reference: @ref{Memory}.
 2390: 
 2391: 
 2392: @node Characters and Strings Tutorial, Alignment Tutorial, Memory Tutorial, Tutorial
 2393: @section Characters and Strings
 2394: @cindex strings tutorial
 2395: @cindex characters tutorial
 2396: 
 2397: On the stack characters take up a cell, like numbers.  In memory they
 2398: have their own size (one 8-bit byte on most systems), and therefore
 2399: require their own words for memory access:
 2400: 
 2401: @example
 2402: create v4 
 2403:   104 c, 97 c, 108 c, 108 c, 111 c,
 2404: v4 4 chars + c@@ .
 2405: v4 5 chars dump
 2406: @end example
 2407: 
 2408: The preferred representation of strings on the stack is @code{addr
 2409: u-count}, where @code{addr} is the address of the first character and
 2410: @code{u-count} is the number of characters in the string.
 2411: 
 2412: @example
 2413: v4 5 type
 2414: @end example
 2415: 
 2416: You get a string constant with
 2417: 
 2418: @example
 2419: s" hello, world" .s
 2420: type
 2421: @end example
 2422: 
 2423: Make sure you have a space between @code{s"} and the string; @code{s"}
 2424: is a normal Forth word and must be delimited with white space (try what
 2425: happens when you remove the space).
 2426: 
 2427: However, this interpretive use of @code{s"} is quite restricted: the
 2428: string exists only until the next call of @code{s"} (some Forth systems
 2429: keep more than one of these strings, but usually they still have a
 2430: limited lifetime).
 2431: 
 2432: @example
 2433: s" hello," s" world" .s
 2434: type
 2435: type
 2436: @end example
 2437: 
 2438: You can also use @code{s"} in a definition, and the resulting
 2439: strings then live forever (well, for as long as the definition):
 2440: 
 2441: @example
 2442: : foo s" hello," s" world" ;
 2443: foo .s
 2444: type
 2445: type
 2446: @end example
 2447: 
 2448: @quotation Assignment
 2449: @code{Emit ( c -- )} types @code{c} as character (not a number).
 2450: Implement @code{type ( addr u -- )}.
 2451: @end quotation
 2452: 
 2453: Reference: @ref{Memory Blocks}.
 2454: 
 2455: 
 2456: @node Alignment Tutorial, Files Tutorial, Characters and Strings Tutorial, Tutorial
 2457: @section Alignment
 2458: @cindex alignment tutorial
 2459: @cindex memory alignment tutorial
 2460: 
 2461: On many processors cells have to be aligned in memory, if you want to
 2462: access them with @code{@@} and @code{!} (and even if the processor does
 2463: not require alignment, access to aligned cells is faster).
 2464: 
 2465: @code{Create} aligns @code{here} (i.e., the place where the next
 2466: allocation will occur, and that the @code{create}d word points to).
 2467: Likewise, the memory produced by @code{allocate} starts at an aligned
 2468: address.  Adding a number of @code{cells} to an aligned address produces
 2469: another aligned address.
 2470: 
 2471: However, address arithmetic involving @code{char+} and @code{chars} can
 2472: create an address that is not cell-aligned.  @code{Aligned ( addr --
 2473: a-addr )} produces the next aligned address:
 2474: 
 2475: @example
 2476: v3 char+ aligned .s @@ .
 2477: v3 char+ .s @@ .
 2478: @end example
 2479: 
 2480: Similarly, @code{align} advances @code{here} to the next aligned
 2481: address:
 2482: 
 2483: @example
 2484: create v5 97 c,
 2485: here .
 2486: align here .
 2487: 1000 ,
 2488: @end example
 2489: 
 2490: Note that you should use aligned addresses even if your processor does
 2491: not require them, if you want your program to be portable.
 2492: 
 2493: Reference: @ref{Address arithmetic}.
 2494: 
 2495: 
 2496: @node Files Tutorial, Interpretation and Compilation Semantics and Immediacy Tutorial, Alignment Tutorial, Tutorial
 2497: @section Files
 2498: @cindex files tutorial
 2499: 
 2500: This section gives a short introduction into how to use files inside
 2501: Forth. It's broken up into five easy steps:
 2502: 
 2503: @enumerate 1
 2504: @item Opened an ASCII text file for input
 2505: @item Opened a file for output
 2506: @item Read input file until string matched (or some other condition matched)
 2507: @item Wrote some lines from input ( modified or not) to output
 2508: @item Closed the files.
 2509: @end enumerate
 2510: 
 2511: Reference: @ref{General files}.
 2512: 
 2513: @subsection Open file for input
 2514: 
 2515: @example
 2516: s" foo.in"  r/o open-file throw Value fd-in
 2517: @end example
 2518: 
 2519: @subsection Create file for output
 2520: 
 2521: @example
 2522: s" foo.out" w/o create-file throw Value fd-out
 2523: @end example
 2524: 
 2525: The available file modes are r/o for read-only access, r/w for
 2526: read-write access, and w/o for write-only access. You could open both
 2527: files with r/w, too, if you like. All file words return error codes; for
 2528: most applications, it's best to pass there error codes with @code{throw}
 2529: to the outer error handler.
 2530: 
 2531: If you want words for opening and assigning, define them as follows:
 2532: 
 2533: @example
 2534: 0 Value fd-in
 2535: 0 Value fd-out
 2536: : open-input ( addr u -- )  r/o open-file throw to fd-in ;
 2537: : open-output ( addr u -- )  w/o create-file throw to fd-out ;
 2538: @end example
 2539: 
 2540: Usage example:
 2541: 
 2542: @example
 2543: s" foo.in" open-input
 2544: s" foo.out" open-output
 2545: @end example
 2546: 
 2547: @subsection Scan file for a particular line
 2548: 
 2549: @example
 2550: 256 Constant max-line
 2551: Create line-buffer  max-line 2 + allot
 2552: 
 2553: : scan-file ( addr u -- )
 2554:   begin
 2555:       line-buffer max-line fd-in read-line throw
 2556:   while
 2557:          >r 2dup line-buffer r> compare 0=
 2558:      until
 2559:   else
 2560:      drop
 2561:   then
 2562:   2drop ;
 2563: @end example
 2564: 
 2565: @code{read-line ( addr u1 fd -- u2 flag ior )} reads up to u1 bytes into
 2566: the buffer at addr, and returns the number of bytes read, a flag that is
 2567: false when the end of file is reached, and an error code.
 2568: 
 2569: @code{compare ( addr1 u1 addr2 u2 -- n )} compares two strings and
 2570: returns zero if both strings are equal. It returns a positive number if
 2571: the first string is lexically greater, a negative if the second string
 2572: is lexically greater.
 2573: 
 2574: We haven't seen this loop here; it has two exits. Since the @code{while}
 2575: exits with the number of bytes read on the stack, we have to clean up
 2576: that separately; that's after the @code{else}.
 2577: 
 2578: Usage example:
 2579: 
 2580: @example
 2581: s" The text I search is here" scan-file
 2582: @end example
 2583: 
 2584: @subsection Copy input to output
 2585: 
 2586: @example
 2587: : copy-file ( -- )
 2588:   begin
 2589:       line-buffer max-line fd-in read-line throw
 2590:   while
 2591:       line-buffer swap fd-out write-file throw
 2592:   repeat ;
 2593: @end example
 2594: 
 2595: @subsection Close files
 2596: 
 2597: @example
 2598: fd-in close-file throw
 2599: fd-out close-file throw
 2600: @end example
 2601: 
 2602: Likewise, you can put that into definitions, too:
 2603: 
 2604: @example
 2605: : close-input ( -- )  fd-in close-file throw ;
 2606: : close-output ( -- )  fd-out close-file throw ;
 2607: @end example
 2608: 
 2609: @quotation Assignment
 2610: How could you modify @code{copy-file} so that it copies until a second line is
 2611: matched? Can you write a program that extracts a section of a text file,
 2612: given the line that starts and the line that terminates that section?
 2613: @end quotation
 2614: 
 2615: @node Interpretation and Compilation Semantics and Immediacy Tutorial, Execution Tokens Tutorial, Files Tutorial, Tutorial
 2616: @section Interpretation and Compilation Semantics and Immediacy
 2617: @cindex semantics tutorial
 2618: @cindex interpretation semantics tutorial
 2619: @cindex compilation semantics tutorial
 2620: @cindex immediate, tutorial
 2621: 
 2622: When a word is compiled, it behaves differently from being interpreted.
 2623: E.g., consider @code{+}:
 2624: 
 2625: @example
 2626: 1 2 + .
 2627: : foo + ;
 2628: @end example
 2629: 
 2630: These two behaviours are known as compilation and interpretation
 2631: semantics.  For normal words (e.g., @code{+}), the compilation semantics
 2632: is to append the interpretation semantics to the currently defined word
 2633: (@code{foo} in the example above).  I.e., when @code{foo} is executed
 2634: later, the interpretation semantics of @code{+} (i.e., adding two
 2635: numbers) will be performed.
 2636: 
 2637: However, there are words with non-default compilation semantics, e.g.,
 2638: the control-flow words like @code{if}.  You can use @code{immediate} to
 2639: change the compilation semantics of the last defined word to be equal to
 2640: the interpretation semantics:
 2641: 
 2642: @example
 2643: : [FOO] ( -- )
 2644:  5 . ; immediate
 2645: 
 2646: [FOO]
 2647: : bar ( -- )
 2648:   [FOO] ;
 2649: bar
 2650: see bar
 2651: @end example
 2652: 
 2653: Two conventions to mark words with non-default compilation semnatics are
 2654: names with brackets (more frequently used) and to write them all in
 2655: upper case (less frequently used).
 2656: 
 2657: In Gforth (and many other systems) you can also remove the
 2658: interpretation semantics with @code{compile-only} (the compilation
 2659: semantics is derived from the original interpretation semantics):
 2660: 
 2661: @example
 2662: : flip ( -- )
 2663:  6 . ; compile-only \ but not immediate
 2664: flip
 2665: 
 2666: : flop ( -- )
 2667:  flip ;
 2668: flop
 2669: @end example
 2670: 
 2671: In this example the interpretation semantics of @code{flop} is equal to
 2672: the original interpretation semantics of @code{flip}.
 2673: 
 2674: The text interpreter has two states: in interpret state, it performs the
 2675: interpretation semantics of words it encounters; in compile state, it
 2676: performs the compilation semantics of these words.
 2677: 
 2678: Among other things, @code{:} switches into compile state, and @code{;}
 2679: switches back to interpret state.  They contain the factors @code{]}
 2680: (switch to compile state) and @code{[} (switch to interpret state), that
 2681: do nothing but switch the state.
 2682: 
 2683: @example
 2684: : xxx ( -- )
 2685:   [ 5 . ]
 2686: ;
 2687: 
 2688: xxx
 2689: see xxx
 2690: @end example
 2691: 
 2692: These brackets are also the source of the naming convention mentioned
 2693: above.
 2694: 
 2695: Reference: @ref{Interpretation and Compilation Semantics}.
 2696: 
 2697: 
 2698: @node Execution Tokens Tutorial, Exceptions Tutorial, Interpretation and Compilation Semantics and Immediacy Tutorial, Tutorial
 2699: @section Execution Tokens
 2700: @cindex execution tokens tutorial
 2701: @cindex XT tutorial
 2702: 
 2703: @code{' word} gives you the execution token (XT) of a word.  The XT is a
 2704: cell representing the interpretation semantics of a word.  You can
 2705: execute this semantics with @code{execute}:
 2706: 
 2707: @example
 2708: ' + .s
 2709: 1 2 rot execute .
 2710: @end example
 2711: 
 2712: The XT is similar to a function pointer in C.  However, parameter
 2713: passing through the stack makes it a little more flexible:
 2714: 
 2715: @example
 2716: : map-array ( ... addr u xt -- ... )
 2717: \ executes xt ( ... x -- ... ) for every element of the array starting
 2718: \ at addr and containing u elements
 2719:   @{ xt @}
 2720:   cells over + swap ?do
 2721:     i @@ xt execute
 2722:   1 cells +loop ;
 2723: 
 2724: create a 3 , 4 , 2 , -1 , 4 ,
 2725: a 5 ' . map-array .s
 2726: 0 a 5 ' + map-array .
 2727: s" max-n" environment? drop .s
 2728: a 5 ' min map-array .
 2729: @end example
 2730: 
 2731: You can use map-array with the XTs of words that consume one element
 2732: more than they produce.  In theory you can also use it with other XTs,
 2733: but the stack effect then depends on the size of the array, which is
 2734: hard to understand.
 2735: 
 2736: Since XTs are cell-sized, you can store them in memory and manipulate
 2737: them on the stack like other cells.  You can also compile the XT into a
 2738: word with @code{compile,}:
 2739: 
 2740: @example
 2741: : foo1 ( n1 n2 -- n )
 2742:    [ ' + compile, ] ;
 2743: see foo
 2744: @end example
 2745: 
 2746: This is non-standard, because @code{compile,} has no compilation
 2747: semantics in the standard, but it works in good Forth systems.  For the
 2748: broken ones, use
 2749: 
 2750: @example
 2751: : [compile,] compile, ; immediate
 2752: 
 2753: : foo1 ( n1 n2 -- n )
 2754:    [ ' + ] [compile,] ;
 2755: see foo
 2756: @end example
 2757: 
 2758: @code{'} is a word with default compilation semantics; it parses the
 2759: next word when its interpretation semantics are executed, not during
 2760: compilation:
 2761: 
 2762: @example
 2763: : foo ( -- xt )
 2764:   ' ;
 2765: see foo
 2766: : bar ( ... "word" -- ... )
 2767:   ' execute ;
 2768: see bar
 2769: 1 2 bar + .
 2770: @end example
 2771: 
 2772: You often want to parse a word during compilation and compile its XT so
 2773: it will be pushed on the stack at run-time.  @code{[']} does this:
 2774: 
 2775: @example
 2776: : xt-+ ( -- xt )
 2777:   ['] + ;
 2778: see xt-+
 2779: 1 2 xt-+ execute .
 2780: @end example
 2781: 
 2782: Many programmers tend to see @code{'} and the word it parses as one
 2783: unit, and expect it to behave like @code{[']} when compiled, and are
 2784: confused by the actual behaviour.  If you are, just remember that the
 2785: Forth system just takes @code{'} as one unit and has no idea that it is
 2786: a parsing word (attempts to convenience programmers in this issue have
 2787: usually resulted in even worse pitfalls, see
 2788: @uref{http://www.complang.tuwien.ac.at/papers/ertl98.ps.gz,
 2789: @code{State}-smartness---Why it is evil and How to Exorcise it}).
 2790: 
 2791: Note that the state of the interpreter does not come into play when
 2792: creating and executing XTs.  I.e., even when you execute @code{'} in
 2793: compile state, it still gives you the interpretation semantics.  And
 2794: whatever that state is, @code{execute} performs the semantics
 2795: represented by the XT (i.e., for XTs produced with @code{'} the
 2796: interpretation semantics).
 2797: 
 2798: Reference: @ref{Tokens for Words}.
 2799: 
 2800: 
 2801: @node Exceptions Tutorial, Defining Words Tutorial, Execution Tokens Tutorial, Tutorial
 2802: @section Exceptions
 2803: @cindex exceptions tutorial
 2804: 
 2805: @code{throw ( n -- )} causes an exception unless n is zero.
 2806: 
 2807: @example
 2808: 100 throw .s
 2809: 0 throw .s
 2810: @end example
 2811: 
 2812: @code{catch ( ... xt -- ... n )} behaves similar to @code{execute}, but
 2813: it catches exceptions and pushes the number of the exception on the
 2814: stack (or 0, if the xt executed without exception).  If there was an
 2815: exception, the stacks have the same depth as when entering @code{catch}:
 2816: 
 2817: @example
 2818: .s
 2819: 3 0 ' / catch .s
 2820: 3 2 ' / catch .s
 2821: @end example
 2822: 
 2823: @quotation Assignment
 2824: Try the same with @code{execute} instead of @code{catch}.
 2825: @end quotation
 2826: 
 2827: @code{Throw} always jumps to the dynamically next enclosing
 2828: @code{catch}, even if it has to leave several call levels to achieve
 2829: this:
 2830: 
 2831: @example
 2832: : foo 100 throw ;
 2833: : foo1 foo ." after foo" ;
 2834: : bar ['] foo1 catch ;
 2835: bar .
 2836: @end example
 2837: 
 2838: It is often important to restore a value upon leaving a definition, even
 2839: if the definition is left through an exception.  You can ensure this
 2840: like this:
 2841: 
 2842: @example
 2843: : ...
 2844:    save-x
 2845:    ['] word-changing-x catch ( ... n )
 2846:    restore-x
 2847:    ( ... n ) throw ;
 2848: @end example
 2849: 
 2850: Gforth provides an alternative syntax in addition to @code{catch}:
 2851: @code{try ... recover ... endtry}.  If the code between @code{try} and
 2852: @code{recover} has an exception, the stack depths are restored, the
 2853: exception number is pushed on the stack, and the code between
 2854: @code{recover} and @code{endtry} is performed.  E.g., the definition for
 2855: @code{catch} is
 2856: 
 2857: @example
 2858: : catch ( x1 .. xn xt -- y1 .. ym 0 / z1 .. zn error ) \ exception
 2859:   try
 2860:     execute 0
 2861:   recover
 2862:     nip
 2863:   endtry ;
 2864: @end example
 2865: 
 2866: The equivalent to the restoration code above is
 2867: 
 2868: @example
 2869: : ...
 2870:   save-x
 2871:   try
 2872:     word-changing-x 0
 2873:   recover endtry
 2874:   restore-x
 2875:   throw ;
 2876: @end example
 2877: 
 2878: This works if @code{word-changing-x} does not change the stack depth,
 2879: otherwise you should add some code between @code{recover} and
 2880: @code{endtry} to balance the stack.
 2881: 
 2882: Reference: @ref{Exception Handling}.
 2883: 
 2884: 
 2885: @node Defining Words Tutorial, Arrays and Records Tutorial, Exceptions Tutorial, Tutorial
 2886: @section Defining Words
 2887: @cindex defining words tutorial
 2888: @cindex does> tutorial
 2889: @cindex create...does> tutorial
 2890: 
 2891: @c before semantics?
 2892: 
 2893: @code{:}, @code{create}, and @code{variable} are definition words: They
 2894: define other words.  @code{Constant} is another definition word:
 2895: 
 2896: @example
 2897: 5 constant foo
 2898: foo .
 2899: @end example
 2900: 
 2901: You can also use the prefixes @code{2} (double-cell) and @code{f}
 2902: (floating point) with @code{variable} and @code{constant}.
 2903: 
 2904: You can also define your own defining words.  E.g.:
 2905: 
 2906: @example
 2907: : variable ( "name" -- )
 2908:   create 0 , ;
 2909: @end example
 2910: 
 2911: You can also define defining words that create words that do something
 2912: other than just producing their address:
 2913: 
 2914: @example
 2915: : constant ( n "name" -- )
 2916:   create ,
 2917: does> ( -- n )
 2918:   ( addr ) @@ ;
 2919: 
 2920: 5 constant foo
 2921: foo .
 2922: @end example
 2923: 
 2924: The definition of @code{constant} above ends at the @code{does>}; i.e.,
 2925: @code{does>} replaces @code{;}, but it also does something else: It
 2926: changes the last defined word such that it pushes the address of the
 2927: body of the word and then performs the code after the @code{does>}
 2928: whenever it is called.
 2929: 
 2930: In the example above, @code{constant} uses @code{,} to store 5 into the
 2931: body of @code{foo}.  When @code{foo} executes, it pushes the address of
 2932: the body onto the stack, then (in the code after the @code{does>})
 2933: fetches the 5 from there.
 2934: 
 2935: The stack comment near the @code{does>} reflects the stack effect of the
 2936: defined word, not the stack effect of the code after the @code{does>}
 2937: (the difference is that the code expects the address of the body that
 2938: the stack comment does not show).
 2939: 
 2940: You can use these definition words to do factoring in cases that involve
 2941: (other) definition words.  E.g., a field offset is always added to an
 2942: address.  Instead of defining
 2943: 
 2944: @example
 2945: 2 cells constant offset-field1
 2946: @end example
 2947: 
 2948: and using this like
 2949: 
 2950: @example
 2951: ( addr ) offset-field1 +
 2952: @end example
 2953: 
 2954: you can define a definition word
 2955: 
 2956: @example
 2957: : simple-field ( n "name" -- )
 2958:   create ,
 2959: does> ( n1 -- n1+n )
 2960:   ( addr ) @@ + ;
 2961: @end example
 2962: 
 2963: Definition and use of field offsets now look like this:
 2964: 
 2965: @example
 2966: 2 cells simple-field field1
 2967: create mystruct 4 cells allot
 2968: mystruct .s field1 .s drop
 2969: @end example
 2970: 
 2971: If you want to do something with the word without performing the code
 2972: after the @code{does>}, you can access the body of a @code{create}d word
 2973: with @code{>body ( xt -- addr )}:
 2974: 
 2975: @example
 2976: : value ( n "name" -- )
 2977:   create ,
 2978: does> ( -- n1 )
 2979:   @@ ;
 2980: : to ( n "name" -- )
 2981:   ' >body ! ;
 2982: 
 2983: 5 value foo
 2984: foo .
 2985: 7 to foo
 2986: foo .
 2987: @end example
 2988: 
 2989: @quotation Assignment
 2990: Define @code{defer ( "name" -- )}, which creates a word that stores an
 2991: XT (at the start the XT of @code{abort}), and upon execution
 2992: @code{execute}s the XT.  Define @code{is ( xt "name" -- )} that stores
 2993: @code{xt} into @code{name}, a word defined with @code{defer}.  Indirect
 2994: recursion is one application of @code{defer}.
 2995: @end quotation
 2996: 
 2997: Reference: @ref{User-defined Defining Words}.
 2998: 
 2999: 
 3000: @node Arrays and Records Tutorial, POSTPONE Tutorial, Defining Words Tutorial, Tutorial
 3001: @section Arrays and Records
 3002: @cindex arrays tutorial
 3003: @cindex records tutorial
 3004: @cindex structs tutorial
 3005: 
 3006: Forth has no standard words for defining data structures such as arrays
 3007: and records (structs in C terminology), but you can build them yourself
 3008: based on address arithmetic.  You can also define words for defining
 3009: arrays and records (@pxref{Defining Words Tutorial,, Defining Words}).
 3010: 
 3011: One of the first projects a Forth newcomer sets out upon when learning
 3012: about defining words is an array defining word (possibly for
 3013: n-dimensional arrays).  Go ahead and do it, I did it, too; you will
 3014: learn something from it.  However, don't be disappointed when you later
 3015: learn that you have little use for these words (inappropriate use would
 3016: be even worse).  I have not yet found a set of useful array words yet;
 3017: the needs are just too diverse, and named, global arrays (the result of
 3018: naive use of defining words) are often not flexible enough (e.g.,
 3019: consider how to pass them as parameters).  Another such project is a set
 3020: of words to help dealing with strings.
 3021: 
 3022: On the other hand, there is a useful set of record words, and it has
 3023: been defined in @file{compat/struct.fs}; these words are predefined in
 3024: Gforth.  They are explained in depth elsewhere in this manual (see
 3025: @pxref{Structures}).  The @code{simple-field} example above is
 3026: simplified variant of fields in this package.
 3027: 
 3028: 
 3029: @node POSTPONE Tutorial, Literal Tutorial, Arrays and Records Tutorial, Tutorial
 3030: @section @code{POSTPONE}
 3031: @cindex postpone tutorial
 3032: 
 3033: You can compile the compilation semantics (instead of compiling the
 3034: interpretation semantics) of a word with @code{POSTPONE}:
 3035: 
 3036: @example
 3037: : MY-+ ( Compilation: -- ; Run-time of compiled code: n1 n2 -- n )
 3038:  POSTPONE + ; immediate
 3039: : foo ( n1 n2 -- n )
 3040:  MY-+ ;
 3041: 1 2 foo .
 3042: see foo
 3043: @end example
 3044: 
 3045: During the definition of @code{foo} the text interpreter performs the
 3046: compilation semantics of @code{MY-+}, which performs the compilation
 3047: semantics of @code{+}, i.e., it compiles @code{+} into @code{foo}.
 3048: 
 3049: This example also displays separate stack comments for the compilation
 3050: semantics and for the stack effect of the compiled code.  For words with
 3051: default compilation semantics these stack effects are usually not
 3052: displayed; the stack effect of the compilation semantics is always
 3053: @code{( -- )} for these words, the stack effect for the compiled code is
 3054: the stack effect of the interpretation semantics.
 3055: 
 3056: Note that the state of the interpreter does not come into play when
 3057: performing the compilation semantics in this way.  You can also perform
 3058: it interpretively, e.g.:
 3059: 
 3060: @example
 3061: : foo2 ( n1 n2 -- n )
 3062:  [ MY-+ ] ;
 3063: 1 2 foo .
 3064: see foo
 3065: @end example
 3066: 
 3067: However, there are some broken Forth systems where this does not always
 3068: work, and therefore this practice was been declared non-standard in
 3069: 1999.
 3070: @c !! repair.fs
 3071: 
 3072: Here is another example for using @code{POSTPONE}:
 3073: 
 3074: @example
 3075: : MY-- ( Compilation: -- ; Run-time of compiled code: n1 n2 -- n )
 3076:  POSTPONE negate POSTPONE + ; immediate compile-only
 3077: : bar ( n1 n2 -- n )
 3078:   MY-- ;
 3079: 2 1 bar .
 3080: see bar
 3081: @end example
 3082: 
 3083: You can define @code{ENDIF} in this way:
 3084: 
 3085: @example
 3086: : ENDIF ( Compilation: orig -- )
 3087:   POSTPONE then ; immediate
 3088: @end example
 3089: 
 3090: @quotation Assignment
 3091: Write @code{MY-2DUP} that has compilation semantics equivalent to
 3092: @code{2dup}, but compiles @code{over over}.
 3093: @end quotation
 3094: 
 3095: @c !! @xref{Macros} for reference
 3096: 
 3097: 
 3098: @node Literal Tutorial, Advanced macros Tutorial, POSTPONE Tutorial, Tutorial
 3099: @section @code{Literal}
 3100: @cindex literal tutorial
 3101: 
 3102: You cannot @code{POSTPONE} numbers:
 3103: 
 3104: @example
 3105: : [FOO] POSTPONE 500 ; immediate
 3106: @end example
 3107: 
 3108: Instead, you can use @code{LITERAL (compilation: n --; run-time: -- n )}:
 3109: 
 3110: @example
 3111: : [FOO] ( compilation: --; run-time: -- n )
 3112:   500 POSTPONE literal ; immediate
 3113: 
 3114: : flip [FOO] ;
 3115: flip .
 3116: see flip
 3117: @end example
 3118: 
 3119: @code{LITERAL} consumes a number at compile-time (when it's compilation
 3120: semantics are executed) and pushes it at run-time (when the code it
 3121: compiled is executed).  A frequent use of @code{LITERAL} is to compile a
 3122: number computed at compile time into the current word:
 3123: 
 3124: @example
 3125: : bar ( -- n )
 3126:   [ 2 2 + ] literal ;
 3127: see bar
 3128: @end example
 3129: 
 3130: @quotation Assignment
 3131: Write @code{]L} which allows writing the example above as @code{: bar (
 3132: -- n ) [ 2 2 + ]L ;}
 3133: @end quotation
 3134: 
 3135: @c !! @xref{Macros} for reference
 3136: 
 3137: 
 3138: @node Advanced macros Tutorial, Compilation Tokens Tutorial, Literal Tutorial, Tutorial
 3139: @section Advanced macros
 3140: @cindex macros, advanced tutorial
 3141: @cindex run-time code generation, tutorial
 3142: 
 3143: Reconsider @code{map-array} from @ref{Execution Tokens Tutorial,,
 3144: Execution Tokens}.  It frequently performs @code{execute}, a relatively
 3145: expensive operation in some Forth implementations.  You can use
 3146: @code{compile,} and @code{POSTPONE} to eliminate these @code{execute}s
 3147: and produce a word that contains the word to be performed directly:
 3148: 
 3149: @c use ]] ... [[
 3150: @example
 3151: : compile-map-array ( compilation: xt -- ; run-time: ... addr u -- ... )
 3152: \ at run-time, execute xt ( ... x -- ... ) for each element of the
 3153: \ array beginning at addr and containing u elements
 3154:   @{ xt @}
 3155:   POSTPONE cells POSTPONE over POSTPONE + POSTPONE swap POSTPONE ?do
 3156:     POSTPONE i POSTPONE @@ xt compile,
 3157:   1 cells POSTPONE literal POSTPONE +loop ;
 3158: 
 3159: : sum-array ( addr u -- n )
 3160:  0 rot rot [ ' + compile-map-array ] ;
 3161: see sum-array
 3162: a 5 sum-array .
 3163: @end example
 3164: 
 3165: You can use the full power of Forth for generating the code; here's an
 3166: example where the code is generated in a loop:
 3167: 
 3168: @example
 3169: : compile-vmul-step ( compilation: n --; run-time: n1 addr1 -- n2 addr2 )
 3170: \ n2=n1+(addr1)*n, addr2=addr1+cell
 3171:   POSTPONE tuck POSTPONE @@
 3172:   POSTPONE literal POSTPONE * POSTPONE +
 3173:   POSTPONE swap POSTPONE cell+ ;
 3174: 
 3175: : compile-vmul ( compilation: addr1 u -- ; run-time: addr2 -- n )
 3176: \ n=v1*v2 (inner product), where the v_i are represented as addr_i u
 3177:   0 postpone literal postpone swap
 3178:   [ ' compile-vmul-step compile-map-array ]
 3179:   postpone drop ;
 3180: see compile-vmul
 3181: 
 3182: : a-vmul ( addr -- n )
 3183: \ n=a*v, where v is a vector that's as long as a and starts at addr
 3184:  [ a 5 compile-vmul ] ;
 3185: see a-vmul
 3186: a a-vmul .
 3187: @end example
 3188: 
 3189: This example uses @code{compile-map-array} to show off, but you could
 3190: also use @code{map-array} instead (try it now!).
 3191: 
 3192: You can use this technique for efficient multiplication of large
 3193: matrices.  In matrix multiplication, you multiply every line of one
 3194: matrix with every column of the other matrix.  You can generate the code
 3195: for one line once, and use it for every column.  The only downside of
 3196: this technique is that it is cumbersome to recover the memory consumed
 3197: by the generated code when you are done (and in more complicated cases
 3198: it is not possible portably).
 3199: 
 3200: @c !! @xref{Macros} for reference
 3201: 
 3202: 
 3203: @node Compilation Tokens Tutorial, Wordlists and Search Order Tutorial, Advanced macros Tutorial, Tutorial
 3204: @section Compilation Tokens
 3205: @cindex compilation tokens, tutorial
 3206: @cindex CT, tutorial
 3207: 
 3208: This section is Gforth-specific.  You can skip it.
 3209: 
 3210: @code{' word compile,} compiles the interpretation semantics.  For words
 3211: with default compilation semantics this is the same as performing the
 3212: compilation semantics.  To represent the compilation semantics of other
 3213: words (e.g., words like @code{if} that have no interpretation
 3214: semantics), Gforth has the concept of a compilation token (CT,
 3215: consisting of two cells), and words @code{comp'} and @code{[comp']}.
 3216: You can perform the compilation semantics represented by a CT with
 3217: @code{execute}:
 3218: 
 3219: @example
 3220: : foo2 ( n1 n2 -- n )
 3221:    [ comp' + execute ] ;
 3222: see foo
 3223: @end example
 3224: 
 3225: You can compile the compilation semantics represented by a CT with
 3226: @code{postpone,}:
 3227: 
 3228: @example
 3229: : foo3 ( -- )
 3230:   [ comp' + postpone, ] ;
 3231: see foo3
 3232: @end example
 3233: 
 3234: @code{[ comp' word postpone, ]} is equivalent to @code{POSTPONE word}.
 3235: @code{comp'} is particularly useful for words that have no
 3236: interpretation semantics:
 3237: 
 3238: @example
 3239: ' if
 3240: comp' if .s 2drop
 3241: @end example
 3242: 
 3243: Reference: @ref{Tokens for Words}.
 3244: 
 3245: 
 3246: @node Wordlists and Search Order Tutorial,  , Compilation Tokens Tutorial, Tutorial
 3247: @section Wordlists and Search Order
 3248: @cindex wordlists tutorial
 3249: @cindex search order, tutorial
 3250: 
 3251: The dictionary is not just a memory area that allows you to allocate
 3252: memory with @code{allot}, it also contains the Forth words, arranged in
 3253: several wordlists.  When searching for a word in a wordlist,
 3254: conceptually you start searching at the youngest and proceed towards
 3255: older words (in reality most systems nowadays use hash-tables); i.e., if
 3256: you define a word with the same name as an older word, the new word
 3257: shadows the older word.
 3258: 
 3259: Which wordlists are searched in which order is determined by the search
 3260: order.  You can display the search order with @code{order}.  It displays
 3261: first the search order, starting with the wordlist searched first, then
 3262: it displays the wordlist that will contain newly defined words.
 3263: 
 3264: You can create a new, empty wordlist with @code{wordlist ( -- wid )}:
 3265: 
 3266: @example
 3267: wordlist constant mywords
 3268: @end example
 3269: 
 3270: @code{Set-current ( wid -- )} sets the wordlist that will contain newly
 3271: defined words (the @emph{current} wordlist):
 3272: 
 3273: @example
 3274: mywords set-current
 3275: order
 3276: @end example
 3277: 
 3278: Gforth does not display a name for the wordlist in @code{mywords}
 3279: because this wordlist was created anonymously with @code{wordlist}.
 3280: 
 3281: You can get the current wordlist with @code{get-current ( -- wid)}.  If
 3282: you want to put something into a specific wordlist without overall
 3283: effect on the current wordlist, this typically looks like this:
 3284: 
 3285: @example
 3286: get-current mywords set-current ( wid )
 3287: create someword
 3288: ( wid ) set-current
 3289: @end example
 3290: 
 3291: You can write the search order with @code{set-order ( wid1 .. widn n --
 3292: )} and read it with @code{get-order ( -- wid1 .. widn n )}.  The first
 3293: searched wordlist is topmost.
 3294: 
 3295: @example
 3296: get-order mywords swap 1+ set-order
 3297: order
 3298: @end example
 3299: 
 3300: Yes, the order of wordlists in the output of @code{order} is reversed
 3301: from stack comments and the output of @code{.s} and thus unintuitive.
 3302: 
 3303: @quotation Assignment
 3304: Define @code{>order ( wid -- )} with adds @code{wid} as first searched
 3305: wordlist to the search order.  Define @code{previous ( -- )}, which
 3306: removes the first searched wordlist from the search order.  Experiment
 3307: with boundary conditions (you will see some crashes or situations that
 3308: are hard or impossible to leave).
 3309: @end quotation
 3310: 
 3311: The search order is a powerful foundation for providing features similar
 3312: to Modula-2 modules and C++ namespaces.  However, trying to modularize
 3313: programs in this way has disadvantages for debugging and reuse/factoring
 3314: that overcome the advantages in my experience (I don't do huge projects,
 3315: though).  These disadvantages are not so clear in other
 3316: languages/programming environments, because these languages are not so
 3317: strong in debugging and reuse.
 3318: 
 3319: @c !! example
 3320: 
 3321: Reference: @ref{Word Lists}.
 3322: 
 3323: @c ******************************************************************
 3324: @node Introduction, Words, Tutorial, Top
 3325: @comment node-name,     next,           previous, up
 3326: @chapter An Introduction to ANS Forth
 3327: @cindex Forth - an introduction
 3328: 
 3329: The difference of this chapter from the Tutorial (@pxref{Tutorial}) is
 3330: that it is slower-paced in its examples, but uses them to dive deep into
 3331: explaining Forth internals (not covered by the Tutorial).  Apart from
 3332: that, this chapter covers far less material.  It is suitable for reading
 3333: without using a computer.
 3334: 
 3335: The primary purpose of this manual is to document Gforth. However, since
 3336: Forth is not a widely-known language and there is a lack of up-to-date
 3337: teaching material, it seems worthwhile to provide some introductory
 3338: material.  For other sources of Forth-related
 3339: information, see @ref{Forth-related information}.
 3340: 
 3341: The examples in this section should work on any ANS Forth; the
 3342: output shown was produced using Gforth. Each example attempts to
 3343: reproduce the exact output that Gforth produces. If you try out the
 3344: examples (and you should), what you should type is shown @kbd{like this}
 3345: and Gforth's response is shown @code{like this}. The single exception is
 3346: that, where the example shows @key{RET} it means that you should
 3347: press the ``carriage return'' key. Unfortunately, some output formats for
 3348: this manual cannot show the difference between @kbd{this} and
 3349: @code{this} which will make trying out the examples harder (but not
 3350: impossible).
 3351: 
 3352: Forth is an unusual language. It provides an interactive development
 3353: environment which includes both an interpreter and compiler. Forth
 3354: programming style encourages you to break a problem down into many
 3355: @cindex factoring
 3356: small fragments (@dfn{factoring}), and then to develop and test each
 3357: fragment interactively. Forth advocates assert that breaking the
 3358: edit-compile-test cycle used by conventional programming languages can
 3359: lead to great productivity improvements.
 3360: 
 3361: @menu
 3362: * Introducing the Text Interpreter::  
 3363: * Stacks and Postfix notation::  
 3364: * Your first definition::       
 3365: * How does that work?::         
 3366: * Forth is written in Forth::   
 3367: * Review - elements of a Forth system::  
 3368: * Where to go next::            
 3369: * Exercises::                   
 3370: @end menu
 3371: 
 3372: @comment ----------------------------------------------
 3373: @node Introducing the Text Interpreter, Stacks and Postfix notation, Introduction, Introduction
 3374: @section Introducing the Text Interpreter
 3375: @cindex text interpreter
 3376: @cindex outer interpreter
 3377: 
 3378: @c IMO this is too detailed and the pace is too slow for
 3379: @c an introduction.  If you know German, take a look at
 3380: @c http://www.complang.tuwien.ac.at/anton/lvas/skriptum-stack.html 
 3381: @c to see how I do it - anton 
 3382: 
 3383: @c nac-> Where I have accepted your comments 100% and modified the text
 3384: @c accordingly, I have deleted your comments. Elsewhere I have added a
 3385: @c response like this to attempt to rationalise what I have done. Of
 3386: @c course, this is a very clumsy mechanism for something that would be
 3387: @c done far more efficiently over a beer. Please delete any dialogue
 3388: @c you consider closed.
 3389: 
 3390: When you invoke the Forth image, you will see a startup banner printed
 3391: and nothing else (if you have Gforth installed on your system, try
 3392: invoking it now, by typing @kbd{gforth@key{RET}}). Forth is now running
 3393: its command line interpreter, which is called the @dfn{Text Interpreter}
 3394: (also known as the @dfn{Outer Interpreter}).  (You will learn a lot
 3395: about the text interpreter as you read through this chapter, for more
 3396: detail @pxref{The Text Interpreter}).
 3397: 
 3398: Although it's not obvious, Forth is actually waiting for your
 3399: input. Type a number and press the @key{RET} key:
 3400: 
 3401: @example
 3402: @kbd{45@key{RET}}  ok
 3403: @end example
 3404: 
 3405: Rather than give you a prompt to invite you to input something, the text
 3406: interpreter prints a status message @i{after} it has processed a line
 3407: of input. The status message in this case (``@code{ ok}'' followed by
 3408: carriage-return) indicates that the text interpreter was able to process
 3409: all of your input successfully. Now type something illegal:
 3410: 
 3411: @example
 3412: @kbd{qwer341@key{RET}}
 3413: *the terminal*:2: Undefined word
 3414: >>>qwer341<<<
 3415: Backtrace:
 3416: $2A95B42A20 throw 
 3417: $2A95B57FB8 no.extensions 
 3418: @end example
 3419: 
 3420: The exact text, other than the ``Undefined word'' may differ slightly
 3421: on your system, but the effect is the same; when the text interpreter
 3422: detects an error, it discards any remaining text on a line, resets
 3423: certain internal state and prints an error message. For a detailed
 3424: description of error messages see @ref{Error messages}.
 3425: 
 3426: The text interpreter waits for you to press carriage-return, and then
 3427: processes your input line. Starting at the beginning of the line, it
 3428: breaks the line into groups of characters separated by spaces. For each
 3429: group of characters in turn, it makes two attempts to do something:
 3430: 
 3431: @itemize @bullet
 3432: @item
 3433: @cindex name dictionary
 3434: It tries to treat it as a command. It does this by searching a @dfn{name
 3435: dictionary}. If the group of characters matches an entry in the name
 3436: dictionary, the name dictionary provides the text interpreter with
 3437: information that allows the text interpreter perform some actions. In
 3438: Forth jargon, we say that the group
 3439: @cindex word
 3440: @cindex definition
 3441: @cindex execution token
 3442: @cindex xt
 3443: of characters names a @dfn{word}, that the dictionary search returns an
 3444: @dfn{execution token (xt)} corresponding to the @dfn{definition} of the
 3445: word, and that the text interpreter executes the xt. Often, the terms
 3446: @dfn{word} and @dfn{definition} are used interchangeably.
 3447: @item
 3448: If the text interpreter fails to find a match in the name dictionary, it
 3449: tries to treat the group of characters as a number in the current number
 3450: base (when you start up Forth, the current number base is base 10). If
 3451: the group of characters legitimately represents a number, the text
 3452: interpreter pushes the number onto a stack (we'll learn more about that
 3453: in the next section).
 3454: @end itemize
 3455: 
 3456: If the text interpreter is unable to do either of these things with any
 3457: group of characters, it discards the group of characters and the rest of
 3458: the line, then prints an error message. If the text interpreter reaches
 3459: the end of the line without error, it prints the status message ``@code{ ok}''
 3460: followed by carriage-return.
 3461: 
 3462: This is the simplest command we can give to the text interpreter:
 3463: 
 3464: @example
 3465: @key{RET}  ok
 3466: @end example
 3467: 
 3468: The text interpreter did everything we asked it to do (nothing) without
 3469: an error, so it said that everything is ``@code{ ok}''. Try a slightly longer
 3470: command:
 3471: 
 3472: @example
 3473: @kbd{12 dup fred dup@key{RET}}
 3474: *the terminal*:3: Undefined word
 3475: 12 dup >>>fred<<< dup
 3476: Backtrace:
 3477: $2A95B42A20 throw 
 3478: $2A95B57FB8 no.extensions 
 3479: @end example
 3480: 
 3481: When you press the carriage-return key, the text interpreter starts to
 3482: work its way along the line:
 3483: 
 3484: @itemize @bullet
 3485: @item
 3486: When it gets to the space after the @code{2}, it takes the group of
 3487: characters @code{12} and looks them up in the name
 3488: dictionary@footnote{We can't tell if it found them or not, but assume
 3489: for now that it did not}. There is no match for this group of characters
 3490: in the name dictionary, so it tries to treat them as a number. It is
 3491: able to do this successfully, so it puts the number, 12, ``on the stack''
 3492: (whatever that means).
 3493: @item
 3494: The text interpreter resumes scanning the line and gets the next group
 3495: of characters, @code{dup}. It looks it up in the name dictionary and
 3496: (you'll have to take my word for this) finds it, and executes the word
 3497: @code{dup} (whatever that means).
 3498: @item
 3499: Once again, the text interpreter resumes scanning the line and gets the
 3500: group of characters @code{fred}. It looks them up in the name
 3501: dictionary, but can't find them. It tries to treat them as a number, but
 3502: they don't represent any legal number.
 3503: @end itemize
 3504: 
 3505: At this point, the text interpreter gives up and prints an error
 3506: message. The error message shows exactly how far the text interpreter
 3507: got in processing the line. In particular, it shows that the text
 3508: interpreter made no attempt to do anything with the final character
 3509: group, @code{dup}, even though we have good reason to believe that the
 3510: text interpreter would have no problem looking that word up and
 3511: executing it a second time.
 3512: 
 3513: 
 3514: @comment ----------------------------------------------
 3515: @node Stacks and Postfix notation, Your first definition, Introducing the Text Interpreter, Introduction
 3516: @section Stacks, postfix notation and parameter passing
 3517: @cindex text interpreter
 3518: @cindex outer interpreter
 3519: 
 3520: In procedural programming languages (like C and Pascal), the
 3521: building-block of programs is the @dfn{function} or @dfn{procedure}. These
 3522: functions or procedures are called with @dfn{explicit parameters}. For
 3523: example, in C we might write:
 3524: 
 3525: @example
 3526: total = total + new_volume(length,height,depth);
 3527: @end example
 3528: 
 3529: @noindent
 3530: where new_volume is a function-call to another piece of code, and total,
 3531: length, height and depth are all variables. length, height and depth are
 3532: parameters to the function-call.
 3533: 
 3534: In Forth, the equivalent of the function or procedure is the
 3535: @dfn{definition} and parameters are implicitly passed between
 3536: definitions using a shared stack that is visible to the
 3537: programmer. Although Forth does support variables, the existence of the
 3538: stack means that they are used far less often than in most other
 3539: programming languages. When the text interpreter encounters a number, it
 3540: will place (@dfn{push}) it on the stack. There are several stacks (the
 3541: actual number is implementation-dependent ...) and the particular stack
 3542: used for any operation is implied unambiguously by the operation being
 3543: performed. The stack used for all integer operations is called the @dfn{data
 3544: stack} and, since this is the stack used most commonly, references to
 3545: ``the data stack'' are often abbreviated to ``the stack''.
 3546: 
 3547: The stacks have a last-in, first-out (LIFO) organisation. If you type:
 3548: 
 3549: @example
 3550: @kbd{1 2 3@key{RET}}  ok
 3551: @end example
 3552: 
 3553: Then this instructs the text interpreter to placed three numbers on the
 3554: (data) stack. An analogy for the behaviour of the stack is to take a
 3555: pack of playing cards and deal out the ace (1), 2 and 3 into a pile on
 3556: the table. The 3 was the last card onto the pile (``last-in'') and if
 3557: you take a card off the pile then, unless you're prepared to fiddle a
 3558: bit, the card that you take off will be the 3 (``first-out''). The
 3559: number that will be first-out of the stack is called the @dfn{top of
 3560: stack}, which
 3561: @cindex TOS definition
 3562: is often abbreviated to @dfn{TOS}.
 3563: 
 3564: To understand how parameters are passed in Forth, consider the
 3565: behaviour of the definition @code{+} (pronounced ``plus''). You will not
 3566: be surprised to learn that this definition performs addition. More
 3567: precisely, it adds two number together and produces a result. Where does
 3568: it get the two numbers from? It takes the top two numbers off the
 3569: stack. Where does it place the result? On the stack. You can act-out the
 3570: behaviour of @code{+} with your playing cards like this:
 3571: 
 3572: @itemize @bullet
 3573: @item
 3574: Pick up two cards from the stack on the table
 3575: @item
 3576: Stare at them intently and ask yourself ``what @i{is} the sum of these two
 3577: numbers''
 3578: @item
 3579: Decide that the answer is 5
 3580: @item
 3581: Shuffle the two cards back into the pack and find a 5
 3582: @item
 3583: Put a 5 on the remaining ace that's on the table.
 3584: @end itemize
 3585: 
 3586: If you don't have a pack of cards handy but you do have Forth running,
 3587: you can use the definition @code{.s} to show the current state of the stack,
 3588: without affecting the stack. Type:
 3589: 
 3590: @example
 3591: @kbd{clearstacks 1 2 3@key{RET}} ok
 3592: @kbd{.s@key{RET}} <3> 1 2 3  ok
 3593: @end example
 3594: 
 3595: The text interpreter looks up the word @code{clearstacks} and executes
 3596: it; it tidies up the stacks and removes any entries that may have been
 3597: left on it by earlier examples. The text interpreter pushes each of the
 3598: three numbers in turn onto the stack. Finally, the text interpreter
 3599: looks up the word @code{.s} and executes it. The effect of executing
 3600: @code{.s} is to print the ``<3>'' (the total number of items on the stack)
 3601: followed by a list of all the items on the stack; the item on the far
 3602: right-hand side is the TOS.
 3603: 
 3604: You can now type:
 3605: 
 3606: @example
 3607: @kbd{+ .s@key{RET}} <2> 1 5  ok
 3608: @end example
 3609: 
 3610: @noindent
 3611: which is correct; there are now 2 items on the stack and the result of
 3612: the addition is 5.
 3613: 
 3614: If you're playing with cards, try doing a second addition: pick up the
 3615: two cards, work out that their sum is 6, shuffle them into the pack,
 3616: look for a 6 and place that on the table. You now have just one item on
 3617: the stack. What happens if you try to do a third addition? Pick up the
 3618: first card, pick up the second card -- ah! There is no second card. This
 3619: is called a @dfn{stack underflow} and consitutes an error. If you try to
 3620: do the same thing with Forth it often reports an error (probably a Stack
 3621: Underflow or an Invalid Memory Address error).
 3622: 
 3623: The opposite situation to a stack underflow is a @dfn{stack overflow},
 3624: which simply accepts that there is a finite amount of storage space
 3625: reserved for the stack. To stretch the playing card analogy, if you had
 3626: enough packs of cards and you piled the cards up on the table, you would
 3627: eventually be unable to add another card; you'd hit the ceiling. Gforth
 3628: allows you to set the maximum size of the stacks. In general, the only
 3629: time that you will get a stack overflow is because a definition has a
 3630: bug in it and is generating data on the stack uncontrollably.
 3631: 
 3632: There's one final use for the playing card analogy. If you model your
 3633: stack using a pack of playing cards, the maximum number of items on
 3634: your stack will be 52 (I assume you didn't use the Joker). The maximum
 3635: @i{value} of any item on the stack is 13 (the King). In fact, the only
 3636: possible numbers are positive integer numbers 1 through 13; you can't
 3637: have (for example) 0 or 27 or 3.52 or -2. If you change the way you
 3638: think about some of the cards, you can accommodate different
 3639: numbers. For example, you could think of the Jack as representing 0,
 3640: the Queen as representing -1 and the King as representing -2. Your
 3641: @i{range} remains unchanged (you can still only represent a total of 13
 3642: numbers) but the numbers that you can represent are -2 through 10.
 3643: 
 3644: In that analogy, the limit was the amount of information that a single
 3645: stack entry could hold, and Forth has a similar limit. In Forth, the
 3646: size of a stack entry is called a @dfn{cell}. The actual size of a cell is
 3647: implementation dependent and affects the maximum value that a stack
 3648: entry can hold. A Standard Forth provides a cell size of at least
 3649: 16-bits, and most desktop systems use a cell size of 32-bits.
 3650: 
 3651: Forth does not do any type checking for you, so you are free to
 3652: manipulate and combine stack items in any way you wish. A convenient way
 3653: of treating stack items is as 2's complement signed integers, and that
 3654: is what Standard words like @code{+} do. Therefore you can type:
 3655: 
 3656: @example
 3657: @kbd{-5 12 + .s@key{RET}} <1> 7  ok
 3658: @end example
 3659: 
 3660: If you use numbers and definitions like @code{+} in order to turn Forth
 3661: into a great big pocket calculator, you will realise that it's rather
 3662: different from a normal calculator. Rather than typing 2 + 3 = you had
 3663: to type 2 3 + (ignore the fact that you had to use @code{.s} to see the
 3664: result). The terminology used to describe this difference is to say that
 3665: your calculator uses @dfn{Infix Notation} (parameters and operators are
 3666: mixed) whilst Forth uses @dfn{Postfix Notation} (parameters and
 3667: operators are separate), also called @dfn{Reverse Polish Notation}.
 3668: 
 3669: Whilst postfix notation might look confusing to begin with, it has
 3670: several important advantages:
 3671: 
 3672: @itemize @bullet
 3673: @item
 3674: it is unambiguous
 3675: @item
 3676: it is more concise
 3677: @item
 3678: it fits naturally with a stack-based system
 3679: @end itemize
 3680: 
 3681: To examine these claims in more detail, consider these sums:
 3682: 
 3683: @example
 3684: 6 + 5 * 4 =
 3685: 4 * 5 + 6 =
 3686: @end example
 3687: 
 3688: If you're just learning maths or your maths is very rusty, you will
 3689: probably come up with the answer 44 for the first and 26 for the
 3690: second. If you are a bit of a whizz at maths you will remember the
 3691: @i{convention} that multiplication takes precendence over addition, and
 3692: you'd come up with the answer 26 both times. To explain the answer 26
 3693: to someone who got the answer 44, you'd probably rewrite the first sum
 3694: like this:
 3695: 
 3696: @example
 3697: 6 + (5 * 4) =
 3698: @end example
 3699: 
 3700: If what you really wanted was to perform the addition before the
 3701: multiplication, you would have to use parentheses to force it.
 3702: 
 3703: If you did the first two sums on a pocket calculator you would probably
 3704: get the right answers, unless you were very cautious and entered them using
 3705: these keystroke sequences:
 3706: 
 3707: 6 + 5 = * 4 =
 3708: 4 * 5 = + 6 =
 3709: 
 3710: Postfix notation is unambiguous because the order that the operators
 3711: are applied is always explicit; that also means that parentheses are
 3712: never required. The operators are @i{active} (the act of quoting the
 3713: operator makes the operation occur) which removes the need for ``=''.
 3714: 
 3715: The sum 6 + 5 * 4 can be written (in postfix notation) in two
 3716: equivalent ways:
 3717: 
 3718: @example
 3719: 6 5 4 * +      or:
 3720: 5 4 * 6 +
 3721: @end example
 3722: 
 3723: An important thing that you should notice about this notation is that
 3724: the @i{order} of the numbers does not change; if you want to subtract
 3725: 2 from 10 you type @code{10 2 -}.
 3726: 
 3727: The reason that Forth uses postfix notation is very simple to explain: it
 3728: makes the implementation extremely simple, and it follows naturally from
 3729: using the stack as a mechanism for passing parameters. Another way of
 3730: thinking about this is to realise that all Forth definitions are
 3731: @i{active}; they execute as they are encountered by the text
 3732: interpreter. The result of this is that the syntax of Forth is trivially
 3733: simple.
 3734: 
 3735: 
 3736: 
 3737: @comment ----------------------------------------------
 3738: @node Your first definition, How does that work?, Stacks and Postfix notation, Introduction
 3739: @section Your first Forth definition
 3740: @cindex first definition
 3741: 
 3742: Until now, the examples we've seen have been trivial; we've just been
 3743: using Forth as a bigger-than-pocket calculator. Also, each calculation
 3744: we've shown has been a ``one-off'' -- to repeat it we'd need to type it in
 3745: again@footnote{That's not quite true. If you press the up-arrow key on
 3746: your keyboard you should be able to scroll back to any earlier command,
 3747: edit it and re-enter it.} In this section we'll see how to add new
 3748: words to Forth's vocabulary.
 3749: 
 3750: The easiest way to create a new word is to use a @dfn{colon
 3751: definition}. We'll define a few and try them out before worrying too
 3752: much about how they work. Try typing in these examples; be careful to
 3753: copy the spaces accurately:
 3754: 
 3755: @example
 3756: : add-two 2 + . ;
 3757: : greet ." Hello and welcome" ;
 3758: : demo 5 add-two ;
 3759: @end example
 3760: 
 3761: @noindent
 3762: Now try them out:
 3763: 
 3764: @example
 3765: @kbd{greet@key{RET}} Hello and welcome  ok
 3766: @kbd{greet greet@key{RET}} Hello and welcomeHello and welcome  ok
 3767: @kbd{4 add-two@key{RET}} 6  ok
 3768: @kbd{demo@key{RET}} 7  ok
 3769: @kbd{9 greet demo add-two@key{RET}} Hello and welcome7 11  ok
 3770: @end example
 3771: 
 3772: The first new thing that we've introduced here is the pair of words
 3773: @code{:} and @code{;}. These are used to start and terminate a new
 3774: definition, respectively. The first word after the @code{:} is the name
 3775: for the new definition.
 3776: 
 3777: As you can see from the examples, a definition is built up of words that
 3778: have already been defined; Forth makes no distinction between
 3779: definitions that existed when you started the system up, and those that
 3780: you define yourself.
 3781: 
 3782: The examples also introduce the words @code{.} (dot), @code{."}
 3783: (dot-quote) and @code{dup} (dewp). Dot takes the value from the top of
 3784: the stack and displays it. It's like @code{.s} except that it only
 3785: displays the top item of the stack and it is destructive; after it has
 3786: executed, the number is no longer on the stack. There is always one
 3787: space printed after the number, and no spaces before it. Dot-quote
 3788: defines a string (a sequence of characters) that will be printed when
 3789: the word is executed. The string can contain any printable characters
 3790: except @code{"}. A @code{"} has a special function; it is not a Forth
 3791: word but it acts as a delimiter (the way that delimiters work is
 3792: described in the next section). Finally, @code{dup} duplicates the value
 3793: at the top of the stack. Try typing @code{5 dup .s} to see what it does.
 3794: 
 3795: We already know that the text interpreter searches through the
 3796: dictionary to locate names. If you've followed the examples earlier, you
 3797: will already have a definition called @code{add-two}. Lets try modifying
 3798: it by typing in a new definition:
 3799: 
 3800: @example
 3801: @kbd{: add-two dup . ." + 2 =" 2 + . ;@key{RET}} redefined add-two  ok
 3802: @end example
 3803: 
 3804: Forth recognised that we were defining a word that already exists, and
 3805: printed a message to warn us of that fact. Let's try out the new
 3806: definition:
 3807: 
 3808: @example
 3809: @kbd{9 add-two@key{RET}} 9 + 2 =11  ok
 3810: @end example
 3811: 
 3812: @noindent
 3813: All that we've actually done here, though, is to create a new
 3814: definition, with a particular name. The fact that there was already a
 3815: definition with the same name did not make any difference to the way
 3816: that the new definition was created (except that Forth printed a warning
 3817: message). The old definition of add-two still exists (try @code{demo}
 3818: again to see that this is true). Any new definition will use the new
 3819: definition of @code{add-two}, but old definitions continue to use the
 3820: version that already existed at the time that they were @code{compiled}.
 3821: 
 3822: Before you go on to the next section, try defining and redefining some
 3823: words of your own.
 3824: 
 3825: @comment ----------------------------------------------
 3826: @node How does that work?, Forth is written in Forth, Your first definition, Introduction
 3827: @section How does that work?
 3828: @cindex parsing words
 3829: 
 3830: @c That's pretty deep (IMO way too deep) for an introduction. - anton
 3831: 
 3832: @c Is it a good idea to talk about the interpretation semantics of a
 3833: @c number? We don't have an xt to go along with it. - anton
 3834: 
 3835: @c Now that I have eliminated execution semantics, I wonder if it would not
 3836: @c be better to keep them (or add run-time semantics), to make it easier to
 3837: @c explain what compilation semantics usually does. - anton
 3838: 
 3839: @c nac-> I removed the term ``default compilation sematics'' from the
 3840: @c introductory chapter. Removing ``execution semantics'' was making
 3841: @c everything simpler to explain, then I think the use of this term made
 3842: @c everything more complex again. I replaced it with ``default
 3843: @c semantics'' (which is used elsewhere in the manual) by which I mean
 3844: @c ``a definition that has neither the immediate nor the compile-only
 3845: @c flag set''.
 3846: 
 3847: @c anton: I have eliminated default semantics (except in one place where it
 3848: @c means "default interpretation and compilation semantics"), because it
 3849: @c makes no sense in the presence of combined words.  I reverted to
 3850: @c "execution semantics" where necessary.
 3851: 
 3852: @c nac-> I reworded big chunks of the ``how does that work''
 3853: @c section (and, unusually for me, I think I even made it shorter!).  See
 3854: @c what you think -- I know I have not addressed your primary concern
 3855: @c that it is too heavy-going for an introduction. From what I understood
 3856: @c of your course notes it looks as though they might be a good framework. 
 3857: @c Things that I've tried to capture here are some things that came as a
 3858: @c great revelation here when I first understood them. Also, I like the
 3859: @c fact that a very simple code example shows up almost all of the issues
 3860: @c that you need to understand to see how Forth works. That's unique and
 3861: @c worthwhile to emphasise.
 3862: 
 3863: @c anton: I think it's a good idea to present the details, especially those
 3864: @c that you found to be a revelation, and probably the tutorial tries to be
 3865: @c too superficial and does not get some of the things across that make
 3866: @c Forth special.  I do believe that most of the time these things should
 3867: @c be discussed at the end of a section or in separate sections instead of
 3868: @c in the middle of a section (e.g., the stuff you added in "User-defined
 3869: @c defining words" leads in a completely different direction from the rest
 3870: @c of the section).
 3871: 
 3872: Now we're going to take another look at the definition of @code{add-two}
 3873: from the previous section. From our knowledge of the way that the text
 3874: interpreter works, we would have expected this result when we tried to
 3875: define @code{add-two}:
 3876: 
 3877: @example
 3878: @kbd{: add-two 2 + . ;@key{RET}}
 3879: *the terminal*:4: Undefined word
 3880: : >>>add-two<<< 2 + . ;
 3881: @end example
 3882: 
 3883: The reason that this didn't happen is bound up in the way that @code{:}
 3884: works. The word @code{:} does two special things. The first special
 3885: thing that it does prevents the text interpreter from ever seeing the
 3886: characters @code{add-two}. The text interpreter uses a variable called
 3887: @cindex modifying >IN
 3888: @code{>IN} (pronounced ``to-in'') to keep track of where it is in the
 3889: input line. When it encounters the word @code{:} it behaves in exactly
 3890: the same way as it does for any other word; it looks it up in the name
 3891: dictionary, finds its xt and executes it. When @code{:} executes, it
 3892: looks at the input buffer, finds the word @code{add-two} and advances the
 3893: value of @code{>IN} to point past it. It then does some other stuff
 3894: associated with creating the new definition (including creating an entry
 3895: for @code{add-two} in the name dictionary). When the execution of @code{:}
 3896: completes, control returns to the text interpreter, which is oblivious
 3897: to the fact that it has been tricked into ignoring part of the input
 3898: line.
 3899: 
 3900: @cindex parsing words
 3901: Words like @code{:} -- words that advance the value of @code{>IN} and so
 3902: prevent the text interpreter from acting on the whole of the input line
 3903: -- are called @dfn{parsing words}.
 3904: 
 3905: @cindex @code{state} - effect on the text interpreter
 3906: @cindex text interpreter - effect of state
 3907: The second special thing that @code{:} does is change the value of a
 3908: variable called @code{state}, which affects the way that the text
 3909: interpreter behaves. When Gforth starts up, @code{state} has the value
 3910: 0, and the text interpreter is said to be @dfn{interpreting}. During a
 3911: colon definition (started with @code{:}), @code{state} is set to -1 and
 3912: the text interpreter is said to be @dfn{compiling}.
 3913: 
 3914: In this example, the text interpreter is compiling when it processes the
 3915: string ``@code{2 + . ;}''. It still breaks the string down into
 3916: character sequences in the same way. However, instead of pushing the
 3917: number @code{2} onto the stack, it lays down (@dfn{compiles}) some magic
 3918: into the definition of @code{add-two} that will make the number @code{2} get
 3919: pushed onto the stack when @code{add-two} is @dfn{executed}. Similarly,
 3920: the behaviours of @code{+} and @code{.} are also compiled into the
 3921: definition.
 3922: 
 3923: One category of words don't get compiled. These so-called @dfn{immediate
 3924: words} get executed (performed @i{now}) regardless of whether the text
 3925: interpreter is interpreting or compiling. The word @code{;} is an
 3926: immediate word. Rather than being compiled into the definition, it
 3927: executes. Its effect is to terminate the current definition, which
 3928: includes changing the value of @code{state} back to 0.
 3929: 
 3930: When you execute @code{add-two}, it has a @dfn{run-time effect} that is
 3931: exactly the same as if you had typed @code{2 + . @key{RET}} outside of a
 3932: definition.
 3933: 
 3934: In Forth, every word or number can be described in terms of two
 3935: properties:
 3936: 
 3937: @itemize @bullet
 3938: @item
 3939: @cindex interpretation semantics
 3940: Its @dfn{interpretation semantics} describe how it will behave when the
 3941: text interpreter encounters it in @dfn{interpret} state. The
 3942: interpretation semantics of a word are represented by an @dfn{execution
 3943: token}.
 3944: @item
 3945: @cindex compilation semantics
 3946: Its @dfn{compilation semantics} describe how it will behave when the
 3947: text interpreter encounters it in @dfn{compile} state. The compilation
 3948: semantics of a word are represented in an implementation-dependent way;
 3949: Gforth uses a @dfn{compilation token}.
 3950: @end itemize
 3951: 
 3952: @noindent
 3953: Numbers are always treated in a fixed way:
 3954: 
 3955: @itemize @bullet
 3956: @item
 3957: When the number is @dfn{interpreted}, its behaviour is to push the
 3958: number onto the stack.
 3959: @item
 3960: When the number is @dfn{compiled}, a piece of code is appended to the
 3961: current definition that pushes the number when it runs. (In other words,
 3962: the compilation semantics of a number are to postpone its interpretation
 3963: semantics until the run-time of the definition that it is being compiled
 3964: into.)
 3965: @end itemize
 3966: 
 3967: Words don't behave in such a regular way, but most have @i{default
 3968: semantics} which means that they behave like this:
 3969: 
 3970: @itemize @bullet
 3971: @item
 3972: The @dfn{interpretation semantics} of the word are to do something useful.
 3973: @item
 3974: The @dfn{compilation semantics} of the word are to append its
 3975: @dfn{interpretation semantics} to the current definition (so that its
 3976: run-time behaviour is to do something useful).
 3977: @end itemize
 3978: 
 3979: @cindex immediate words
 3980: The actual behaviour of any particular word can be controlled by using
 3981: the words @code{immediate} and @code{compile-only} when the word is
 3982: defined. These words set flags in the name dictionary entry of the most
 3983: recently defined word, and these flags are retrieved by the text
 3984: interpreter when it finds the word in the name dictionary.
 3985: 
 3986: A word that is marked as @dfn{immediate} has compilation semantics that
 3987: are identical to its interpretation semantics. In other words, it
 3988: behaves like this:
 3989: 
 3990: @itemize @bullet
 3991: @item
 3992: The @dfn{interpretation semantics} of the word are to do something useful.
 3993: @item
 3994: The @dfn{compilation semantics} of the word are to do something useful
 3995: (and actually the same thing); i.e., it is executed during compilation.
 3996: @end itemize
 3997: 
 3998: Marking a word as @dfn{compile-only} prohibits the text interpreter from
 3999: performing the interpretation semantics of the word directly; an attempt
 4000: to do so will generate an error. It is never necessary to use
 4001: @code{compile-only} (and it is not even part of ANS Forth, though it is
 4002: provided by many implementations) but it is good etiquette to apply it
 4003: to a word that will not behave correctly (and might have unexpected
 4004: side-effects) in interpret state. For example, it is only legal to use
 4005: the conditional word @code{IF} within a definition. If you forget this
 4006: and try to use it elsewhere, the fact that (in Gforth) it is marked as
 4007: @code{compile-only} allows the text interpreter to generate a helpful
 4008: error message rather than subjecting you to the consequences of your
 4009: folly.
 4010: 
 4011: This example shows the difference between an immediate and a
 4012: non-immediate word:
 4013: 
 4014: @example
 4015: : show-state state @@ . ;
 4016: : show-state-now show-state ; immediate
 4017: : word1 show-state ;
 4018: : word2 show-state-now ;
 4019: @end example
 4020: 
 4021: The word @code{immediate} after the definition of @code{show-state-now}
 4022: makes that word an immediate word. These definitions introduce a new
 4023: word: @code{@@} (pronounced ``fetch''). This word fetches the value of a
 4024: variable, and leaves it on the stack. Therefore, the behaviour of
 4025: @code{show-state} is to print a number that represents the current value
 4026: of @code{state}.
 4027: 
 4028: When you execute @code{word1}, it prints the number 0, indicating that
 4029: the system is interpreting. When the text interpreter compiled the
 4030: definition of @code{word1}, it encountered @code{show-state} whose
 4031: compilation semantics are to append its interpretation semantics to the
 4032: current definition. When you execute @code{word1}, it performs the
 4033: interpretation semantics of @code{show-state}.  At the time that @code{word1}
 4034: (and therefore @code{show-state}) are executed, the system is
 4035: interpreting.
 4036: 
 4037: When you pressed @key{RET} after entering the definition of @code{word2},
 4038: you should have seen the number -1 printed, followed by ``@code{
 4039: ok}''. When the text interpreter compiled the definition of
 4040: @code{word2}, it encountered @code{show-state-now}, an immediate word,
 4041: whose compilation semantics are therefore to perform its interpretation
 4042: semantics. It is executed straight away (even before the text
 4043: interpreter has moved on to process another group of characters; the
 4044: @code{;} in this example). The effect of executing it are to display the
 4045: value of @code{state} @i{at the time that the definition of}
 4046: @code{word2} @i{is being defined}. Printing -1 demonstrates that the
 4047: system is compiling at this time. If you execute @code{word2} it does
 4048: nothing at all.
 4049: 
 4050: @cindex @code{."}, how it works
 4051: Before leaving the subject of immediate words, consider the behaviour of
 4052: @code{."} in the definition of @code{greet}, in the previous
 4053: section. This word is both a parsing word and an immediate word. Notice
 4054: that there is a space between @code{."} and the start of the text
 4055: @code{Hello and welcome}, but that there is no space between the last
 4056: letter of @code{welcome} and the @code{"} character. The reason for this
 4057: is that @code{."} is a Forth word; it must have a space after it so that
 4058: the text interpreter can identify it. The @code{"} is not a Forth word;
 4059: it is a @dfn{delimiter}. The examples earlier show that, when the string
 4060: is displayed, there is neither a space before the @code{H} nor after the
 4061: @code{e}. Since @code{."} is an immediate word, it executes at the time
 4062: that @code{greet} is defined. When it executes, its behaviour is to
 4063: search forward in the input line looking for the delimiter. When it
 4064: finds the delimiter, it updates @code{>IN} to point past the
 4065: delimiter. It also compiles some magic code into the definition of
 4066: @code{greet}; the xt of a run-time routine that prints a text string. It
 4067: compiles the string @code{Hello and welcome} into memory so that it is
 4068: available to be printed later. When the text interpreter gains control,
 4069: the next word it finds in the input stream is @code{;} and so it
 4070: terminates the definition of @code{greet}.
 4071: 
 4072: 
 4073: @comment ----------------------------------------------
 4074: @node Forth is written in Forth, Review - elements of a Forth system, How does that work?, Introduction
 4075: @section Forth is written in Forth
 4076: @cindex structure of Forth programs
 4077: 
 4078: When you start up a Forth compiler, a large number of definitions
 4079: already exist. In Forth, you develop a new application using bottom-up
 4080: programming techniques to create new definitions that are defined in
 4081: terms of existing definitions. As you create each definition you can
 4082: test and debug it interactively.
 4083: 
 4084: If you have tried out the examples in this section, you will probably
 4085: have typed them in by hand; when you leave Gforth, your definitions will
 4086: be lost. You can avoid this by using a text editor to enter Forth source
 4087: code into a file, and then loading code from the file using
 4088: @code{include} (@pxref{Forth source files}). A Forth source file is
 4089: processed by the text interpreter, just as though you had typed it in by
 4090: hand@footnote{Actually, there are some subtle differences -- see
 4091: @ref{The Text Interpreter}.}.
 4092: 
 4093: Gforth also supports the traditional Forth alternative to using text
 4094: files for program entry (@pxref{Blocks}).
 4095: 
 4096: In common with many, if not most, Forth compilers, most of Gforth is
 4097: actually written in Forth. All of the @file{.fs} files in the
 4098: installation directory@footnote{For example,
 4099: @file{/usr/local/share/gforth...}} are Forth source files, which you can
 4100: study to see examples of Forth programming.
 4101: 
 4102: Gforth maintains a history file that records every line that you type to
 4103: the text interpreter. This file is preserved between sessions, and is
 4104: used to provide a command-line recall facility. If you enter long
 4105: definitions by hand, you can use a text editor to paste them out of the
 4106: history file into a Forth source file for reuse at a later time
 4107: (for more information @pxref{Command-line editing}).
 4108: 
 4109: 
 4110: @comment ----------------------------------------------
 4111: @node Review - elements of a Forth system, Where to go next, Forth is written in Forth, Introduction
 4112: @section Review - elements of a Forth system
 4113: @cindex elements of a Forth system
 4114: 
 4115: To summarise this chapter:
 4116: 
 4117: @itemize @bullet
 4118: @item
 4119: Forth programs use @dfn{factoring} to break a problem down into small
 4120: fragments called @dfn{words} or @dfn{definitions}.
 4121: @item
 4122: Forth program development is an interactive process.
 4123: @item
 4124: The main command loop that accepts input, and controls both
 4125: interpretation and compilation, is called the @dfn{text interpreter}
 4126: (also known as the @dfn{outer interpreter}).
 4127: @item
 4128: Forth has a very simple syntax, consisting of words and numbers
 4129: separated by spaces or carriage-return characters. Any additional syntax
 4130: is imposed by @dfn{parsing words}.
 4131: @item
 4132: Forth uses a stack to pass parameters between words. As a result, it
 4133: uses postfix notation.
 4134: @item
 4135: To use a word that has previously been defined, the text interpreter
 4136: searches for the word in the @dfn{name dictionary}.
 4137: @item
 4138: Words have @dfn{interpretation semantics} and @dfn{compilation semantics}.
 4139: @item
 4140: The text interpreter uses the value of @code{state} to select between
 4141: the use of the @dfn{interpretation semantics} and the  @dfn{compilation
 4142: semantics} of a word that it encounters.
 4143: @item
 4144: The relationship between the @dfn{interpretation semantics} and
 4145: @dfn{compilation semantics} for a word
 4146: depend upon the way in which the word was defined (for example, whether
 4147: it is an @dfn{immediate} word).
 4148: @item
 4149: Forth definitions can be implemented in Forth (called @dfn{high-level
 4150: definitions}) or in some other way (usually a lower-level language and
 4151: as a result often called @dfn{low-level definitions}, @dfn{code
 4152: definitions} or @dfn{primitives}).
 4153: @item
 4154: Many Forth systems are implemented mainly in Forth.
 4155: @end itemize
 4156: 
 4157: 
 4158: @comment ----------------------------------------------
 4159: @node Where to go next, Exercises, Review - elements of a Forth system, Introduction
 4160: @section Where To Go Next
 4161: @cindex where to go next
 4162: 
 4163: Amazing as it may seem, if you have read (and understood) this far, you
 4164: know almost all the fundamentals about the inner workings of a Forth
 4165: system. You certainly know enough to be able to read and understand the
 4166: rest of this manual and the ANS Forth document, to learn more about the
 4167: facilities that Forth in general and Gforth in particular provide. Even
 4168: scarier, you know almost enough to implement your own Forth system.
 4169: However, that's not a good idea just yet... better to try writing some
 4170: programs in Gforth.
 4171: 
 4172: Forth has such a rich vocabulary that it can be hard to know where to
 4173: start in learning it. This section suggests a few sets of words that are
 4174: enough to write small but useful programs. Use the word index in this
 4175: document to learn more about each word, then try it out and try to write
 4176: small definitions using it. Start by experimenting with these words:
 4177: 
 4178: @itemize @bullet
 4179: @item
 4180: Arithmetic: @code{+ - * / /MOD */ ABS INVERT}
 4181: @item
 4182: Comparison: @code{MIN MAX =}
 4183: @item
 4184: Logic: @code{AND OR XOR NOT}
 4185: @item
 4186: Stack manipulation: @code{DUP DROP SWAP OVER}
 4187: @item
 4188: Loops and decisions: @code{IF ELSE ENDIF ?DO I LOOP}
 4189: @item
 4190: Input/Output: @code{. ." EMIT CR KEY}
 4191: @item
 4192: Defining words: @code{: ; CREATE}
 4193: @item
 4194: Memory allocation words: @code{ALLOT ,}
 4195: @item
 4196: Tools: @code{SEE WORDS .S MARKER}
 4197: @end itemize
 4198: 
 4199: When you have mastered those, go on to:
 4200: 
 4201: @itemize @bullet
 4202: @item
 4203: More defining words: @code{VARIABLE CONSTANT VALUE TO CREATE DOES>}
 4204: @item
 4205: Memory access: @code{@@ !}
 4206: @end itemize
 4207: 
 4208: When you have mastered these, there's nothing for it but to read through
 4209: the whole of this manual and find out what you've missed.
 4210: 
 4211: @comment ----------------------------------------------
 4212: @node Exercises,  , Where to go next, Introduction
 4213: @section Exercises
 4214: @cindex exercises
 4215: 
 4216: TODO: provide a set of programming excercises linked into the stuff done
 4217: already and into other sections of the manual. Provide solutions to all
 4218: the exercises in a .fs file in the distribution.
 4219: 
 4220: @c Get some inspiration from Starting Forth and Kelly&Spies.
 4221: 
 4222: @c excercises:
 4223: @c 1. take inches and convert to feet and inches.
 4224: @c 2. take temperature and convert from fahrenheight to celcius;
 4225: @c    may need to care about symmetric vs floored??
 4226: @c 3. take input line and do character substitution
 4227: @c    to encipher or decipher
 4228: @c 4. as above but work on a file for in and out
 4229: @c 5. take input line and convert to pig-latin 
 4230: @c
 4231: @c thing of sets of things to exercise then come up with
 4232: @c problems that need those things.
 4233: 
 4234: 
 4235: @c ******************************************************************
 4236: @node Words, Error messages, Introduction, Top
 4237: @chapter Forth Words
 4238: @cindex words
 4239: 
 4240: @menu
 4241: * Notation::                    
 4242: * Case insensitivity::          
 4243: * Comments::                    
 4244: * Boolean Flags::               
 4245: * Arithmetic::                  
 4246: * Stack Manipulation::          
 4247: * Memory::                      
 4248: * Control Structures::          
 4249: * Defining Words::              
 4250: * Interpretation and Compilation Semantics::  
 4251: * Tokens for Words::            
 4252: * Compiling words::             
 4253: * The Text Interpreter::        
 4254: * The Input Stream::            
 4255: * Word Lists::                  
 4256: * Environmental Queries::       
 4257: * Files::                       
 4258: * Blocks::                      
 4259: * Other I/O::                   
 4260: * OS command line arguments::   
 4261: * Locals::                      
 4262: * Structures::                  
 4263: * Object-oriented Forth::       
 4264: * Programming Tools::           
 4265: * C Interface::                 
 4266: * Assembler and Code Words::    
 4267: * Threading Words::             
 4268: * Passing Commands to the OS::  
 4269: * Keeping track of Time::       
 4270: * Miscellaneous Words::         
 4271: @end menu
 4272: 
 4273: @node Notation, Case insensitivity, Words, Words
 4274: @section Notation
 4275: @cindex notation of glossary entries
 4276: @cindex format of glossary entries
 4277: @cindex glossary notation format
 4278: @cindex word glossary entry format
 4279: 
 4280: The Forth words are described in this section in the glossary notation
 4281: that has become a de-facto standard for Forth texts:
 4282: 
 4283: @format
 4284: @i{word}     @i{Stack effect}   @i{wordset}   @i{pronunciation}
 4285: @end format
 4286: @i{Description}
 4287: 
 4288: @table @var
 4289: @item word
 4290: The name of the word.
 4291: 
 4292: @item Stack effect
 4293: @cindex stack effect
 4294: The stack effect is written in the notation @code{@i{before} --
 4295: @i{after}}, where @i{before} and @i{after} describe the top of
 4296: stack entries before and after the execution of the word. The rest of
 4297: the stack is not touched by the word. The top of stack is rightmost,
 4298: i.e., a stack sequence is written as it is typed in. Note that Gforth
 4299: uses a separate floating point stack, but a unified stack
 4300: notation. Also, return stack effects are not shown in @i{stack
 4301: effect}, but in @i{Description}. The name of a stack item describes
 4302: the type and/or the function of the item. See below for a discussion of
 4303: the types.
 4304: 
 4305: All words have two stack effects: A compile-time stack effect and a
 4306: run-time stack effect. The compile-time stack-effect of most words is
 4307: @i{ -- }. If the compile-time stack-effect of a word deviates from
 4308: this standard behaviour, or the word does other unusual things at
 4309: compile time, both stack effects are shown; otherwise only the run-time
 4310: stack effect is shown.
 4311: 
 4312: @cindex pronounciation of words
 4313: @item pronunciation
 4314: How the word is pronounced.
 4315: 
 4316: @cindex wordset
 4317: @cindex environment wordset
 4318: @item wordset
 4319: The ANS Forth standard is divided into several word sets. A standard
 4320: system need not support all of them. Therefore, in theory, the fewer
 4321: word sets your program uses the more portable it will be. However, we
 4322: suspect that most ANS Forth systems on personal machines will feature
 4323: all word sets. Words that are not defined in ANS Forth have
 4324: @code{gforth} or @code{gforth-internal} as word set. @code{gforth}
 4325: describes words that will work in future releases of Gforth;
 4326: @code{gforth-internal} words are more volatile. Environmental query
 4327: strings are also displayed like words; you can recognize them by the
 4328: @code{environment} in the word set field.
 4329: 
 4330: @item Description
 4331: A description of the behaviour of the word.
 4332: @end table
 4333: 
 4334: @cindex types of stack items
 4335: @cindex stack item types
 4336: The type of a stack item is specified by the character(s) the name
 4337: starts with:
 4338: 
 4339: @table @code
 4340: @item f
 4341: @cindex @code{f}, stack item type
 4342: Boolean flags, i.e. @code{false} or @code{true}.
 4343: @item c
 4344: @cindex @code{c}, stack item type
 4345: Char
 4346: @item w
 4347: @cindex @code{w}, stack item type
 4348: Cell, can contain an integer or an address
 4349: @item n
 4350: @cindex @code{n}, stack item type
 4351: signed integer
 4352: @item u
 4353: @cindex @code{u}, stack item type
 4354: unsigned integer
 4355: @item d
 4356: @cindex @code{d}, stack item type
 4357: double sized signed integer
 4358: @item ud
 4359: @cindex @code{ud}, stack item type
 4360: double sized unsigned integer
 4361: @item r
 4362: @cindex @code{r}, stack item type
 4363: Float (on the FP stack)
 4364: @item a-
 4365: @cindex @code{a_}, stack item type
 4366: Cell-aligned address
 4367: @item c-
 4368: @cindex @code{c_}, stack item type
 4369: Char-aligned address (note that a Char may have two bytes in Windows NT)
 4370: @item f-
 4371: @cindex @code{f_}, stack item type
 4372: Float-aligned address
 4373: @item df-
 4374: @cindex @code{df_}, stack item type
 4375: Address aligned for IEEE double precision float
 4376: @item sf-
 4377: @cindex @code{sf_}, stack item type
 4378: Address aligned for IEEE single precision float
 4379: @item xt
 4380: @cindex @code{xt}, stack item type
 4381: Execution token, same size as Cell
 4382: @item wid
 4383: @cindex @code{wid}, stack item type
 4384: Word list ID, same size as Cell
 4385: @item ior, wior
 4386: @cindex ior type description
 4387: @cindex wior type description
 4388: I/O result code, cell-sized.  In Gforth, you can @code{throw} iors.
 4389: @item f83name
 4390: @cindex @code{f83name}, stack item type
 4391: Pointer to a name structure
 4392: @item "
 4393: @cindex @code{"}, stack item type
 4394: string in the input stream (not on the stack). The terminating character
 4395: is a blank by default. If it is not a blank, it is shown in @code{<>}
 4396: quotes.
 4397: @end table
 4398: 
 4399: @comment ----------------------------------------------
 4400: @node Case insensitivity, Comments, Notation, Words
 4401: @section Case insensitivity
 4402: @cindex case sensitivity
 4403: @cindex upper and lower case
 4404: 
 4405: Gforth is case-insensitive; you can enter definitions and invoke
 4406: Standard words using upper, lower or mixed case (however,
 4407: @pxref{core-idef, Implementation-defined options, Implementation-defined
 4408: options}).
 4409: 
 4410: ANS Forth only @i{requires} implementations to recognise Standard words
 4411: when they are typed entirely in upper case. Therefore, a Standard
 4412: program must use upper case for all Standard words. You can use whatever
 4413: case you like for words that you define, but in a Standard program you
 4414: have to use the words in the same case that you defined them.
 4415: 
 4416: Gforth supports case sensitivity through @code{table}s (case-sensitive
 4417: wordlists, @pxref{Word Lists}).
 4418: 
 4419: Two people have asked how to convert Gforth to be case-sensitive; while
 4420: we think this is a bad idea, you can change all wordlists into tables
 4421: like this:
 4422: 
 4423: @example
 4424: ' table-find forth-wordlist wordlist-map @ !
 4425: @end example
 4426: 
 4427: Note that you now have to type the predefined words in the same case
 4428: that we defined them, which are varying.  You may want to convert them
 4429: to your favourite case before doing this operation (I won't explain how,
 4430: because if you are even contemplating doing this, you'd better have
 4431: enough knowledge of Forth systems to know this already).
 4432: 
 4433: @node Comments, Boolean Flags, Case insensitivity, Words
 4434: @section Comments
 4435: @cindex comments
 4436: 
 4437: Forth supports two styles of comment; the traditional @i{in-line} comment,
 4438: @code{(} and its modern cousin, the @i{comment to end of line}; @code{\}.
 4439: 
 4440: 
 4441: doc-(
 4442: doc-\
 4443: doc-\G
 4444: 
 4445: 
 4446: @node Boolean Flags, Arithmetic, Comments, Words
 4447: @section Boolean Flags
 4448: @cindex Boolean flags
 4449: 
 4450: A Boolean flag is cell-sized. A cell with all bits clear represents the
 4451: flag @code{false} and a flag with all bits set represents the flag
 4452: @code{true}. Words that check a flag (for example, @code{IF}) will treat
 4453: a cell that has @i{any} bit set as @code{true}.
 4454: @c on and off to Memory? 
 4455: @c true and false to "Bitwise operations" or "Numeric comparison"?
 4456: 
 4457: doc-true
 4458: doc-false
 4459: doc-on
 4460: doc-off
 4461: 
 4462: 
 4463: @node Arithmetic, Stack Manipulation, Boolean Flags, Words
 4464: @section Arithmetic
 4465: @cindex arithmetic words
 4466: 
 4467: @cindex division with potentially negative operands
 4468: Forth arithmetic is not checked, i.e., you will not hear about integer
 4469: overflow on addition or multiplication, you may hear about division by
 4470: zero if you are lucky. The operator is written after the operands, but
 4471: the operands are still in the original order. I.e., the infix @code{2-1}
 4472: corresponds to @code{2 1 -}. Forth offers a variety of division
 4473: operators. If you perform division with potentially negative operands,
 4474: you do not want to use @code{/} or @code{/mod} with its undefined
 4475: behaviour, but rather @code{fm/mod} or @code{sm/mod} (probably the
 4476: former, @pxref{Mixed precision}).
 4477: @comment TODO discuss the different division forms and the std approach
 4478: 
 4479: @menu
 4480: * Single precision::            
 4481: * Double precision::            Double-cell integer arithmetic
 4482: * Bitwise operations::          
 4483: * Numeric comparison::          
 4484: * Mixed precision::             Operations with single and double-cell integers
 4485: * Floating Point::              
 4486: @end menu
 4487: 
 4488: @node Single precision, Double precision, Arithmetic, Arithmetic
 4489: @subsection Single precision
 4490: @cindex single precision arithmetic words
 4491: 
 4492: @c !! cell undefined
 4493: 
 4494: By default, numbers in Forth are single-precision integers that are one
 4495: cell in size. They can be signed or unsigned, depending upon how you
 4496: treat them. For the rules used by the text interpreter for recognising
 4497: single-precision integers see @ref{Number Conversion}.
 4498: 
 4499: These words are all defined for signed operands, but some of them also
 4500: work for unsigned numbers: @code{+}, @code{1+}, @code{-}, @code{1-},
 4501: @code{*}.
 4502: 
 4503: doc-+
 4504: doc-1+
 4505: doc-under+
 4506: doc--
 4507: doc-1-
 4508: doc-*
 4509: doc-/
 4510: doc-mod
 4511: doc-/mod
 4512: doc-negate
 4513: doc-abs
 4514: doc-min
 4515: doc-max
 4516: doc-floored
 4517: 
 4518: 
 4519: @node Double precision, Bitwise operations, Single precision, Arithmetic
 4520: @subsection Double precision
 4521: @cindex double precision arithmetic words
 4522: 
 4523: For the rules used by the text interpreter for
 4524: recognising double-precision integers, see @ref{Number Conversion}.
 4525: 
 4526: A double precision number is represented by a cell pair, with the most
 4527: significant cell at the TOS. It is trivial to convert an unsigned single
 4528: to a double: simply push a @code{0} onto the TOS. Since numbers are
 4529: represented by Gforth using 2's complement arithmetic, converting a
 4530: signed single to a (signed) double requires sign-extension across the
 4531: most significant cell. This can be achieved using @code{s>d}. The moral
 4532: of the story is that you cannot convert a number without knowing whether
 4533: it represents an unsigned or a signed number.
 4534: 
 4535: These words are all defined for signed operands, but some of them also
 4536: work for unsigned numbers: @code{d+}, @code{d-}.
 4537: 
 4538: doc-s>d
 4539: doc-d>s
 4540: doc-d+
 4541: doc-d-
 4542: doc-dnegate
 4543: doc-dabs
 4544: doc-dmin
 4545: doc-dmax
 4546: 
 4547: 
 4548: @node Bitwise operations, Numeric comparison, Double precision, Arithmetic
 4549: @subsection Bitwise operations
 4550: @cindex bitwise operation words
 4551: 
 4552: 
 4553: doc-and
 4554: doc-or
 4555: doc-xor
 4556: doc-invert
 4557: doc-lshift
 4558: doc-rshift
 4559: doc-2*
 4560: doc-d2*
 4561: doc-2/
 4562: doc-d2/
 4563: 
 4564: 
 4565: @node Numeric comparison, Mixed precision, Bitwise operations, Arithmetic
 4566: @subsection Numeric comparison
 4567: @cindex numeric comparison words
 4568: 
 4569: Note that the words that compare for equality (@code{= <> 0= 0<> d= d<>
 4570: d0= d0<>}) work for for both signed and unsigned numbers.
 4571: 
 4572: doc-<
 4573: doc-<=
 4574: doc-<>
 4575: doc-=
 4576: doc->
 4577: doc->=
 4578: 
 4579: doc-0<
 4580: doc-0<=
 4581: doc-0<>
 4582: doc-0=
 4583: doc-0>
 4584: doc-0>=
 4585: 
 4586: doc-u<
 4587: doc-u<=
 4588: @c u<> and u= exist but are the same as <> and =
 4589: @c doc-u<>
 4590: @c doc-u=
 4591: doc-u>
 4592: doc-u>=
 4593: 
 4594: doc-within
 4595: 
 4596: doc-d<
 4597: doc-d<=
 4598: doc-d<>
 4599: doc-d=
 4600: doc-d>
 4601: doc-d>=
 4602: 
 4603: doc-d0<
 4604: doc-d0<=
 4605: doc-d0<>
 4606: doc-d0=
 4607: doc-d0>
 4608: doc-d0>=
 4609: 
 4610: doc-du<
 4611: doc-du<=
 4612: @c du<> and du= exist but are the same as d<> and d=
 4613: @c doc-du<>
 4614: @c doc-du=
 4615: doc-du>
 4616: doc-du>=
 4617: 
 4618: 
 4619: @node Mixed precision, Floating Point, Numeric comparison, Arithmetic
 4620: @subsection Mixed precision
 4621: @cindex mixed precision arithmetic words
 4622: 
 4623: 
 4624: doc-m+
 4625: doc-*/
 4626: doc-*/mod
 4627: doc-m*
 4628: doc-um*
 4629: doc-m*/
 4630: doc-um/mod
 4631: doc-fm/mod
 4632: doc-sm/rem
 4633: 
 4634: 
 4635: @node Floating Point,  , Mixed precision, Arithmetic
 4636: @subsection Floating Point
 4637: @cindex floating point arithmetic words
 4638: 
 4639: For the rules used by the text interpreter for
 4640: recognising floating-point numbers see @ref{Number Conversion}.
 4641: 
 4642: Gforth has a separate floating point stack, but the documentation uses
 4643: the unified notation.@footnote{It's easy to generate the separate
 4644: notation from that by just separating the floating-point numbers out:
 4645: e.g. @code{( n r1 u r2 -- r3 )} becomes @code{( n u -- ) ( F: r1 r2 --
 4646: r3 )}.}
 4647: 
 4648: @cindex floating-point arithmetic, pitfalls
 4649: Floating point numbers have a number of unpleasant surprises for the
 4650: unwary (e.g., floating point addition is not associative) and even a few
 4651: for the wary. You should not use them unless you know what you are doing
 4652: or you don't care that the results you get are totally bogus. If you
 4653: want to learn about the problems of floating point numbers (and how to
 4654: avoid them), you might start with @cite{David Goldberg,
 4655: @uref{http://www.validgh.com/goldberg/paper.ps,What Every Computer
 4656: Scientist Should Know About Floating-Point Arithmetic}, ACM Computing
 4657: Surveys 23(1):5@minus{}48, March 1991}.
 4658: 
 4659: 
 4660: doc-d>f
 4661: doc-f>d
 4662: doc-f+
 4663: doc-f-
 4664: doc-f*
 4665: doc-f/
 4666: doc-fnegate
 4667: doc-fabs
 4668: doc-fmax
 4669: doc-fmin
 4670: doc-floor
 4671: doc-fround
 4672: doc-f**
 4673: doc-fsqrt
 4674: doc-fexp
 4675: doc-fexpm1
 4676: doc-fln
 4677: doc-flnp1
 4678: doc-flog
 4679: doc-falog
 4680: doc-f2*
 4681: doc-f2/
 4682: doc-1/f
 4683: doc-precision
 4684: doc-set-precision
 4685: 
 4686: @cindex angles in trigonometric operations
 4687: @cindex trigonometric operations
 4688: Angles in floating point operations are given in radians (a full circle
 4689: has 2 pi radians).
 4690: 
 4691: doc-fsin
 4692: doc-fcos
 4693: doc-fsincos
 4694: doc-ftan
 4695: doc-fasin
 4696: doc-facos
 4697: doc-fatan
 4698: doc-fatan2
 4699: doc-fsinh
 4700: doc-fcosh
 4701: doc-ftanh
 4702: doc-fasinh
 4703: doc-facosh
 4704: doc-fatanh
 4705: doc-pi
 4706: 
 4707: @cindex equality of floats
 4708: @cindex floating-point comparisons
 4709: One particular problem with floating-point arithmetic is that comparison
 4710: for equality often fails when you would expect it to succeed.  For this
 4711: reason approximate equality is often preferred (but you still have to
 4712: know what you are doing).  Also note that IEEE NaNs may compare
 4713: differently from what you might expect.  The comparison words are:
 4714: 
 4715: doc-f~rel
 4716: doc-f~abs
 4717: doc-f~
 4718: doc-f=
 4719: doc-f<>
 4720: 
 4721: doc-f<
 4722: doc-f<=
 4723: doc-f>
 4724: doc-f>=
 4725: 
 4726: doc-f0<
 4727: doc-f0<=
 4728: doc-f0<>
 4729: doc-f0=
 4730: doc-f0>
 4731: doc-f0>=
 4732: 
 4733: 
 4734: @node Stack Manipulation, Memory, Arithmetic, Words
 4735: @section Stack Manipulation
 4736: @cindex stack manipulation words
 4737: 
 4738: @cindex floating-point stack in the standard
 4739: Gforth maintains a number of separate stacks:
 4740: 
 4741: @cindex data stack
 4742: @cindex parameter stack
 4743: @itemize @bullet
 4744: @item
 4745: A data stack (also known as the @dfn{parameter stack}) -- for
 4746: characters, cells, addresses, and double cells.
 4747: 
 4748: @cindex floating-point stack
 4749: @item
 4750: A floating point stack -- for holding floating point (FP) numbers.
 4751: 
 4752: @cindex return stack
 4753: @item
 4754: A return stack -- for holding the return addresses of colon
 4755: definitions and other (non-FP) data.
 4756: 
 4757: @cindex locals stack
 4758: @item
 4759: A locals stack -- for holding local variables.
 4760: @end itemize
 4761: 
 4762: @menu
 4763: * Data stack::                  
 4764: * Floating point stack::        
 4765: * Return stack::                
 4766: * Locals stack::                
 4767: * Stack pointer manipulation::  
 4768: @end menu
 4769: 
 4770: @node Data stack, Floating point stack, Stack Manipulation, Stack Manipulation
 4771: @subsection Data stack
 4772: @cindex data stack manipulation words
 4773: @cindex stack manipulations words, data stack
 4774: 
 4775: 
 4776: doc-drop
 4777: doc-nip
 4778: doc-dup
 4779: doc-over
 4780: doc-tuck
 4781: doc-swap
 4782: doc-pick
 4783: doc-rot
 4784: doc--rot
 4785: doc-?dup
 4786: doc-roll
 4787: doc-2drop
 4788: doc-2nip
 4789: doc-2dup
 4790: doc-2over
 4791: doc-2tuck
 4792: doc-2swap
 4793: doc-2rot
 4794: 
 4795: 
 4796: @node Floating point stack, Return stack, Data stack, Stack Manipulation
 4797: @subsection Floating point stack
 4798: @cindex floating-point stack manipulation words
 4799: @cindex stack manipulation words, floating-point stack
 4800: 
 4801: Whilst every sane Forth has a separate floating-point stack, it is not
 4802: strictly required; an ANS Forth system could theoretically keep
 4803: floating-point numbers on the data stack. As an additional difficulty,
 4804: you don't know how many cells a floating-point number takes. It is
 4805: reportedly possible to write words in a way that they work also for a
 4806: unified stack model, but we do not recommend trying it. Instead, just
 4807: say that your program has an environmental dependency on a separate
 4808: floating-point stack.
 4809: 
 4810: doc-floating-stack
 4811: 
 4812: doc-fdrop
 4813: doc-fnip
 4814: doc-fdup
 4815: doc-fover
 4816: doc-ftuck
 4817: doc-fswap
 4818: doc-fpick
 4819: doc-frot
 4820: 
 4821: 
 4822: @node Return stack, Locals stack, Floating point stack, Stack Manipulation
 4823: @subsection Return stack
 4824: @cindex return stack manipulation words
 4825: @cindex stack manipulation words, return stack
 4826: 
 4827: @cindex return stack and locals
 4828: @cindex locals and return stack
 4829: A Forth system is allowed to keep local variables on the
 4830: return stack. This is reasonable, as local variables usually eliminate
 4831: the need to use the return stack explicitly. So, if you want to produce
 4832: a standard compliant program and you are using local variables in a
 4833: word, forget about return stack manipulations in that word (refer to the
 4834: standard document for the exact rules).
 4835: 
 4836: doc->r
 4837: doc-r>
 4838: doc-r@
 4839: doc-rdrop
 4840: doc-2>r
 4841: doc-2r>
 4842: doc-2r@
 4843: doc-2rdrop
 4844: 
 4845: 
 4846: @node Locals stack, Stack pointer manipulation, Return stack, Stack Manipulation
 4847: @subsection Locals stack
 4848: 
 4849: Gforth uses an extra locals stack.  It is described, along with the
 4850: reasons for its existence, in @ref{Locals implementation}.
 4851: 
 4852: @node Stack pointer manipulation,  , Locals stack, Stack Manipulation
 4853: @subsection Stack pointer manipulation
 4854: @cindex stack pointer manipulation words
 4855: 
 4856: @c removed s0 r0 l0 -- they are obsolete aliases for sp0 rp0 lp0
 4857: doc-sp0
 4858: doc-sp@
 4859: doc-sp!
 4860: doc-fp0
 4861: doc-fp@
 4862: doc-fp!
 4863: doc-rp0
 4864: doc-rp@
 4865: doc-rp!
 4866: doc-lp0
 4867: doc-lp@
 4868: doc-lp!
 4869: 
 4870: 
 4871: @node Memory, Control Structures, Stack Manipulation, Words
 4872: @section Memory
 4873: @cindex memory words
 4874: 
 4875: @menu
 4876: * Memory model::                
 4877: * Dictionary allocation::       
 4878: * Heap Allocation::             
 4879: * Memory Access::               
 4880: * Address arithmetic::          
 4881: * Memory Blocks::               
 4882: @end menu
 4883: 
 4884: In addition to the standard Forth memory allocation words, there is also
 4885: a @uref{http://www.complang.tuwien.ac.at/forth/garbage-collection.zip,
 4886: garbage collector}.
 4887: 
 4888: @node Memory model, Dictionary allocation, Memory, Memory
 4889: @subsection ANS Forth and Gforth memory models
 4890: 
 4891: @c The ANS Forth description is a mess (e.g., is the heap part of
 4892: @c the dictionary?), so let's not stick to closely with it.
 4893: 
 4894: ANS Forth considers a Forth system as consisting of several address
 4895: spaces, of which only @dfn{data space} is managed and accessible with
 4896: the memory words.  Memory not necessarily in data space includes the
 4897: stacks, the code (called code space) and the headers (called name
 4898: space). In Gforth everything is in data space, but the code for the
 4899: primitives is usually read-only.
 4900: 
 4901: Data space is divided into a number of areas: The (data space portion of
 4902: the) dictionary@footnote{Sometimes, the term @dfn{dictionary} is used to
 4903: refer to the search data structure embodied in word lists and headers,
 4904: because it is used for looking up names, just as you would in a
 4905: conventional dictionary.}, the heap, and a number of system-allocated
 4906: buffers.
 4907: 
 4908: @cindex address arithmetic restrictions, ANS vs. Gforth
 4909: @cindex contiguous regions, ANS vs. Gforth
 4910: In ANS Forth data space is also divided into contiguous regions.  You
 4911: can only use address arithmetic within a contiguous region, not between
 4912: them.  Usually each allocation gives you one contiguous region, but the
 4913: dictionary allocation words have additional rules (@pxref{Dictionary
 4914: allocation}).
 4915: 
 4916: Gforth provides one big address space, and address arithmetic can be
 4917: performed between any addresses. However, in the dictionary headers or
 4918: code are interleaved with data, so almost the only contiguous data space
 4919: regions there are those described by ANS Forth as contiguous; but you
 4920: can be sure that the dictionary is allocated towards increasing
 4921: addresses even between contiguous regions.  The memory order of
 4922: allocations in the heap is platform-dependent (and possibly different
 4923: from one run to the next).
 4924: 
 4925: 
 4926: @node Dictionary allocation, Heap Allocation, Memory model, Memory
 4927: @subsection Dictionary allocation
 4928: @cindex reserving data space
 4929: @cindex data space - reserving some
 4930: 
 4931: Dictionary allocation is a stack-oriented allocation scheme, i.e., if
 4932: you want to deallocate X, you also deallocate everything
 4933: allocated after X.
 4934: 
 4935: @cindex contiguous regions in dictionary allocation
 4936: The allocations using the words below are contiguous and grow the region
 4937: towards increasing addresses.  Other words that allocate dictionary
 4938: memory of any kind (i.e., defining words including @code{:noname}) end
 4939: the contiguous region and start a new one.
 4940: 
 4941: In ANS Forth only @code{create}d words are guaranteed to produce an
 4942: address that is the start of the following contiguous region.  In
 4943: particular, the cell allocated by @code{variable} is not guaranteed to
 4944: be contiguous with following @code{allot}ed memory.
 4945: 
 4946: You can deallocate memory by using @code{allot} with a negative argument
 4947: (with some restrictions, see @code{allot}). For larger deallocations use
 4948: @code{marker}.
 4949: 
 4950: 
 4951: doc-here
 4952: doc-unused
 4953: doc-allot
 4954: doc-c,
 4955: doc-f,
 4956: doc-,
 4957: doc-2,
 4958: 
 4959: Memory accesses have to be aligned (@pxref{Address arithmetic}). So of
 4960: course you should allocate memory in an aligned way, too. I.e., before
 4961: allocating allocating a cell, @code{here} must be cell-aligned, etc.
 4962: The words below align @code{here} if it is not already.  Basically it is
 4963: only already aligned for a type, if the last allocation was a multiple
 4964: of the size of this type and if @code{here} was aligned for this type
 4965: before.
 4966: 
 4967: After freshly @code{create}ing a word, @code{here} is @code{align}ed in
 4968: ANS Forth (@code{maxalign}ed in Gforth).
 4969: 
 4970: doc-align
 4971: doc-falign
 4972: doc-sfalign
 4973: doc-dfalign
 4974: doc-maxalign
 4975: doc-cfalign
 4976: 
 4977: 
 4978: @node Heap Allocation, Memory Access, Dictionary allocation, Memory
 4979: @subsection Heap allocation
 4980: @cindex heap allocation
 4981: @cindex dynamic allocation of memory
 4982: @cindex memory-allocation word set
 4983: 
 4984: @cindex contiguous regions and heap allocation
 4985: Heap allocation supports deallocation of allocated memory in any
 4986: order. Dictionary allocation is not affected by it (i.e., it does not
 4987: end a contiguous region). In Gforth, these words are implemented using
 4988: the standard C library calls malloc(), free() and resize().
 4989: 
 4990: The memory region produced by one invocation of @code{allocate} or
 4991: @code{resize} is internally contiguous.  There is no contiguity between
 4992: such a region and any other region (including others allocated from the
 4993: heap).
 4994: 
 4995: doc-allocate
 4996: doc-free
 4997: doc-resize
 4998: 
 4999: 
 5000: @node Memory Access, Address arithmetic, Heap Allocation, Memory
 5001: @subsection Memory Access
 5002: @cindex memory access words
 5003: 
 5004: doc-@
 5005: doc-!
 5006: doc-+!
 5007: doc-c@
 5008: doc-c!
 5009: doc-2@
 5010: doc-2!
 5011: doc-f@
 5012: doc-f!
 5013: doc-sf@
 5014: doc-sf!
 5015: doc-df@
 5016: doc-df!
 5017: doc-sw@
 5018: doc-uw@
 5019: doc-w!
 5020: doc-sl@
 5021: doc-ul@
 5022: doc-l!
 5023: 
 5024: @node Address arithmetic, Memory Blocks, Memory Access, Memory
 5025: @subsection Address arithmetic
 5026: @cindex address arithmetic words
 5027: 
 5028: Address arithmetic is the foundation on which you can build data
 5029: structures like arrays, records (@pxref{Structures}) and objects
 5030: (@pxref{Object-oriented Forth}).
 5031: 
 5032: @cindex address unit
 5033: @cindex au (address unit)
 5034: ANS Forth does not specify the sizes of the data types. Instead, it
 5035: offers a number of words for computing sizes and doing address
 5036: arithmetic. Address arithmetic is performed in terms of address units
 5037: (aus); on most systems the address unit is one byte. Note that a
 5038: character may have more than one au, so @code{chars} is no noop (on
 5039: platforms where it is a noop, it compiles to nothing).
 5040: 
 5041: The basic address arithmetic words are @code{+} and @code{-}.  E.g., if
 5042: you have the address of a cell, perform @code{1 cells +}, and you will
 5043: have the address of the next cell.
 5044: 
 5045: @cindex contiguous regions and address arithmetic
 5046: In ANS Forth you can perform address arithmetic only within a contiguous
 5047: region, i.e., if you have an address into one region, you can only add
 5048: and subtract such that the result is still within the region; you can
 5049: only subtract or compare addresses from within the same contiguous
 5050: region.  Reasons: several contiguous regions can be arranged in memory
 5051: in any way; on segmented systems addresses may have unusual
 5052: representations, such that address arithmetic only works within a
 5053: region.  Gforth provides a few more guarantees (linear address space,
 5054: dictionary grows upwards), but in general I have found it easy to stay
 5055: within contiguous regions (exception: computing and comparing to the
 5056: address just beyond the end of an array).
 5057: 
 5058: @cindex alignment of addresses for types
 5059: ANS Forth also defines words for aligning addresses for specific
 5060: types. Many computers require that accesses to specific data types
 5061: must only occur at specific addresses; e.g., that cells may only be
 5062: accessed at addresses divisible by 4. Even if a machine allows unaligned
 5063: accesses, it can usually perform aligned accesses faster. 
 5064: 
 5065: For the performance-conscious: alignment operations are usually only
 5066: necessary during the definition of a data structure, not during the
 5067: (more frequent) accesses to it.
 5068: 
 5069: ANS Forth defines no words for character-aligning addresses. This is not
 5070: an oversight, but reflects the fact that addresses that are not
 5071: char-aligned have no use in the standard and therefore will not be
 5072: created.
 5073: 
 5074: @cindex @code{CREATE} and alignment
 5075: ANS Forth guarantees that addresses returned by @code{CREATE}d words
 5076: are cell-aligned; in addition, Gforth guarantees that these addresses
 5077: are aligned for all purposes.
 5078: 
 5079: Note that the ANS Forth word @code{char} has nothing to do with address
 5080: arithmetic.
 5081: 
 5082: 
 5083: doc-chars
 5084: doc-char+
 5085: doc-cells
 5086: doc-cell+
 5087: doc-cell
 5088: doc-aligned
 5089: doc-floats
 5090: doc-float+
 5091: doc-float
 5092: doc-faligned
 5093: doc-sfloats
 5094: doc-sfloat+
 5095: doc-sfaligned
 5096: doc-dfloats
 5097: doc-dfloat+
 5098: doc-dfaligned
 5099: doc-maxaligned
 5100: doc-cfaligned
 5101: doc-address-unit-bits
 5102: doc-/w
 5103: doc-/l
 5104: 
 5105: @node Memory Blocks,  , Address arithmetic, Memory
 5106: @subsection Memory Blocks
 5107: @cindex memory block words
 5108: @cindex character strings - moving and copying
 5109: 
 5110: Memory blocks often represent character strings; For ways of storing
 5111: character strings in memory see @ref{String Formats}.  For other
 5112: string-processing words see @ref{Displaying characters and strings}.
 5113: 
 5114: A few of these words work on address unit blocks.  In that case, you
 5115: usually have to insert @code{CHARS} before the word when working on
 5116: character strings.  Most words work on character blocks, and expect a
 5117: char-aligned address.
 5118: 
 5119: When copying characters between overlapping memory regions, use
 5120: @code{chars move} or choose carefully between @code{cmove} and
 5121: @code{cmove>}.
 5122: 
 5123: doc-move
 5124: doc-erase
 5125: doc-cmove
 5126: doc-cmove>
 5127: doc-fill
 5128: doc-blank
 5129: doc-compare
 5130: doc-str=
 5131: doc-str<
 5132: doc-string-prefix?
 5133: doc-search
 5134: doc--trailing
 5135: doc-/string
 5136: doc-bounds
 5137: doc-pad
 5138: 
 5139: @comment TODO examples
 5140: 
 5141: 
 5142: @node Control Structures, Defining Words, Memory, Words
 5143: @section Control Structures
 5144: @cindex control structures
 5145: 
 5146: Control structures in Forth cannot be used interpretively, only in a
 5147: colon definition@footnote{To be precise, they have no interpretation
 5148: semantics (@pxref{Interpretation and Compilation Semantics}).}. We do
 5149: not like this limitation, but have not seen a satisfying way around it
 5150: yet, although many schemes have been proposed.
 5151: 
 5152: @menu
 5153: * Selection::                   IF ... ELSE ... ENDIF
 5154: * Simple Loops::                BEGIN ...
 5155: * Counted Loops::               DO
 5156: * Arbitrary control structures::  
 5157: * Calls and returns::           
 5158: * Exception Handling::          
 5159: @end menu
 5160: 
 5161: @node Selection, Simple Loops, Control Structures, Control Structures
 5162: @subsection Selection
 5163: @cindex selection control structures
 5164: @cindex control structures for selection
 5165: 
 5166: @cindex @code{IF} control structure
 5167: @example
 5168: @i{flag}
 5169: IF
 5170:   @i{code}
 5171: ENDIF
 5172: @end example
 5173: @noindent
 5174: 
 5175: If @i{flag} is non-zero (as far as @code{IF} etc. are concerned, a cell
 5176: with any bit set represents truth) @i{code} is executed.
 5177: 
 5178: @example
 5179: @i{flag}
 5180: IF
 5181:   @i{code1}
 5182: ELSE
 5183:   @i{code2}
 5184: ENDIF
 5185: @end example
 5186: 
 5187: If @var{flag} is true, @i{code1} is executed, otherwise @i{code2} is
 5188: executed.
 5189: 
 5190: You can use @code{THEN} instead of @code{ENDIF}. Indeed, @code{THEN} is
 5191: standard, and @code{ENDIF} is not, although it is quite popular. We
 5192: recommend using @code{ENDIF}, because it is less confusing for people
 5193: who also know other languages (and is not prone to reinforcing negative
 5194: prejudices against Forth in these people). Adding @code{ENDIF} to a
 5195: system that only supplies @code{THEN} is simple:
 5196: @example
 5197: : ENDIF   POSTPONE then ; immediate
 5198: @end example
 5199: 
 5200: [According to @cite{Webster's New Encyclopedic Dictionary}, @dfn{then
 5201: (adv.)}  has the following meanings:
 5202: @quotation
 5203: ... 2b: following next after in order ... 3d: as a necessary consequence
 5204: (if you were there, then you saw them).
 5205: @end quotation
 5206: Forth's @code{THEN} has the meaning 2b, whereas @code{THEN} in Pascal
 5207: and many other programming languages has the meaning 3d.]
 5208: 
 5209: Gforth also provides the words @code{?DUP-IF} and @code{?DUP-0=-IF}, so
 5210: you can avoid using @code{?dup}. Using these alternatives is also more
 5211: efficient than using @code{?dup}. Definitions in ANS Forth
 5212: for @code{ENDIF}, @code{?DUP-IF} and @code{?DUP-0=-IF} are provided in
 5213: @file{compat/control.fs}.
 5214: 
 5215: @cindex @code{CASE} control structure
 5216: @example
 5217: @i{n}
 5218: CASE
 5219:   @i{n1} OF @i{code1} ENDOF
 5220:   @i{n2} OF @i{code2} ENDOF
 5221:   @dots{}
 5222:   ( n ) @i{default-code} ( n )
 5223: ENDCASE ( )
 5224: @end example
 5225: 
 5226: Executes the first @i{codei}, where the @i{ni} is equal to @i{n}.  If
 5227: no @i{ni} matches, the optional @i{default-code} is executed. The
 5228: optional default case can be added by simply writing the code after
 5229: the last @code{ENDOF}. It may use @i{n}, which is on top of the stack,
 5230: but must not consume it.  The value @i{n} is consumed by this
 5231: construction (either by a OF that matches, or by the ENDCASE, if no OF
 5232: matches).
 5233: 
 5234: @progstyle
 5235: To keep the code understandable, you should ensure that you change the
 5236: stack in the same way (wrt. number and types of stack items consumed
 5237: and pushed) on all paths through a selection construct.
 5238: 
 5239: @node Simple Loops, Counted Loops, Selection, Control Structures
 5240: @subsection Simple Loops
 5241: @cindex simple loops
 5242: @cindex loops without count 
 5243: 
 5244: @cindex @code{WHILE} loop
 5245: @example
 5246: BEGIN
 5247:   @i{code1}
 5248:   @i{flag}
 5249: WHILE
 5250:   @i{code2}
 5251: REPEAT
 5252: @end example
 5253: 
 5254: @i{code1} is executed and @i{flag} is computed. If it is true,
 5255: @i{code2} is executed and the loop is restarted; If @i{flag} is
 5256: false, execution continues after the @code{REPEAT}.
 5257: 
 5258: @cindex @code{UNTIL} loop
 5259: @example
 5260: BEGIN
 5261:   @i{code}
 5262:   @i{flag}
 5263: UNTIL
 5264: @end example
 5265: 
 5266: @i{code} is executed. The loop is restarted if @code{flag} is false.
 5267: 
 5268: @progstyle
 5269: To keep the code understandable, a complete iteration of the loop should
 5270: not change the number and types of the items on the stacks.
 5271: 
 5272: @cindex endless loop
 5273: @cindex loops, endless
 5274: @example
 5275: BEGIN
 5276:   @i{code}
 5277: AGAIN
 5278: @end example
 5279: 
 5280: This is an endless loop.
 5281: 
 5282: @node Counted Loops, Arbitrary control structures, Simple Loops, Control Structures
 5283: @subsection Counted Loops
 5284: @cindex counted loops
 5285: @cindex loops, counted
 5286: @cindex @code{DO} loops
 5287: 
 5288: The basic counted loop is:
 5289: @example
 5290: @i{limit} @i{start}
 5291: ?DO
 5292:   @i{body}
 5293: LOOP
 5294: @end example
 5295: 
 5296: This performs one iteration for every integer, starting from @i{start}
 5297: and up to, but excluding @i{limit}. The counter, or @i{index}, can be
 5298: accessed with @code{i}. For example, the loop:
 5299: @example
 5300: 10 0 ?DO
 5301:   i .
 5302: LOOP
 5303: @end example
 5304: @noindent
 5305: prints @code{0 1 2 3 4 5 6 7 8 9}
 5306: 
 5307: The index of the innermost loop can be accessed with @code{i}, the index
 5308: of the next loop with @code{j}, and the index of the third loop with
 5309: @code{k}.
 5310: 
 5311: 
 5312: doc-i
 5313: doc-j
 5314: doc-k
 5315: 
 5316: 
 5317: The loop control data are kept on the return stack, so there are some
 5318: restrictions on mixing return stack accesses and counted loop words. In
 5319: particuler, if you put values on the return stack outside the loop, you
 5320: cannot read them inside the loop@footnote{well, not in a way that is
 5321: portable.}. If you put values on the return stack within a loop, you
 5322: have to remove them before the end of the loop and before accessing the
 5323: index of the loop.
 5324: 
 5325: There are several variations on the counted loop:
 5326: 
 5327: @itemize @bullet
 5328: @item
 5329: @code{LEAVE} leaves the innermost counted loop immediately; execution
 5330: continues after the associated @code{LOOP} or @code{NEXT}. For example:
 5331: 
 5332: @example
 5333: 10 0 ?DO  i DUP . 3 = IF LEAVE THEN LOOP
 5334: @end example
 5335: prints @code{0 1 2 3}
 5336: 
 5337: 
 5338: @item
 5339: @code{UNLOOP} prepares for an abnormal loop exit, e.g., via
 5340: @code{EXIT}. @code{UNLOOP} removes the loop control parameters from the
 5341: return stack so @code{EXIT} can get to its return address. For example:
 5342: 
 5343: @example
 5344: : demo 10 0 ?DO i DUP . 3 = IF UNLOOP EXIT THEN LOOP ." Done" ;
 5345: @end example
 5346: prints @code{0 1 2 3}
 5347: 
 5348: 
 5349: @item
 5350: If @i{start} is greater than @i{limit}, a @code{?DO} loop is entered
 5351: (and @code{LOOP} iterates until they become equal by wrap-around
 5352: arithmetic). This behaviour is usually not what you want. Therefore,
 5353: Gforth offers @code{+DO} and @code{U+DO} (as replacements for
 5354: @code{?DO}), which do not enter the loop if @i{start} is greater than
 5355: @i{limit}; @code{+DO} is for signed loop parameters, @code{U+DO} for
 5356: unsigned loop parameters.
 5357: 
 5358: @item
 5359: @code{?DO} can be replaced by @code{DO}. @code{DO} always enters
 5360: the loop, independent of the loop parameters. Do not use @code{DO}, even
 5361: if you know that the loop is entered in any case. Such knowledge tends
 5362: to become invalid during maintenance of a program, and then the
 5363: @code{DO} will make trouble.
 5364: 
 5365: @item
 5366: @code{LOOP} can be replaced with @code{@i{n} +LOOP}; this updates the
 5367: index by @i{n} instead of by 1. The loop is terminated when the border
 5368: between @i{limit-1} and @i{limit} is crossed. E.g.:
 5369: 
 5370: @example
 5371: 4 0 +DO  i .  2 +LOOP
 5372: @end example
 5373: @noindent
 5374: prints @code{0 2}
 5375: 
 5376: @example
 5377: 4 1 +DO  i .  2 +LOOP
 5378: @end example
 5379: @noindent
 5380: prints @code{1 3}
 5381: 
 5382: @item
 5383: @cindex negative increment for counted loops
 5384: @cindex counted loops with negative increment
 5385: The behaviour of @code{@i{n} +LOOP} is peculiar when @i{n} is negative:
 5386: 
 5387: @example
 5388: -1 0 ?DO  i .  -1 +LOOP
 5389: @end example
 5390: @noindent
 5391: prints @code{0 -1}
 5392: 
 5393: @example
 5394: 0 0 ?DO  i .  -1 +LOOP
 5395: @end example
 5396: prints nothing.
 5397: 
 5398: Therefore we recommend avoiding @code{@i{n} +LOOP} with negative
 5399: @i{n}. One alternative is @code{@i{u} -LOOP}, which reduces the
 5400: index by @i{u} each iteration. The loop is terminated when the border
 5401: between @i{limit+1} and @i{limit} is crossed. Gforth also provides
 5402: @code{-DO} and @code{U-DO} for down-counting loops. E.g.:
 5403: 
 5404: @example
 5405: -2 0 -DO  i .  1 -LOOP
 5406: @end example
 5407: @noindent
 5408: prints @code{0 -1}
 5409: 
 5410: @example
 5411: -1 0 -DO  i .  1 -LOOP
 5412: @end example
 5413: @noindent
 5414: prints @code{0}
 5415: 
 5416: @example
 5417: 0 0 -DO  i .  1 -LOOP
 5418: @end example
 5419: @noindent
 5420: prints nothing.
 5421: 
 5422: @end itemize
 5423: 
 5424: Unfortunately, @code{+DO}, @code{U+DO}, @code{-DO}, @code{U-DO} and
 5425: @code{-LOOP} are not defined in ANS Forth. However, an implementation
 5426: for these words that uses only standard words is provided in
 5427: @file{compat/loops.fs}.
 5428: 
 5429: 
 5430: @cindex @code{FOR} loops
 5431: Another counted loop is:
 5432: @example
 5433: @i{n}
 5434: FOR
 5435:   @i{body}
 5436: NEXT
 5437: @end example
 5438: This is the preferred loop of native code compiler writers who are too
 5439: lazy to optimize @code{?DO} loops properly. This loop structure is not
 5440: defined in ANS Forth. In Gforth, this loop iterates @i{n+1} times;
 5441: @code{i} produces values starting with @i{n} and ending with 0. Other
 5442: Forth systems may behave differently, even if they support @code{FOR}
 5443: loops. To avoid problems, don't use @code{FOR} loops.
 5444: 
 5445: @node Arbitrary control structures, Calls and returns, Counted Loops, Control Structures
 5446: @subsection Arbitrary control structures
 5447: @cindex control structures, user-defined
 5448: 
 5449: @cindex control-flow stack
 5450: ANS Forth permits and supports using control structures in a non-nested
 5451: way. Information about incomplete control structures is stored on the
 5452: control-flow stack. This stack may be implemented on the Forth data
 5453: stack, and this is what we have done in Gforth.
 5454: 
 5455: @cindex @code{orig}, control-flow stack item
 5456: @cindex @code{dest}, control-flow stack item
 5457: An @i{orig} entry represents an unresolved forward branch, a @i{dest}
 5458: entry represents a backward branch target. A few words are the basis for
 5459: building any control structure possible (except control structures that
 5460: need storage, like calls, coroutines, and backtracking).
 5461: 
 5462: 
 5463: doc-if
 5464: doc-ahead
 5465: doc-then
 5466: doc-begin
 5467: doc-until
 5468: doc-again
 5469: doc-cs-pick
 5470: doc-cs-roll
 5471: 
 5472: 
 5473: The Standard words @code{CS-PICK} and @code{CS-ROLL} allow you to
 5474: manipulate the control-flow stack in a portable way. Without them, you
 5475: would need to know how many stack items are occupied by a control-flow
 5476: entry (many systems use one cell. In Gforth they currently take three,
 5477: but this may change in the future).
 5478: 
 5479: Some standard control structure words are built from these words:
 5480: 
 5481: 
 5482: doc-else
 5483: doc-while
 5484: doc-repeat
 5485: 
 5486: 
 5487: @noindent
 5488: Gforth adds some more control-structure words:
 5489: 
 5490: 
 5491: doc-endif
 5492: doc-?dup-if
 5493: doc-?dup-0=-if
 5494: 
 5495: 
 5496: @noindent
 5497: Counted loop words constitute a separate group of words:
 5498: 
 5499: 
 5500: doc-?do
 5501: doc-+do
 5502: doc-u+do
 5503: doc--do
 5504: doc-u-do
 5505: doc-do
 5506: doc-for
 5507: doc-loop
 5508: doc-+loop
 5509: doc--loop
 5510: doc-next
 5511: doc-leave
 5512: doc-?leave
 5513: doc-unloop
 5514: doc-done
 5515: 
 5516: 
 5517: The standard does not allow using @code{CS-PICK} and @code{CS-ROLL} on
 5518: @i{do-sys}. Gforth allows it, but it's your job to ensure that for
 5519: every @code{?DO} etc. there is exactly one @code{UNLOOP} on any path
 5520: through the definition (@code{LOOP} etc. compile an @code{UNLOOP} on the
 5521: fall-through path). Also, you have to ensure that all @code{LEAVE}s are
 5522: resolved (by using one of the loop-ending words or @code{DONE}).
 5523: 
 5524: @noindent
 5525: Another group of control structure words are:
 5526: 
 5527: 
 5528: doc-case
 5529: doc-endcase
 5530: doc-of
 5531: doc-endof
 5532: 
 5533: 
 5534: @i{case-sys} and @i{of-sys} cannot be processed using @code{CS-PICK} and
 5535: @code{CS-ROLL}.
 5536: 
 5537: @subsubsection Programming Style
 5538: @cindex control structures programming style
 5539: @cindex programming style, arbitrary control structures
 5540: 
 5541: In order to ensure readability we recommend that you do not create
 5542: arbitrary control structures directly, but define new control structure
 5543: words for the control structure you want and use these words in your
 5544: program. For example, instead of writing:
 5545: 
 5546: @example
 5547: BEGIN
 5548:   ...
 5549: IF [ 1 CS-ROLL ]
 5550:   ...
 5551: AGAIN THEN
 5552: @end example
 5553: 
 5554: @noindent
 5555: we recommend defining control structure words, e.g.,
 5556: 
 5557: @example
 5558: : WHILE ( DEST -- ORIG DEST )
 5559:  POSTPONE IF
 5560:  1 CS-ROLL ; immediate
 5561: 
 5562: : REPEAT ( orig dest -- )
 5563:  POSTPONE AGAIN
 5564:  POSTPONE THEN ; immediate
 5565: @end example
 5566: 
 5567: @noindent
 5568: and then using these to create the control structure:
 5569: 
 5570: @example
 5571: BEGIN
 5572:   ...
 5573: WHILE
 5574:   ...
 5575: REPEAT
 5576: @end example
 5577: 
 5578: That's much easier to read, isn't it? Of course, @code{REPEAT} and
 5579: @code{WHILE} are predefined, so in this example it would not be
 5580: necessary to define them.
 5581: 
 5582: @node Calls and returns, Exception Handling, Arbitrary control structures, Control Structures
 5583: @subsection Calls and returns
 5584: @cindex calling a definition
 5585: @cindex returning from a definition
 5586: 
 5587: @cindex recursive definitions
 5588: A definition can be called simply be writing the name of the definition
 5589: to be called. Normally a definition is invisible during its own
 5590: definition. If you want to write a directly recursive definition, you
 5591: can use @code{recursive} to make the current definition visible, or
 5592: @code{recurse} to call the current definition directly.
 5593: 
 5594: 
 5595: doc-recursive
 5596: doc-recurse
 5597: 
 5598: 
 5599: @comment TODO add example of the two recursion methods
 5600: @quotation
 5601: @progstyle
 5602: I prefer using @code{recursive} to @code{recurse}, because calling the
 5603: definition by name is more descriptive (if the name is well-chosen) than
 5604: the somewhat cryptic @code{recurse}.  E.g., in a quicksort
 5605: implementation, it is much better to read (and think) ``now sort the
 5606: partitions'' than to read ``now do a recursive call''.
 5607: @end quotation
 5608: 
 5609: For mutual recursion, use @code{Defer}red words, like this:
 5610: 
 5611: @example
 5612: Defer foo
 5613: 
 5614: : bar ( ... -- ... )
 5615:  ... foo ... ;
 5616: 
 5617: :noname ( ... -- ... )
 5618:  ... bar ... ;
 5619: IS foo
 5620: @end example
 5621: 
 5622: Deferred words are discussed in more detail in @ref{Deferred words}.
 5623: 
 5624: The current definition returns control to the calling definition when
 5625: the end of the definition is reached or @code{EXIT} is encountered.
 5626: 
 5627: doc-exit
 5628: doc-;s
 5629: 
 5630: 
 5631: @node Exception Handling,  , Calls and returns, Control Structures
 5632: @subsection Exception Handling
 5633: @cindex exceptions
 5634: 
 5635: @c quit is a very bad idea for error handling, 
 5636: @c because it does not translate into a THROW
 5637: @c it also does not belong into this chapter
 5638: 
 5639: If a word detects an error condition that it cannot handle, it can
 5640: @code{throw} an exception.  In the simplest case, this will terminate
 5641: your program, and report an appropriate error.
 5642: 
 5643: doc-throw
 5644: 
 5645: @code{Throw} consumes a cell-sized error number on the stack. There are
 5646: some predefined error numbers in ANS Forth (see @file{errors.fs}).  In
 5647: Gforth (and most other systems) you can use the iors produced by various
 5648: words as error numbers (e.g., a typical use of @code{allocate} is
 5649: @code{allocate throw}).  Gforth also provides the word @code{exception}
 5650: to define your own error numbers (with decent error reporting); an ANS
 5651: Forth version of this word (but without the error messages) is available
 5652: in @code{compat/except.fs}.  And finally, you can use your own error
 5653: numbers (anything outside the range -4095..0), but won't get nice error
 5654: messages, only numbers.  For example, try:
 5655: 
 5656: @example
 5657: -10 throw                    \ ANS defined
 5658: -267 throw                   \ system defined
 5659: s" my error" exception throw \ user defined
 5660: 7 throw                      \ arbitrary number
 5661: @end example
 5662: 
 5663: doc---exception-exception
 5664: 
 5665: A common idiom to @code{THROW} a specific error if a flag is true is
 5666: this:
 5667: 
 5668: @example
 5669: @code{( flag ) 0<> @i{errno} and throw}
 5670: @end example
 5671: 
 5672: Your program can provide exception handlers to catch exceptions.  An
 5673: exception handler can be used to correct the problem, or to clean up
 5674: some data structures and just throw the exception to the next exception
 5675: handler.  Note that @code{throw} jumps to the dynamically innermost
 5676: exception handler.  The system's exception handler is outermost, and just
 5677: prints an error and restarts command-line interpretation (or, in batch
 5678: mode (i.e., while processing the shell command line), leaves Gforth).
 5679: 
 5680: The ANS Forth way to catch exceptions is @code{catch}:
 5681: 
 5682: doc-catch
 5683: doc-nothrow
 5684: 
 5685: The most common use of exception handlers is to clean up the state when
 5686: an error happens.  E.g.,
 5687: 
 5688: @example
 5689: base @ >r hex \ actually the hex should be inside foo, or we h
 5690: ['] foo catch ( nerror|0 )
 5691: r> base !
 5692: ( nerror|0 ) throw \ pass it on
 5693: @end example
 5694: 
 5695: A use of @code{catch} for handling the error @code{myerror} might look
 5696: like this:
 5697: 
 5698: @example
 5699: ['] foo catch
 5700: CASE
 5701:   myerror OF ... ( do something about it ) nothrow ENDOF
 5702:   dup throw \ default: pass other errors on, do nothing on non-errors
 5703: ENDCASE
 5704: @end example
 5705: 
 5706: Having to wrap the code into a separate word is often cumbersome,
 5707: therefore Gforth provides an alternative syntax:
 5708: 
 5709: @example
 5710: TRY
 5711:   @i{code1}
 5712: RECOVER
 5713:   @i{code2} \ optional
 5714: ENDTRY
 5715: @end example
 5716: 
 5717: This performs @i{Code1}.  If @i{code1} completes normally, execution
 5718: continues after the @code{endtry}.  If @i{Code1} throws, the stacks are
 5719: reset to the state during @code{try}, the throw value is pushed on the
 5720: data stack, and execution constinues at @i{code2}, and finally falls
 5721: through the @code{endtry} into the following code.
 5722: 
 5723: doc-try
 5724: doc-recover
 5725: doc-endtry
 5726: 
 5727: The cleanup example from above in this syntax:
 5728: 
 5729: @example
 5730: base @ >r TRY
 5731:   hex foo \ now the hex is placed correctly
 5732:   0       \ value for throw
 5733: RECOVER ENDTRY
 5734: r> base ! throw
 5735: @end example
 5736: 
 5737: And here's the error handling example:
 5738: 
 5739: @example
 5740: TRY
 5741:   foo
 5742: RECOVER
 5743:   CASE
 5744:     myerror OF ... ( do something about it ) nothrow ENDOF
 5745:     throw \ pass other errors on
 5746:   ENDCASE
 5747: ENDTRY
 5748: @end example
 5749: 
 5750: @progstyle
 5751: As usual, you should ensure that the stack depth is statically known at
 5752: the end: either after the @code{throw} for passing on errors, or after
 5753: the @code{ENDTRY} (or, if you use @code{catch}, after the end of the
 5754: selection construct for handling the error).
 5755: 
 5756: There are two alternatives to @code{throw}: @code{Abort"} is conditional
 5757: and you can provide an error message.  @code{Abort} just produces an
 5758: ``Aborted'' error.
 5759: 
 5760: The problem with these words is that exception handlers cannot
 5761: differentiate between different @code{abort"}s; they just look like
 5762: @code{-2 throw} to them (the error message cannot be accessed by
 5763: standard programs).  Similar @code{abort} looks like @code{-1 throw} to
 5764: exception handlers.
 5765: 
 5766: doc-abort"
 5767: doc-abort
 5768: 
 5769: 
 5770: 
 5771: @c -------------------------------------------------------------
 5772: @node Defining Words, Interpretation and Compilation Semantics, Control Structures, Words
 5773: @section Defining Words
 5774: @cindex defining words
 5775: 
 5776: Defining words are used to extend Forth by creating new entries in the dictionary.
 5777: 
 5778: @menu
 5779: * CREATE::                      
 5780: * Variables::                   Variables and user variables
 5781: * Constants::                   
 5782: * Values::                      Initialised variables
 5783: * Colon Definitions::           
 5784: * Anonymous Definitions::       Definitions without names
 5785: * Supplying names::             Passing definition names as strings
 5786: * User-defined Defining Words::  
 5787: * Deferred words::              Allow forward references
 5788: * Aliases::                     
 5789: @end menu
 5790: 
 5791: @node CREATE, Variables, Defining Words, Defining Words
 5792: @subsection @code{CREATE}
 5793: @cindex simple defining words
 5794: @cindex defining words, simple
 5795: 
 5796: Defining words are used to create new entries in the dictionary. The
 5797: simplest defining word is @code{CREATE}. @code{CREATE} is used like
 5798: this:
 5799: 
 5800: @example
 5801: CREATE new-word1
 5802: @end example
 5803: 
 5804: @code{CREATE} is a parsing word, i.e., it takes an argument from the
 5805: input stream (@code{new-word1} in our example).  It generates a
 5806: dictionary entry for @code{new-word1}. When @code{new-word1} is
 5807: executed, all that it does is leave an address on the stack. The address
 5808: represents the value of the data space pointer (@code{HERE}) at the time
 5809: that @code{new-word1} was defined. Therefore, @code{CREATE} is a way of
 5810: associating a name with the address of a region of memory.
 5811: 
 5812: doc-create
 5813: 
 5814: Note that in ANS Forth guarantees only for @code{create} that its body
 5815: is in dictionary data space (i.e., where @code{here}, @code{allot}
 5816: etc. work, @pxref{Dictionary allocation}).  Also, in ANS Forth only
 5817: @code{create}d words can be modified with @code{does>}
 5818: (@pxref{User-defined Defining Words}).  And in ANS Forth @code{>body}
 5819: can only be applied to @code{create}d words.
 5820: 
 5821: By extending this example to reserve some memory in data space, we end
 5822: up with something like a @i{variable}. Here are two different ways to do
 5823: it:
 5824: 
 5825: @example
 5826: CREATE new-word2 1 cells allot  \ reserve 1 cell - initial value undefined
 5827: CREATE new-word3 4 ,            \ reserve 1 cell and initialise it (to 4)
 5828: @end example
 5829: 
 5830: The variable can be examined and modified using @code{@@} (``fetch'') and
 5831: @code{!} (``store'') like this:
 5832: 
 5833: @example
 5834: new-word2 @@ .      \ get address, fetch from it and display
 5835: 1234 new-word2 !   \ new value, get address, store to it
 5836: @end example
 5837: 
 5838: @cindex arrays
 5839: A similar mechanism can be used to create arrays. For example, an
 5840: 80-character text input buffer:
 5841: 
 5842: @example
 5843: CREATE text-buf 80 chars allot
 5844: 
 5845: text-buf 0 chars c@@ \ the 1st character (offset 0)
 5846: text-buf 3 chars c@@ \ the 4th character (offset 3)
 5847: @end example
 5848: 
 5849: You can build arbitrarily complex data structures by allocating
 5850: appropriate areas of memory. For further discussions of this, and to
 5851: learn about some Gforth tools that make it easier,
 5852: @xref{Structures}.
 5853: 
 5854: 
 5855: @node Variables, Constants, CREATE, Defining Words
 5856: @subsection Variables
 5857: @cindex variables
 5858: 
 5859: The previous section showed how a sequence of commands could be used to
 5860: generate a variable.  As a final refinement, the whole code sequence can
 5861: be wrapped up in a defining word (pre-empting the subject of the next
 5862: section), making it easier to create new variables:
 5863: 
 5864: @example
 5865: : myvariableX ( "name" -- a-addr ) CREATE 1 cells allot ;
 5866: : myvariable0 ( "name" -- a-addr ) CREATE 0 , ;
 5867: 
 5868: myvariableX foo \ variable foo starts off with an unknown value
 5869: myvariable0 joe \ whilst joe is initialised to 0
 5870: 
 5871: 45 3 * foo !   \ set foo to 135
 5872: 1234 joe !     \ set joe to 1234
 5873: 3 joe +!       \ increment joe by 3.. to 1237
 5874: @end example
 5875: 
 5876: Not surprisingly, there is no need to define @code{myvariable}, since
 5877: Forth already has a definition @code{Variable}. ANS Forth does not
 5878: guarantee that a @code{Variable} is initialised when it is created
 5879: (i.e., it may behave like @code{myvariableX}). In contrast, Gforth's
 5880: @code{Variable} initialises the variable to 0 (i.e., it behaves exactly
 5881: like @code{myvariable0}). Forth also provides @code{2Variable} and
 5882: @code{fvariable} for double and floating-point variables, respectively
 5883: -- they are initialised to 0. and 0e in Gforth. If you use a @code{Variable} to
 5884: store a boolean, you can use @code{on} and @code{off} to toggle its
 5885: state.
 5886: 
 5887: doc-variable
 5888: doc-2variable
 5889: doc-fvariable
 5890: 
 5891: @cindex user variables
 5892: @cindex user space
 5893: The defining word @code{User} behaves in the same way as @code{Variable}.
 5894: The difference is that it reserves space in @i{user (data) space} rather
 5895: than normal data space. In a Forth system that has a multi-tasker, each
 5896: task has its own set of user variables.
 5897: 
 5898: doc-user
 5899: @c doc-udp
 5900: @c doc-uallot
 5901: 
 5902: @comment TODO is that stuff about user variables strictly correct? Is it
 5903: @comment just terminal tasks that have user variables?
 5904: @comment should document tasker.fs (with some examples) elsewhere
 5905: @comment in this manual, then expand on user space and user variables.
 5906: 
 5907: @node Constants, Values, Variables, Defining Words
 5908: @subsection Constants
 5909: @cindex constants
 5910: 
 5911: @code{Constant} allows you to declare a fixed value and refer to it by
 5912: name. For example:
 5913: 
 5914: @example
 5915: 12 Constant INCHES-PER-FOOT
 5916: 3E+08 fconstant SPEED-O-LIGHT
 5917: @end example
 5918: 
 5919: A @code{Variable} can be both read and written, so its run-time
 5920: behaviour is to supply an address through which its current value can be
 5921: manipulated. In contrast, the value of a @code{Constant} cannot be
 5922: changed once it has been declared@footnote{Well, often it can be -- but
 5923: not in a Standard, portable way. It's safer to use a @code{Value} (read
 5924: on).} so it's not necessary to supply the address -- it is more
 5925: efficient to return the value of the constant directly. That's exactly
 5926: what happens; the run-time effect of a constant is to put its value on
 5927: the top of the stack (You can find one
 5928: way of implementing @code{Constant} in @ref{User-defined Defining Words}).
 5929: 
 5930: Forth also provides @code{2Constant} and @code{fconstant} for defining
 5931: double and floating-point constants, respectively.
 5932: 
 5933: doc-constant
 5934: doc-2constant
 5935: doc-fconstant
 5936: 
 5937: @c that's too deep, and it's not necessarily true for all ANS Forths. - anton
 5938: @c nac-> How could that not be true in an ANS Forth? You can't define a
 5939: @c constant, use it and then delete the definition of the constant..
 5940: 
 5941: @c anton->An ANS Forth system can compile a constant to a literal; On
 5942: @c decompilation you would see only the number, just as if it had been used
 5943: @c in the first place.  The word will stay, of course, but it will only be
 5944: @c used by the text interpreter (no run-time duties, except when it is 
 5945: @c POSTPONEd or somesuch).
 5946: 
 5947: @c nac:
 5948: @c I agree that it's rather deep, but IMO it is an important difference
 5949: @c relative to other programming languages.. often it's annoying: it
 5950: @c certainly changes my programming style relative to C.
 5951: 
 5952: @c anton: In what way?
 5953: 
 5954: Constants in Forth behave differently from their equivalents in other
 5955: programming languages. In other languages, a constant (such as an EQU in
 5956: assembler or a #define in C) only exists at compile-time; in the
 5957: executable program the constant has been translated into an absolute
 5958: number and, unless you are using a symbolic debugger, it's impossible to
 5959: know what abstract thing that number represents. In Forth a constant has
 5960: an entry in the header space and remains there after the code that uses
 5961: it has been defined. In fact, it must remain in the dictionary since it
 5962: has run-time duties to perform. For example:
 5963: 
 5964: @example
 5965: 12 Constant INCHES-PER-FOOT
 5966: : FEET-TO-INCHES ( n1 -- n2 ) INCHES-PER-FOOT * ;
 5967: @end example
 5968: 
 5969: @cindex in-lining of constants
 5970: When @code{FEET-TO-INCHES} is executed, it will in turn execute the xt
 5971: associated with the constant @code{INCHES-PER-FOOT}. If you use
 5972: @code{see} to decompile the definition of @code{FEET-TO-INCHES}, you can
 5973: see that it makes a call to @code{INCHES-PER-FOOT}. Some Forth compilers
 5974: attempt to optimise constants by in-lining them where they are used. You
 5975: can force Gforth to in-line a constant like this:
 5976: 
 5977: @example
 5978: : FEET-TO-INCHES ( n1 -- n2 ) [ INCHES-PER-FOOT ] LITERAL * ;
 5979: @end example
 5980: 
 5981: If you use @code{see} to decompile @i{this} version of
 5982: @code{FEET-TO-INCHES}, you can see that @code{INCHES-PER-FOOT} is no
 5983: longer present. To understand how this works, read
 5984: @ref{Interpret/Compile states}, and @ref{Literals}.
 5985: 
 5986: In-lining constants in this way might improve execution time
 5987: fractionally, and can ensure that a constant is now only referenced at
 5988: compile-time. However, the definition of the constant still remains in
 5989: the dictionary. Some Forth compilers provide a mechanism for controlling
 5990: a second dictionary for holding transient words such that this second
 5991: dictionary can be deleted later in order to recover memory
 5992: space. However, there is no standard way of doing this.
 5993: 
 5994: 
 5995: @node Values, Colon Definitions, Constants, Defining Words
 5996: @subsection Values
 5997: @cindex values
 5998: 
 5999: A @code{Value} behaves like a @code{Constant}, but it can be changed.
 6000: @code{TO} is a parsing word that changes a @code{Values}.  In Gforth
 6001: (not in ANS Forth) you can access (and change) a @code{value} also with
 6002: @code{>body}.
 6003: 
 6004: Here are some
 6005: examples:
 6006: 
 6007: @example
 6008: 12 Value APPLES     \ Define APPLES with an initial value of 12
 6009: 34 TO APPLES        \ Change the value of APPLES. TO is a parsing word
 6010: 1 ' APPLES >body +! \ Increment APPLES.  Non-standard usage.
 6011: APPLES              \ puts 35 on the top of the stack.
 6012: @end example
 6013: 
 6014: doc-value
 6015: doc-to
 6016: 
 6017: 
 6018: 
 6019: @node Colon Definitions, Anonymous Definitions, Values, Defining Words
 6020: @subsection Colon Definitions
 6021: @cindex colon definitions
 6022: 
 6023: @example
 6024: : name ( ... -- ... )
 6025:     word1 word2 word3 ;
 6026: @end example
 6027: 
 6028: @noindent
 6029: Creates a word called @code{name} that, upon execution, executes
 6030: @code{word1 word2 word3}. @code{name} is a @dfn{(colon) definition}.
 6031: 
 6032: The explanation above is somewhat superficial. For simple examples of
 6033: colon definitions see @ref{Your first definition}.  For an in-depth
 6034: discussion of some of the issues involved, @xref{Interpretation and
 6035: Compilation Semantics}.
 6036: 
 6037: doc-:
 6038: doc-;
 6039: 
 6040: 
 6041: @node Anonymous Definitions, Supplying names, Colon Definitions, Defining Words
 6042: @subsection Anonymous Definitions
 6043: @cindex colon definitions
 6044: @cindex defining words without name
 6045: 
 6046: Sometimes you want to define an @dfn{anonymous word}; a word without a
 6047: name. You can do this with:
 6048: 
 6049: doc-:noname
 6050: 
 6051: This leaves the execution token for the word on the stack after the
 6052: closing @code{;}. Here's an example in which a deferred word is
 6053: initialised with an @code{xt} from an anonymous colon definition:
 6054: 
 6055: @example
 6056: Defer deferred
 6057: :noname ( ... -- ... )
 6058:   ... ;
 6059: IS deferred
 6060: @end example
 6061: 
 6062: @noindent
 6063: Gforth provides an alternative way of doing this, using two separate
 6064: words:
 6065: 
 6066: doc-noname
 6067: @cindex execution token of last defined word
 6068: doc-latestxt
 6069: 
 6070: @noindent
 6071: The previous example can be rewritten using @code{noname} and
 6072: @code{latestxt}:
 6073: 
 6074: @example
 6075: Defer deferred
 6076: noname : ( ... -- ... )
 6077:   ... ;
 6078: latestxt IS deferred
 6079: @end example
 6080: 
 6081: @noindent
 6082: @code{noname} works with any defining word, not just @code{:}.
 6083: 
 6084: @code{latestxt} also works when the last word was not defined as
 6085: @code{noname}.  It does not work for combined words, though.  It also has
 6086: the useful property that is is valid as soon as the header for a
 6087: definition has been built. Thus:
 6088: 
 6089: @example
 6090: latestxt . : foo [ latestxt . ] ; ' foo .
 6091: @end example
 6092: 
 6093: @noindent
 6094: prints 3 numbers; the last two are the same.
 6095: 
 6096: @node Supplying names, User-defined Defining Words, Anonymous Definitions, Defining Words
 6097: @subsection Supplying the name of a defined word
 6098: @cindex names for defined words
 6099: @cindex defining words, name given in a string
 6100: 
 6101: By default, a defining word takes the name for the defined word from the
 6102: input stream. Sometimes you want to supply the name from a string. You
 6103: can do this with:
 6104: 
 6105: doc-nextname
 6106: 
 6107: For example:
 6108: 
 6109: @example
 6110: s" foo" nextname create
 6111: @end example
 6112: 
 6113: @noindent
 6114: is equivalent to:
 6115: 
 6116: @example
 6117: create foo
 6118: @end example
 6119: 
 6120: @noindent
 6121: @code{nextname} works with any defining word.
 6122: 
 6123: 
 6124: @node User-defined Defining Words, Deferred words, Supplying names, Defining Words
 6125: @subsection User-defined Defining Words
 6126: @cindex user-defined defining words
 6127: @cindex defining words, user-defined
 6128: 
 6129: You can create a new defining word by wrapping defining-time code around
 6130: an existing defining word and putting the sequence in a colon
 6131: definition. 
 6132: 
 6133: @c anton: This example is very complex and leads in a quite different
 6134: @c direction from the CREATE-DOES> stuff that follows.  It should probably
 6135: @c be done elsewhere, or as a subsubsection of this subsection (or as a
 6136: @c subsection of Defining Words)
 6137: 
 6138: For example, suppose that you have a word @code{stats} that
 6139: gathers statistics about colon definitions given the @i{xt} of the
 6140: definition, and you want every colon definition in your application to
 6141: make a call to @code{stats}. You can define and use a new version of
 6142: @code{:} like this:
 6143: 
 6144: @example
 6145: : stats ( xt -- ) DUP ." (Gathering statistics for " . ." )"
 6146:   ... ;  \ other code
 6147: 
 6148: : my: : latestxt postpone literal ['] stats compile, ;
 6149: 
 6150: my: foo + - ;
 6151: @end example
 6152: 
 6153: When @code{foo} is defined using @code{my:} these steps occur:
 6154: 
 6155: @itemize @bullet
 6156: @item
 6157: @code{my:} is executed.
 6158: @item
 6159: The @code{:} within the definition (the one between @code{my:} and
 6160: @code{latestxt}) is executed, and does just what it always does; it parses
 6161: the input stream for a name, builds a dictionary header for the name
 6162: @code{foo} and switches @code{state} from interpret to compile.
 6163: @item
 6164: The word @code{latestxt} is executed. It puts the @i{xt} for the word that is
 6165: being defined -- @code{foo} -- onto the stack.
 6166: @item
 6167: The code that was produced by @code{postpone literal} is executed; this
 6168: causes the value on the stack to be compiled as a literal in the code
 6169: area of @code{foo}.
 6170: @item
 6171: The code @code{['] stats} compiles a literal into the definition of
 6172: @code{my:}. When @code{compile,} is executed, that literal -- the
 6173: execution token for @code{stats} -- is layed down in the code area of
 6174: @code{foo} , following the literal@footnote{Strictly speaking, the
 6175: mechanism that @code{compile,} uses to convert an @i{xt} into something
 6176: in the code area is implementation-dependent. A threaded implementation
 6177: might spit out the execution token directly whilst another
 6178: implementation might spit out a native code sequence.}.
 6179: @item
 6180: At this point, the execution of @code{my:} is complete, and control
 6181: returns to the text interpreter. The text interpreter is in compile
 6182: state, so subsequent text @code{+ -} is compiled into the definition of
 6183: @code{foo} and the @code{;} terminates the definition as always.
 6184: @end itemize
 6185: 
 6186: You can use @code{see} to decompile a word that was defined using
 6187: @code{my:} and see how it is different from a normal @code{:}
 6188: definition. For example:
 6189: 
 6190: @example
 6191: : bar + - ;  \ like foo but using : rather than my:
 6192: see bar
 6193: : bar
 6194:   + - ;
 6195: see foo
 6196: : foo
 6197:   107645672 stats + - ;
 6198: 
 6199: \ use ' foo . to show that 107645672 is the xt for foo
 6200: @end example
 6201: 
 6202: You can use techniques like this to make new defining words in terms of
 6203: @i{any} existing defining word.
 6204: 
 6205: 
 6206: @cindex defining defining words
 6207: @cindex @code{CREATE} ... @code{DOES>}
 6208: If you want the words defined with your defining words to behave
 6209: differently from words defined with standard defining words, you can
 6210: write your defining word like this:
 6211: 
 6212: @example
 6213: : def-word ( "name" -- )
 6214:     CREATE @i{code1}
 6215: DOES> ( ... -- ... )
 6216:     @i{code2} ;
 6217: 
 6218: def-word name
 6219: @end example
 6220: 
 6221: @cindex child words
 6222: This fragment defines a @dfn{defining word} @code{def-word} and then
 6223: executes it.  When @code{def-word} executes, it @code{CREATE}s a new
 6224: word, @code{name}, and executes the code @i{code1}. The code @i{code2}
 6225: is not executed at this time. The word @code{name} is sometimes called a
 6226: @dfn{child} of @code{def-word}.
 6227: 
 6228: When you execute @code{name}, the address of the body of @code{name} is
 6229: put on the data stack and @i{code2} is executed (the address of the body
 6230: of @code{name} is the address @code{HERE} returns immediately after the
 6231: @code{CREATE}, i.e., the address a @code{create}d word returns by
 6232: default).
 6233: 
 6234: @c anton:
 6235: @c www.dictionary.com says:
 6236: @c at·a·vism: 1.The reappearance of a characteristic in an organism after
 6237: @c several generations of absence, usually caused by the chance
 6238: @c recombination of genes.  2.An individual or a part that exhibits
 6239: @c atavism. Also called throwback.  3.The return of a trait or recurrence
 6240: @c of previous behavior after a period of absence.
 6241: @c
 6242: @c Doesn't seem to fit.
 6243: 
 6244: @c @cindex atavism in child words
 6245: You can use @code{def-word} to define a set of child words that behave
 6246: similarly; they all have a common run-time behaviour determined by
 6247: @i{code2}. Typically, the @i{code1} sequence builds a data area in the
 6248: body of the child word. The structure of the data is common to all
 6249: children of @code{def-word}, but the data values are specific -- and
 6250: private -- to each child word. When a child word is executed, the
 6251: address of its private data area is passed as a parameter on TOS to be
 6252: used and manipulated@footnote{It is legitimate both to read and write to
 6253: this data area.} by @i{code2}.
 6254: 
 6255: The two fragments of code that make up the defining words act (are
 6256: executed) at two completely separate times:
 6257: 
 6258: @itemize @bullet
 6259: @item
 6260: At @i{define time}, the defining word executes @i{code1} to generate a
 6261: child word
 6262: @item
 6263: At @i{child execution time}, when a child word is invoked, @i{code2}
 6264: is executed, using parameters (data) that are private and specific to
 6265: the child word.
 6266: @end itemize
 6267: 
 6268: Another way of understanding the behaviour of @code{def-word} and
 6269: @code{name} is to say that, if you make the following definitions:
 6270: @example
 6271: : def-word1 ( "name" -- )
 6272:     CREATE @i{code1} ;
 6273: 
 6274: : action1 ( ... -- ... )
 6275:     @i{code2} ;
 6276: 
 6277: def-word1 name1
 6278: @end example
 6279: 
 6280: @noindent
 6281: Then using @code{name1 action1} is equivalent to using @code{name}.
 6282: 
 6283: The classic example is that you can define @code{CONSTANT} in this way:
 6284: 
 6285: @example
 6286: : CONSTANT ( w "name" -- )
 6287:     CREATE ,
 6288: DOES> ( -- w )
 6289:     @@ ;
 6290: @end example
 6291: 
 6292: @comment There is a beautiful description of how this works and what
 6293: @comment it does in the Forthwrite 100th edition.. as well as an elegant
 6294: @comment commentary on the Counting Fruits problem.
 6295: 
 6296: When you create a constant with @code{5 CONSTANT five}, a set of
 6297: define-time actions take place; first a new word @code{five} is created,
 6298: then the value 5 is laid down in the body of @code{five} with
 6299: @code{,}. When @code{five} is executed, the address of the body is put on
 6300: the stack, and @code{@@} retrieves the value 5. The word @code{five} has
 6301: no code of its own; it simply contains a data field and a pointer to the
 6302: code that follows @code{DOES>} in its defining word. That makes words
 6303: created in this way very compact.
 6304: 
 6305: The final example in this section is intended to remind you that space
 6306: reserved in @code{CREATE}d words is @i{data} space and therefore can be
 6307: both read and written by a Standard program@footnote{Exercise: use this
 6308: example as a starting point for your own implementation of @code{Value}
 6309: and @code{TO} -- if you get stuck, investigate the behaviour of @code{'} and
 6310: @code{[']}.}:
 6311: 
 6312: @example
 6313: : foo ( "name" -- )
 6314:     CREATE -1 ,
 6315: DOES> ( -- )
 6316:     @@ . ;
 6317: 
 6318: foo first-word
 6319: foo second-word
 6320: 
 6321: 123 ' first-word >BODY !
 6322: @end example
 6323: 
 6324: If @code{first-word} had been a @code{CREATE}d word, we could simply
 6325: have executed it to get the address of its data field. However, since it
 6326: was defined to have @code{DOES>} actions, its execution semantics are to
 6327: perform those @code{DOES>} actions. To get the address of its data field
 6328: it's necessary to use @code{'} to get its xt, then @code{>BODY} to
 6329: translate the xt into the address of the data field.  When you execute
 6330: @code{first-word}, it will display @code{123}. When you execute
 6331: @code{second-word} it will display @code{-1}.
 6332: 
 6333: @cindex stack effect of @code{DOES>}-parts
 6334: @cindex @code{DOES>}-parts, stack effect
 6335: In the examples above the stack comment after the @code{DOES>} specifies
 6336: the stack effect of the defined words, not the stack effect of the
 6337: following code (the following code expects the address of the body on
 6338: the top of stack, which is not reflected in the stack comment). This is
 6339: the convention that I use and recommend (it clashes a bit with using
 6340: locals declarations for stack effect specification, though).
 6341: 
 6342: @menu
 6343: * CREATE..DOES> applications::  
 6344: * CREATE..DOES> details::       
 6345: * Advanced does> usage example::  
 6346: * Const-does>::                 
 6347: @end menu
 6348: 
 6349: @node CREATE..DOES> applications, CREATE..DOES> details, User-defined Defining Words, User-defined Defining Words
 6350: @subsubsection Applications of @code{CREATE..DOES>}
 6351: @cindex @code{CREATE} ... @code{DOES>}, applications
 6352: 
 6353: You may wonder how to use this feature. Here are some usage patterns:
 6354: 
 6355: @cindex factoring similar colon definitions
 6356: When you see a sequence of code occurring several times, and you can
 6357: identify a meaning, you will factor it out as a colon definition. When
 6358: you see similar colon definitions, you can factor them using
 6359: @code{CREATE..DOES>}. E.g., an assembler usually defines several words
 6360: that look very similar:
 6361: @example
 6362: : ori, ( reg-target reg-source n -- )
 6363:     0 asm-reg-reg-imm ;
 6364: : andi, ( reg-target reg-source n -- )
 6365:     1 asm-reg-reg-imm ;
 6366: @end example
 6367: 
 6368: @noindent
 6369: This could be factored with:
 6370: @example
 6371: : reg-reg-imm ( op-code -- )
 6372:     CREATE ,
 6373: DOES> ( reg-target reg-source n -- )
 6374:     @@ asm-reg-reg-imm ;
 6375: 
 6376: 0 reg-reg-imm ori,
 6377: 1 reg-reg-imm andi,
 6378: @end example
 6379: 
 6380: @cindex currying
 6381: Another view of @code{CREATE..DOES>} is to consider it as a crude way to
 6382: supply a part of the parameters for a word (known as @dfn{currying} in
 6383: the functional language community). E.g., @code{+} needs two
 6384: parameters. Creating versions of @code{+} with one parameter fixed can
 6385: be done like this:
 6386: 
 6387: @example
 6388: : curry+ ( n1 "name" -- )
 6389:     CREATE ,
 6390: DOES> ( n2 -- n1+n2 )
 6391:     @@ + ;
 6392: 
 6393:  3 curry+ 3+
 6394: -2 curry+ 2-
 6395: @end example
 6396: 
 6397: 
 6398: @node CREATE..DOES> details, Advanced does> usage example, CREATE..DOES> applications, User-defined Defining Words
 6399: @subsubsection The gory details of @code{CREATE..DOES>}
 6400: @cindex @code{CREATE} ... @code{DOES>}, details
 6401: 
 6402: doc-does>
 6403: 
 6404: @cindex @code{DOES>} in a separate definition
 6405: This means that you need not use @code{CREATE} and @code{DOES>} in the
 6406: same definition; you can put the @code{DOES>}-part in a separate
 6407: definition. This allows us to, e.g., select among different @code{DOES>}-parts:
 6408: @example
 6409: : does1 
 6410: DOES> ( ... -- ... )
 6411:     ... ;
 6412: 
 6413: : does2
 6414: DOES> ( ... -- ... )
 6415:     ... ;
 6416: 
 6417: : def-word ( ... -- ... )
 6418:     create ...
 6419:     IF
 6420:        does1
 6421:     ELSE
 6422:        does2
 6423:     ENDIF ;
 6424: @end example
 6425: 
 6426: In this example, the selection of whether to use @code{does1} or
 6427: @code{does2} is made at definition-time; at the time that the child word is
 6428: @code{CREATE}d.
 6429: 
 6430: @cindex @code{DOES>} in interpretation state
 6431: In a standard program you can apply a @code{DOES>}-part only if the last
 6432: word was defined with @code{CREATE}. In Gforth, the @code{DOES>}-part
 6433: will override the behaviour of the last word defined in any case. In a
 6434: standard program, you can use @code{DOES>} only in a colon
 6435: definition. In Gforth, you can also use it in interpretation state, in a
 6436: kind of one-shot mode; for example:
 6437: @example
 6438: CREATE name ( ... -- ... )
 6439:   @i{initialization}
 6440: DOES>
 6441:   @i{code} ;
 6442: @end example
 6443: 
 6444: @noindent
 6445: is equivalent to the standard:
 6446: @example
 6447: :noname
 6448: DOES>
 6449:     @i{code} ;
 6450: CREATE name EXECUTE ( ... -- ... )
 6451:     @i{initialization}
 6452: @end example
 6453: 
 6454: doc->body
 6455: 
 6456: @node Advanced does> usage example, Const-does>, CREATE..DOES> details, User-defined Defining Words
 6457: @subsubsection Advanced does> usage example
 6458: 
 6459: The MIPS disassembler (@file{arch/mips/disasm.fs}) contains many words
 6460: for disassembling instructions, that follow a very repetetive scheme:
 6461: 
 6462: @example
 6463: :noname @var{disasm-operands} s" @var{inst-name}" type ;
 6464: @var{entry-num} cells @var{table} + !
 6465: @end example
 6466: 
 6467: Of course, this inspires the idea to factor out the commonalities to
 6468: allow a definition like
 6469: 
 6470: @example
 6471: @var{disasm-operands} @var{entry-num} @var{table} define-inst @var{inst-name}
 6472: @end example
 6473: 
 6474: The parameters @var{disasm-operands} and @var{table} are usually
 6475: correlated.  Moreover, before I wrote the disassembler, there already
 6476: existed code that defines instructions like this:
 6477: 
 6478: @example
 6479: @var{entry-num} @var{inst-format} @var{inst-name}
 6480: @end example
 6481: 
 6482: This code comes from the assembler and resides in
 6483: @file{arch/mips/insts.fs}.
 6484: 
 6485: So I had to define the @var{inst-format} words that performed the scheme
 6486: above when executed.  At first I chose to use run-time code-generation:
 6487: 
 6488: @example
 6489: : @var{inst-format} ( entry-num "name" -- ; compiled code: addr w -- )
 6490:   :noname Postpone @var{disasm-operands}
 6491:   name Postpone sliteral Postpone type Postpone ;
 6492:   swap cells @var{table} + ! ;
 6493: @end example
 6494: 
 6495: Note that this supplies the other two parameters of the scheme above.
 6496: 
 6497: An alternative would have been to write this using
 6498: @code{create}/@code{does>}:
 6499: 
 6500: @example
 6501: : @var{inst-format} ( entry-num "name" -- )
 6502:   here name string, ( entry-num c-addr ) \ parse and save "name"
 6503:   noname create , ( entry-num )
 6504:   latestxt swap cells @var{table} + !
 6505: does> ( addr w -- )
 6506:   \ disassemble instruction w at addr
 6507:   @@ >r 
 6508:   @var{disasm-operands}
 6509:   r> count type ;
 6510: @end example
 6511: 
 6512: Somehow the first solution is simpler, mainly because it's simpler to
 6513: shift a string from definition-time to use-time with @code{sliteral}
 6514: than with @code{string,} and friends.
 6515: 
 6516: I wrote a lot of words following this scheme and soon thought about
 6517: factoring out the commonalities among them.  Note that this uses a
 6518: two-level defining word, i.e., a word that defines ordinary defining
 6519: words.
 6520: 
 6521: This time a solution involving @code{postpone} and friends seemed more
 6522: difficult (try it as an exercise), so I decided to use a
 6523: @code{create}/@code{does>} word; since I was already at it, I also used
 6524: @code{create}/@code{does>} for the lower level (try using
 6525: @code{postpone} etc. as an exercise), resulting in the following
 6526: definition:
 6527: 
 6528: @example
 6529: : define-format ( disasm-xt table-xt -- )
 6530:     \ define an instruction format that uses disasm-xt for
 6531:     \ disassembling and enters the defined instructions into table
 6532:     \ table-xt
 6533:     create 2,
 6534: does> ( u "inst" -- )
 6535:     \ defines an anonymous word for disassembling instruction inst,
 6536:     \ and enters it as u-th entry into table-xt
 6537:     2@@ swap here name string, ( u table-xt disasm-xt c-addr ) \ remember string
 6538:     noname create 2,      \ define anonymous word
 6539:     execute latestxt swap ! \ enter xt of defined word into table-xt
 6540: does> ( addr w -- )
 6541:     \ disassemble instruction w at addr
 6542:     2@@ >r ( addr w disasm-xt R: c-addr )
 6543:     execute ( R: c-addr ) \ disassemble operands
 6544:     r> count type ; \ print name 
 6545: @end example
 6546: 
 6547: Note that the tables here (in contrast to above) do the @code{cells +}
 6548: by themselves (that's why you have to pass an xt).  This word is used in
 6549: the following way:
 6550: 
 6551: @example
 6552: ' @var{disasm-operands} ' @var{table} define-format @var{inst-format}
 6553: @end example
 6554: 
 6555: As shown above, the defined instruction format is then used like this:
 6556: 
 6557: @example
 6558: @var{entry-num} @var{inst-format} @var{inst-name}
 6559: @end example
 6560: 
 6561: In terms of currying, this kind of two-level defining word provides the
 6562: parameters in three stages: first @var{disasm-operands} and @var{table},
 6563: then @var{entry-num} and @var{inst-name}, finally @code{addr w}, i.e.,
 6564: the instruction to be disassembled.  
 6565: 
 6566: Of course this did not quite fit all the instruction format names used
 6567: in @file{insts.fs}, so I had to define a few wrappers that conditioned
 6568: the parameters into the right form.
 6569: 
 6570: If you have trouble following this section, don't worry.  First, this is
 6571: involved and takes time (and probably some playing around) to
 6572: understand; second, this is the first two-level
 6573: @code{create}/@code{does>} word I have written in seventeen years of
 6574: Forth; and if I did not have @file{insts.fs} to start with, I may well
 6575: have elected to use just a one-level defining word (with some repeating
 6576: of parameters when using the defining word). So it is not necessary to
 6577: understand this, but it may improve your understanding of Forth.
 6578: 
 6579: 
 6580: @node Const-does>,  , Advanced does> usage example, User-defined Defining Words
 6581: @subsubsection @code{Const-does>}
 6582: 
 6583: A frequent use of @code{create}...@code{does>} is for transferring some
 6584: values from definition-time to run-time.  Gforth supports this use with
 6585: 
 6586: doc-const-does>
 6587: 
 6588: A typical use of this word is:
 6589: 
 6590: @example
 6591: : curry+ ( n1 "name" -- )
 6592: 1 0 CONST-DOES> ( n2 -- n1+n2 )
 6593:     + ;
 6594: 
 6595: 3 curry+ 3+
 6596: @end example
 6597: 
 6598: Here the @code{1 0} means that 1 cell and 0 floats are transferred from
 6599: definition to run-time.
 6600: 
 6601: The advantages of using @code{const-does>} are:
 6602: 
 6603: @itemize
 6604: 
 6605: @item
 6606: You don't have to deal with storing and retrieving the values, i.e.,
 6607: your program becomes more writable and readable.
 6608: 
 6609: @item
 6610: When using @code{does>}, you have to introduce a @code{@@} that cannot
 6611: be optimized away (because you could change the data using
 6612: @code{>body}...@code{!}); @code{const-does>} avoids this problem.
 6613: 
 6614: @end itemize
 6615: 
 6616: An ANS Forth implementation of @code{const-does>} is available in
 6617: @file{compat/const-does.fs}.
 6618: 
 6619: 
 6620: @node Deferred words, Aliases, User-defined Defining Words, Defining Words
 6621: @subsection Deferred words
 6622: @cindex deferred words
 6623: 
 6624: The defining word @code{Defer} allows you to define a word by name
 6625: without defining its behaviour; the definition of its behaviour is
 6626: deferred. Here are two situation where this can be useful:
 6627: 
 6628: @itemize @bullet
 6629: @item
 6630: Where you want to allow the behaviour of a word to be altered later, and
 6631: for all precompiled references to the word to change when its behaviour
 6632: is changed.
 6633: @item
 6634: For mutual recursion; @xref{Calls and returns}.
 6635: @end itemize
 6636: 
 6637: In the following example, @code{foo} always invokes the version of
 6638: @code{greet} that prints ``@code{Good morning}'' whilst @code{bar}
 6639: always invokes the version that prints ``@code{Hello}''. There is no way
 6640: of getting @code{foo} to use the later version without re-ordering the
 6641: source code and recompiling it.
 6642: 
 6643: @example
 6644: : greet ." Good morning" ;
 6645: : foo ... greet ... ;
 6646: : greet ." Hello" ;
 6647: : bar ... greet ... ;
 6648: @end example
 6649: 
 6650: This problem can be solved by defining @code{greet} as a @code{Defer}red
 6651: word. The behaviour of a @code{Defer}red word can be defined and
 6652: redefined at any time by using @code{IS} to associate the xt of a
 6653: previously-defined word with it. The previous example becomes:
 6654: 
 6655: @example
 6656: Defer greet ( -- )
 6657: : foo ... greet ... ;
 6658: : bar ... greet ... ;
 6659: : greet1 ( -- ) ." Good morning" ;
 6660: : greet2 ( -- ) ." Hello" ;
 6661: ' greet2 IS greet  \ make greet behave like greet2
 6662: @end example
 6663: 
 6664: @progstyle
 6665: You should write a stack comment for every deferred word, and put only
 6666: XTs into deferred words that conform to this stack effect.  Otherwise
 6667: it's too difficult to use the deferred word.
 6668: 
 6669: A deferred word can be used to improve the statistics-gathering example
 6670: from @ref{User-defined Defining Words}; rather than edit the
 6671: application's source code to change every @code{:} to a @code{my:}, do
 6672: this:
 6673: 
 6674: @example
 6675: : real: : ;     \ retain access to the original
 6676: defer :         \ redefine as a deferred word
 6677: ' my: IS :      \ use special version of :
 6678: \
 6679: \ load application here
 6680: \
 6681: ' real: IS :    \ go back to the original
 6682: @end example
 6683: 
 6684: 
 6685: One thing to note is that @code{IS} has special compilation semantics,
 6686: such that it parses the name at compile time (like @code{TO}):
 6687: 
 6688: @example
 6689: : set-greet ( xt -- )
 6690:   IS greet ;
 6691: 
 6692: ' greet1 set-greet
 6693: @end example
 6694: 
 6695: In situations where @code{IS} does not fit, use @code{defer!} instead.
 6696: 
 6697: A deferred word can only inherit execution semantics from the xt
 6698: (because that is all that an xt can represent -- for more discussion of
 6699: this @pxref{Tokens for Words}); by default it will have default
 6700: interpretation and compilation semantics deriving from this execution
 6701: semantics.  However, you can change the interpretation and compilation
 6702: semantics of the deferred word in the usual ways:
 6703: 
 6704: @example
 6705: : bar .... ; immediate
 6706: Defer fred immediate
 6707: Defer jim
 6708: 
 6709: ' bar IS jim  \ jim has default semantics
 6710: ' bar IS fred \ fred is immediate
 6711: @end example
 6712: 
 6713: doc-defer
 6714: doc-defer!
 6715: doc-is
 6716: doc-defer@
 6717: doc-action-of
 6718: @comment TODO document these: what's defers [is]
 6719: doc-defers
 6720: 
 6721: @c Use @code{words-deferred} to see a list of deferred words.
 6722: 
 6723: Definitions of these words (except @code{defers}) in ANS Forth are
 6724: provided in @file{compat/defer.fs}.
 6725: 
 6726: 
 6727: @node Aliases,  , Deferred words, Defining Words
 6728: @subsection Aliases
 6729: @cindex aliases
 6730: 
 6731: The defining word @code{Alias} allows you to define a word by name that
 6732: has the same behaviour as some other word. Here are two situation where
 6733: this can be useful:
 6734: 
 6735: @itemize @bullet
 6736: @item
 6737: When you want access to a word's definition from a different word list
 6738: (for an example of this, see the definition of the @code{Root} word list
 6739: in the Gforth source).
 6740: @item
 6741: When you want to create a synonym; a definition that can be known by
 6742: either of two names (for example, @code{THEN} and @code{ENDIF} are
 6743: aliases).
 6744: @end itemize
 6745: 
 6746: Like deferred words, an alias has default compilation and interpretation
 6747: semantics at the beginning (not the modifications of the other word),
 6748: but you can change them in the usual ways (@code{immediate},
 6749: @code{compile-only}). For example:
 6750: 
 6751: @example
 6752: : foo ... ; immediate
 6753: 
 6754: ' foo Alias bar \ bar is not an immediate word
 6755: ' foo Alias fooby immediate \ fooby is an immediate word
 6756: @end example
 6757: 
 6758: Words that are aliases have the same xt, different headers in the
 6759: dictionary, and consequently different name tokens (@pxref{Tokens for
 6760: Words}) and possibly different immediate flags.  An alias can only have
 6761: default or immediate compilation semantics; you can define aliases for
 6762: combined words with @code{interpret/compile:} -- see @ref{Combined words}.
 6763: 
 6764: doc-alias
 6765: 
 6766: 
 6767: @node Interpretation and Compilation Semantics, Tokens for Words, Defining Words, Words
 6768: @section Interpretation and Compilation Semantics
 6769: @cindex semantics, interpretation and compilation
 6770: 
 6771: @c !! state and ' are used without explanation
 6772: @c example for immediate/compile-only? or is the tutorial enough
 6773: 
 6774: @cindex interpretation semantics
 6775: The @dfn{interpretation semantics} of a (named) word are what the text
 6776: interpreter does when it encounters the word in interpret state. It also
 6777: appears in some other contexts, e.g., the execution token returned by
 6778: @code{' @i{word}} identifies the interpretation semantics of @i{word}
 6779: (in other words, @code{' @i{word} execute} is equivalent to
 6780: interpret-state text interpretation of @code{@i{word}}).
 6781: 
 6782: @cindex compilation semantics
 6783: The @dfn{compilation semantics} of a (named) word are what the text
 6784: interpreter does when it encounters the word in compile state. It also
 6785: appears in other contexts, e.g, @code{POSTPONE @i{word}}
 6786: compiles@footnote{In standard terminology, ``appends to the current
 6787: definition''.} the compilation semantics of @i{word}.
 6788: 
 6789: @cindex execution semantics
 6790: The standard also talks about @dfn{execution semantics}. They are used
 6791: only for defining the interpretation and compilation semantics of many
 6792: words. By default, the interpretation semantics of a word are to
 6793: @code{execute} its execution semantics, and the compilation semantics of
 6794: a word are to @code{compile,} its execution semantics.@footnote{In
 6795: standard terminology: The default interpretation semantics are its
 6796: execution semantics; the default compilation semantics are to append its
 6797: execution semantics to the execution semantics of the current
 6798: definition.}
 6799: 
 6800: Unnamed words (@pxref{Anonymous Definitions}) cannot be encountered by
 6801: the text interpreter, ticked, or @code{postpone}d, so they have no
 6802: interpretation or compilation semantics.  Their behaviour is represented
 6803: by their XT (@pxref{Tokens for Words}), and we call it execution
 6804: semantics, too.
 6805: 
 6806: @comment TODO expand, make it co-operate with new sections on text interpreter.
 6807: 
 6808: @cindex immediate words
 6809: @cindex compile-only words
 6810: You can change the semantics of the most-recently defined word:
 6811: 
 6812: 
 6813: doc-immediate
 6814: doc-compile-only
 6815: doc-restrict
 6816: 
 6817: By convention, words with non-default compilation semantics (e.g.,
 6818: immediate words) often have names surrounded with brackets (e.g.,
 6819: @code{[']}, @pxref{Execution token}).
 6820: 
 6821: Note that ticking (@code{'}) a compile-only word gives an error
 6822: (``Interpreting a compile-only word'').
 6823: 
 6824: @menu
 6825: * Combined words::              
 6826: @end menu
 6827: 
 6828: 
 6829: @node Combined words,  , Interpretation and Compilation Semantics, Interpretation and Compilation Semantics
 6830: @subsection Combined Words
 6831: @cindex combined words
 6832: 
 6833: Gforth allows you to define @dfn{combined words} -- words that have an
 6834: arbitrary combination of interpretation and compilation semantics.
 6835: 
 6836: doc-interpret/compile:
 6837: 
 6838: This feature was introduced for implementing @code{TO} and @code{S"}. I
 6839: recommend that you do not define such words, as cute as they may be:
 6840: they make it hard to get at both parts of the word in some contexts.
 6841: E.g., assume you want to get an execution token for the compilation
 6842: part. Instead, define two words, one that embodies the interpretation
 6843: part, and one that embodies the compilation part.  Once you have done
 6844: that, you can define a combined word with @code{interpret/compile:} for
 6845: the convenience of your users.
 6846: 
 6847: You might try to use this feature to provide an optimizing
 6848: implementation of the default compilation semantics of a word. For
 6849: example, by defining:
 6850: @example
 6851: :noname
 6852:    foo bar ;
 6853: :noname
 6854:    POSTPONE foo POSTPONE bar ;
 6855: interpret/compile: opti-foobar
 6856: @end example
 6857: 
 6858: @noindent
 6859: as an optimizing version of:
 6860: 
 6861: @example
 6862: : foobar
 6863:     foo bar ;
 6864: @end example
 6865: 
 6866: Unfortunately, this does not work correctly with @code{[compile]},
 6867: because @code{[compile]} assumes that the compilation semantics of all
 6868: @code{interpret/compile:} words are non-default. I.e., @code{[compile]
 6869: opti-foobar} would compile compilation semantics, whereas
 6870: @code{[compile] foobar} would compile interpretation semantics.
 6871: 
 6872: @cindex state-smart words (are a bad idea)
 6873: @anchor{state-smartness}
 6874: Some people try to use @dfn{state-smart} words to emulate the feature provided
 6875: by @code{interpret/compile:} (words are state-smart if they check
 6876: @code{STATE} during execution). E.g., they would try to code
 6877: @code{foobar} like this:
 6878: 
 6879: @example
 6880: : foobar
 6881:   STATE @@
 6882:   IF ( compilation state )
 6883:     POSTPONE foo POSTPONE bar
 6884:   ELSE
 6885:     foo bar
 6886:   ENDIF ; immediate
 6887: @end example
 6888: 
 6889: Although this works if @code{foobar} is only processed by the text
 6890: interpreter, it does not work in other contexts (like @code{'} or
 6891: @code{POSTPONE}). E.g., @code{' foobar} will produce an execution token
 6892: for a state-smart word, not for the interpretation semantics of the
 6893: original @code{foobar}; when you execute this execution token (directly
 6894: with @code{EXECUTE} or indirectly through @code{COMPILE,}) in compile
 6895: state, the result will not be what you expected (i.e., it will not
 6896: perform @code{foo bar}). State-smart words are a bad idea. Simply don't
 6897: write them@footnote{For a more detailed discussion of this topic, see
 6898: M. Anton Ertl,
 6899: @cite{@uref{http://www.complang.tuwien.ac.at/papers/ertl98.ps.gz,@code{State}-smartness---Why
 6900: it is Evil and How to Exorcise it}}, EuroForth '98.}!
 6901: 
 6902: @cindex defining words with arbitrary semantics combinations
 6903: It is also possible to write defining words that define words with
 6904: arbitrary combinations of interpretation and compilation semantics. In
 6905: general, they look like this:
 6906: 
 6907: @example
 6908: : def-word
 6909:     create-interpret/compile
 6910:     @i{code1}
 6911: interpretation>
 6912:     @i{code2}
 6913: <interpretation
 6914: compilation>
 6915:     @i{code3}
 6916: <compilation ;
 6917: @end example
 6918: 
 6919: For a @i{word} defined with @code{def-word}, the interpretation
 6920: semantics are to push the address of the body of @i{word} and perform
 6921: @i{code2}, and the compilation semantics are to push the address of
 6922: the body of @i{word} and perform @i{code3}. E.g., @code{constant}
 6923: can also be defined like this (except that the defined constants don't
 6924: behave correctly when @code{[compile]}d):
 6925: 
 6926: @example
 6927: : constant ( n "name" -- )
 6928:     create-interpret/compile
 6929:     ,
 6930: interpretation> ( -- n )
 6931:     @@
 6932: <interpretation
 6933: compilation> ( compilation. -- ; run-time. -- n )
 6934:     @@ postpone literal
 6935: <compilation ;
 6936: @end example
 6937: 
 6938: 
 6939: doc-create-interpret/compile
 6940: doc-interpretation>
 6941: doc-<interpretation
 6942: doc-compilation>
 6943: doc-<compilation
 6944: 
 6945: 
 6946: Words defined with @code{interpret/compile:} and
 6947: @code{create-interpret/compile} have an extended header structure that
 6948: differs from other words; however, unless you try to access them with
 6949: plain address arithmetic, you should not notice this. Words for
 6950: accessing the header structure usually know how to deal with this; e.g.,
 6951: @code{'} @i{word} @code{>body} also gives you the body of a word created
 6952: with @code{create-interpret/compile}.
 6953: 
 6954: 
 6955: @c -------------------------------------------------------------
 6956: @node Tokens for Words, Compiling words, Interpretation and Compilation Semantics, Words
 6957: @section Tokens for Words
 6958: @cindex tokens for words
 6959: 
 6960: This section describes the creation and use of tokens that represent
 6961: words.
 6962: 
 6963: @menu
 6964: * Execution token::             represents execution/interpretation semantics
 6965: * Compilation token::           represents compilation semantics
 6966: * Name token::                  represents named words
 6967: @end menu
 6968: 
 6969: @node Execution token, Compilation token, Tokens for Words, Tokens for Words
 6970: @subsection Execution token
 6971: 
 6972: @cindex xt
 6973: @cindex execution token
 6974: An @dfn{execution token} (@i{XT}) represents some behaviour of a word.
 6975: You can use @code{execute} to invoke this behaviour.
 6976: 
 6977: @cindex tick (')
 6978: You can use @code{'} to get an execution token that represents the
 6979: interpretation semantics of a named word:
 6980: 
 6981: @example
 6982: 5 ' .   ( n xt ) 
 6983: execute ( )      \ execute the xt (i.e., ".")
 6984: @end example
 6985: 
 6986: doc-'
 6987: 
 6988: @code{'} parses at run-time; there is also a word @code{[']} that parses
 6989: when it is compiled, and compiles the resulting XT:
 6990: 
 6991: @example
 6992: : foo ['] . execute ;
 6993: 5 foo
 6994: : bar ' execute ; \ by contrast,
 6995: 5 bar .           \ ' parses "." when bar executes
 6996: @end example
 6997: 
 6998: doc-[']
 6999: 
 7000: If you want the execution token of @i{word}, write @code{['] @i{word}}
 7001: in compiled code and @code{' @i{word}} in interpreted code.  Gforth's
 7002: @code{'} and @code{[']} behave somewhat unusually by complaining about
 7003: compile-only words (because these words have no interpretation
 7004: semantics).  You might get what you want by using @code{COMP' @i{word}
 7005: DROP} or @code{[COMP'] @i{word} DROP} (for details @pxref{Compilation
 7006: token}).
 7007: 
 7008: Another way to get an XT is @code{:noname} or @code{latestxt}
 7009: (@pxref{Anonymous Definitions}).  For anonymous words this gives an xt
 7010: for the only behaviour the word has (the execution semantics).  For
 7011: named words, @code{latestxt} produces an XT for the same behaviour it
 7012: would produce if the word was defined anonymously.
 7013: 
 7014: @example
 7015: :noname ." hello" ;
 7016: execute
 7017: @end example
 7018: 
 7019: An XT occupies one cell and can be manipulated like any other cell.
 7020: 
 7021: @cindex code field address
 7022: @cindex CFA
 7023: In ANS Forth the XT is just an abstract data type (i.e., defined by the
 7024: operations that produce or consume it).  For old hands: In Gforth, the
 7025: XT is implemented as a code field address (CFA).
 7026: 
 7027: doc-execute
 7028: doc-perform
 7029: 
 7030: @node Compilation token, Name token, Execution token, Tokens for Words
 7031: @subsection Compilation token
 7032: 
 7033: @cindex compilation token
 7034: @cindex CT (compilation token)
 7035: Gforth represents the compilation semantics of a named word by a
 7036: @dfn{compilation token} consisting of two cells: @i{w xt}. The top cell
 7037: @i{xt} is an execution token. The compilation semantics represented by
 7038: the compilation token can be performed with @code{execute}, which
 7039: consumes the whole compilation token, with an additional stack effect
 7040: determined by the represented compilation semantics.
 7041: 
 7042: At present, the @i{w} part of a compilation token is an execution token,
 7043: and the @i{xt} part represents either @code{execute} or
 7044: @code{compile,}@footnote{Depending upon the compilation semantics of the
 7045: word. If the word has default compilation semantics, the @i{xt} will
 7046: represent @code{compile,}. Otherwise (e.g., for immediate words), the
 7047: @i{xt} will represent @code{execute}.}. However, don't rely on that
 7048: knowledge, unless necessary; future versions of Gforth may introduce
 7049: unusual compilation tokens (e.g., a compilation token that represents
 7050: the compilation semantics of a literal).
 7051: 
 7052: You can perform the compilation semantics represented by the compilation
 7053: token with @code{execute}.  You can compile the compilation semantics
 7054: with @code{postpone,}. I.e., @code{COMP' @i{word} postpone,} is
 7055: equivalent to @code{postpone @i{word}}.
 7056: 
 7057: doc-[comp']
 7058: doc-comp'
 7059: doc-postpone,
 7060: 
 7061: @node Name token,  , Compilation token, Tokens for Words
 7062: @subsection Name token
 7063: 
 7064: @cindex name token
 7065: Gforth represents named words by the @dfn{name token}, (@i{nt}).  Name
 7066: token is an abstract data type that occurs as argument or result of the
 7067: words below.
 7068: 
 7069: @c !! put this elswhere?
 7070: @cindex name field address
 7071: @cindex NFA
 7072: The closest thing to the nt in older Forth systems is the name field
 7073: address (NFA), but there are significant differences: in older Forth
 7074: systems each word had a unique NFA, LFA, CFA and PFA (in this order, or
 7075: LFA, NFA, CFA, PFA) and there were words for getting from one to the
 7076: next.  In contrast, in Gforth 0@dots{}n nts correspond to one xt; there
 7077: is a link field in the structure identified by the name token, but
 7078: searching usually uses a hash table external to these structures; the
 7079: name in Gforth has a cell-wide count-and-flags field, and the nt is not
 7080: implemented as the address of that count field.
 7081: 
 7082: doc-find-name
 7083: doc-latest
 7084: doc->name
 7085: doc-name>int
 7086: doc-name?int
 7087: doc-name>comp
 7088: doc-name>string
 7089: doc-id.
 7090: doc-.name
 7091: doc-.id
 7092: 
 7093: @c ----------------------------------------------------------
 7094: @node Compiling words, The Text Interpreter, Tokens for Words, Words
 7095: @section Compiling words
 7096: @cindex compiling words
 7097: @cindex macros
 7098: 
 7099: In contrast to most other languages, Forth has no strict boundary
 7100: between compilation and run-time.  E.g., you can run arbitrary code
 7101: between defining words (or for computing data used by defining words
 7102: like @code{constant}). Moreover, @code{Immediate} (@pxref{Interpretation
 7103: and Compilation Semantics} and @code{[}...@code{]} (see below) allow
 7104: running arbitrary code while compiling a colon definition (exception:
 7105: you must not allot dictionary space).
 7106: 
 7107: @menu
 7108: * Literals::                    Compiling data values
 7109: * Macros::                      Compiling words
 7110: @end menu
 7111: 
 7112: @node Literals, Macros, Compiling words, Compiling words
 7113: @subsection Literals
 7114: @cindex Literals
 7115: 
 7116: The simplest and most frequent example is to compute a literal during
 7117: compilation.  E.g., the following definition prints an array of strings,
 7118: one string per line:
 7119: 
 7120: @example
 7121: : .strings ( addr u -- ) \ gforth
 7122:     2* cells bounds U+DO
 7123: 	cr i 2@@ type
 7124:     2 cells +LOOP ;  
 7125: @end example
 7126: 
 7127: With a simple-minded compiler like Gforth's, this computes @code{2
 7128: cells} on every loop iteration.  You can compute this value once and for
 7129: all at compile time and compile it into the definition like this:
 7130: 
 7131: @example
 7132: : .strings ( addr u -- ) \ gforth
 7133:     2* cells bounds U+DO
 7134: 	cr i 2@@ type
 7135:     [ 2 cells ] literal +LOOP ;  
 7136: @end example
 7137: 
 7138: @code{[} switches the text interpreter to interpret state (you will get
 7139: an @code{ok} prompt if you type this example interactively and insert a
 7140: newline between @code{[} and @code{]}), so it performs the
 7141: interpretation semantics of @code{2 cells}; this computes a number.
 7142: @code{]} switches the text interpreter back into compile state.  It then
 7143: performs @code{Literal}'s compilation semantics, which are to compile
 7144: this number into the current word.  You can decompile the word with
 7145: @code{see .strings} to see the effect on the compiled code.
 7146: 
 7147: You can also optimize the @code{2* cells} into @code{[ 2 cells ] literal
 7148: *} in this way.
 7149: 
 7150: doc-[
 7151: doc-]
 7152: doc-literal
 7153: doc-]L
 7154: 
 7155: There are also words for compiling other data types than single cells as
 7156: literals:
 7157: 
 7158: doc-2literal
 7159: doc-fliteral
 7160: doc-sliteral
 7161: 
 7162: @cindex colon-sys, passing data across @code{:}
 7163: @cindex @code{:}, passing data across
 7164: You might be tempted to pass data from outside a colon definition to the
 7165: inside on the data stack.  This does not work, because @code{:} puhes a
 7166: colon-sys, making stuff below unaccessible.  E.g., this does not work:
 7167: 
 7168: @example
 7169: 5 : foo literal ; \ error: "unstructured"
 7170: @end example
 7171: 
 7172: Instead, you have to pass the value in some other way, e.g., through a
 7173: variable:
 7174: 
 7175: @example
 7176: variable temp
 7177: 5 temp !
 7178: : foo [ temp @@ ] literal ;
 7179: @end example
 7180: 
 7181: 
 7182: @node Macros,  , Literals, Compiling words
 7183: @subsection Macros
 7184: @cindex Macros
 7185: @cindex compiling compilation semantics
 7186: 
 7187: @code{Literal} and friends compile data values into the current
 7188: definition.  You can also write words that compile other words into the
 7189: current definition.  E.g.,
 7190: 
 7191: @example
 7192: : compile-+ ( -- ) \ compiled code: ( n1 n2 -- n )
 7193:   POSTPONE + ;
 7194: 
 7195: : foo ( n1 n2 -- n )
 7196:   [ compile-+ ] ;
 7197: 1 2 foo .
 7198: @end example
 7199: 
 7200: This is equivalent to @code{: foo + ;} (@code{see foo} to check this).
 7201: What happens in this example?  @code{Postpone} compiles the compilation
 7202: semantics of @code{+} into @code{compile-+}; later the text interpreter
 7203: executes @code{compile-+} and thus the compilation semantics of +, which
 7204: compile (the execution semantics of) @code{+} into
 7205: @code{foo}.@footnote{A recent RFI answer requires that compiling words
 7206: should only be executed in compile state, so this example is not
 7207: guaranteed to work on all standard systems, but on any decent system it
 7208: will work.}
 7209: 
 7210: doc-postpone
 7211: doc-[compile]
 7212: 
 7213: Compiling words like @code{compile-+} are usually immediate (or similar)
 7214: so you do not have to switch to interpret state to execute them;
 7215: mopifying the last example accordingly produces:
 7216: 
 7217: @example
 7218: : [compile-+] ( compilation: --; interpretation: -- )
 7219:   \ compiled code: ( n1 n2 -- n )
 7220:   POSTPONE + ; immediate
 7221: 
 7222: : foo ( n1 n2 -- n )
 7223:   [compile-+] ;
 7224: 1 2 foo .
 7225: @end example
 7226: 
 7227: Immediate compiling words are similar to macros in other languages (in
 7228: particular, Lisp).  The important differences to macros in, e.g., C are:
 7229: 
 7230: @itemize @bullet
 7231: 
 7232: @item
 7233: You use the same language for defining and processing macros, not a
 7234: separate preprocessing language and processor.
 7235: 
 7236: @item
 7237: Consequently, the full power of Forth is available in macro definitions.
 7238: E.g., you can perform arbitrarily complex computations, or generate
 7239: different code conditionally or in a loop (e.g., @pxref{Advanced macros
 7240: Tutorial}).  This power is very useful when writing a parser generators
 7241: or other code-generating software.
 7242: 
 7243: @item
 7244: Macros defined using @code{postpone} etc. deal with the language at a
 7245: higher level than strings; name binding happens at macro definition
 7246: time, so you can avoid the pitfalls of name collisions that can happen
 7247: in C macros.  Of course, Forth is a liberal language and also allows to
 7248: shoot yourself in the foot with text-interpreted macros like
 7249: 
 7250: @example
 7251: : [compile-+] s" +" evaluate ; immediate
 7252: @end example
 7253: 
 7254: Apart from binding the name at macro use time, using @code{evaluate}
 7255: also makes your definition @code{state}-smart (@pxref{state-smartness}).
 7256: @end itemize
 7257: 
 7258: You may want the macro to compile a number into a word.  The word to do
 7259: it is @code{literal}, but you have to @code{postpone} it, so its
 7260: compilation semantics take effect when the macro is executed, not when
 7261: it is compiled:
 7262: 
 7263: @example
 7264: : [compile-5] ( -- ) \ compiled code: ( -- n )
 7265:   5 POSTPONE literal ; immediate
 7266: 
 7267: : foo [compile-5] ;
 7268: foo .
 7269: @end example
 7270: 
 7271: You may want to pass parameters to a macro, that the macro should
 7272: compile into the current definition.  If the parameter is a number, then
 7273: you can use @code{postpone literal} (similar for other values).
 7274: 
 7275: If you want to pass a word that is to be compiled, the usual way is to
 7276: pass an execution token and @code{compile,} it:
 7277: 
 7278: @example
 7279: : twice1 ( xt -- ) \ compiled code: ... -- ...
 7280:   dup compile, compile, ;
 7281: 
 7282: : 2+ ( n1 -- n2 )
 7283:   [ ' 1+ twice1 ] ;
 7284: @end example
 7285: 
 7286: doc-compile,
 7287: 
 7288: An alternative available in Gforth, that allows you to pass compile-only
 7289: words as parameters is to use the compilation token (@pxref{Compilation
 7290: token}).  The same example in this technique:
 7291: 
 7292: @example
 7293: : twice ( ... ct -- ... ) \ compiled code: ... -- ...
 7294:   2dup 2>r execute 2r> execute ;
 7295: 
 7296: : 2+ ( n1 -- n2 )
 7297:   [ comp' 1+ twice ] ;
 7298: @end example
 7299: 
 7300: In the example above @code{2>r} and @code{2r>} ensure that @code{twice}
 7301: works even if the executed compilation semantics has an effect on the
 7302: data stack.
 7303: 
 7304: You can also define complete definitions with these words; this provides
 7305: an alternative to using @code{does>} (@pxref{User-defined Defining
 7306: Words}).  E.g., instead of
 7307: 
 7308: @example
 7309: : curry+ ( n1 "name" -- )
 7310:     CREATE ,
 7311: DOES> ( n2 -- n1+n2 )
 7312:     @@ + ;
 7313: @end example
 7314: 
 7315: you could define
 7316: 
 7317: @example
 7318: : curry+ ( n1 "name" -- )
 7319:   \ name execution: ( n2 -- n1+n2 )
 7320:   >r : r> POSTPONE literal POSTPONE + POSTPONE ; ;
 7321: 
 7322: -3 curry+ 3-
 7323: see 3-
 7324: @end example
 7325: 
 7326: The sequence @code{>r : r>} is necessary, because @code{:} puts a
 7327: colon-sys on the data stack that makes everything below it unaccessible.
 7328: 
 7329: This way of writing defining words is sometimes more, sometimes less
 7330: convenient than using @code{does>} (@pxref{Advanced does> usage
 7331: example}).  One advantage of this method is that it can be optimized
 7332: better, because the compiler knows that the value compiled with
 7333: @code{literal} is fixed, whereas the data associated with a
 7334: @code{create}d word can be changed.
 7335: 
 7336: @c ----------------------------------------------------------
 7337: @node The Text Interpreter, The Input Stream, Compiling words, Words
 7338: @section  The Text Interpreter
 7339: @cindex interpreter - outer
 7340: @cindex text interpreter
 7341: @cindex outer interpreter
 7342: 
 7343: @c Should we really describe all these ugly details?  IMO the text
 7344: @c interpreter should be much cleaner, but that may not be possible within
 7345: @c ANS Forth. - anton
 7346: @c nac-> I wanted to explain how it works to show how you can exploit
 7347: @c it in your own programs. When I was writing a cross-compiler, figuring out
 7348: @c some of these gory details was very helpful to me. None of the textbooks
 7349: @c I've seen cover it, and the most modern Forth textbook -- Forth Inc's,
 7350: @c seems to positively avoid going into too much detail for some of
 7351: @c the internals.
 7352: 
 7353: @c anton: ok.  I wonder, though, if this is the right place; for some stuff
 7354: @c it is; for the ugly details, I would prefer another place.  I wonder
 7355: @c whether we should have a chapter before "Words" that describes some
 7356: @c basic concepts referred to in words, and a chapter after "Words" that
 7357: @c describes implementation details.
 7358: 
 7359: The text interpreter@footnote{This is an expanded version of the
 7360: material in @ref{Introducing the Text Interpreter}.} is an endless loop
 7361: that processes input from the current input device. It is also called
 7362: the outer interpreter, in contrast to the inner interpreter
 7363: (@pxref{Engine}) which executes the compiled Forth code on interpretive
 7364: implementations.
 7365: 
 7366: @cindex interpret state
 7367: @cindex compile state
 7368: The text interpreter operates in one of two states: @dfn{interpret
 7369: state} and @dfn{compile state}. The current state is defined by the
 7370: aptly-named variable @code{state}.
 7371: 
 7372: This section starts by describing how the text interpreter behaves when
 7373: it is in interpret state, processing input from the user input device --
 7374: the keyboard. This is the mode that a Forth system is in after it starts
 7375: up.
 7376: 
 7377: @cindex input buffer
 7378: @cindex terminal input buffer
 7379: The text interpreter works from an area of memory called the @dfn{input
 7380: buffer}@footnote{When the text interpreter is processing input from the
 7381: keyboard, this area of memory is called the @dfn{terminal input buffer}
 7382: (TIB) and is addressed by the (obsolescent) words @code{TIB} and
 7383: @code{#TIB}.}, which stores your keyboard input when you press the
 7384: @key{RET} key. Starting at the beginning of the input buffer, it skips
 7385: leading spaces (called @dfn{delimiters}) then parses a string (a
 7386: sequence of non-space characters) until it reaches either a space
 7387: character or the end of the buffer. Having parsed a string, it makes two
 7388: attempts to process it:
 7389: 
 7390: @cindex dictionary
 7391: @itemize @bullet
 7392: @item
 7393: It looks for the string in a @dfn{dictionary} of definitions. If the
 7394: string is found, the string names a @dfn{definition} (also known as a
 7395: @dfn{word}) and the dictionary search returns information that allows
 7396: the text interpreter to perform the word's @dfn{interpretation
 7397: semantics}. In most cases, this simply means that the word will be
 7398: executed.
 7399: @item
 7400: If the string is not found in the dictionary, the text interpreter
 7401: attempts to treat it as a number, using the rules described in
 7402: @ref{Number Conversion}. If the string represents a legal number in the
 7403: current radix, the number is pushed onto a parameter stack (the data
 7404: stack for integers, the floating-point stack for floating-point
 7405: numbers).
 7406: @end itemize
 7407: 
 7408: If both attempts fail, or if the word is found in the dictionary but has
 7409: no interpretation semantics@footnote{This happens if the word was
 7410: defined as @code{COMPILE-ONLY}.} the text interpreter discards the
 7411: remainder of the input buffer, issues an error message and waits for
 7412: more input. If one of the attempts succeeds, the text interpreter
 7413: repeats the parsing process until the whole of the input buffer has been
 7414: processed, at which point it prints the status message ``@code{ ok}''
 7415: and waits for more input.
 7416: 
 7417: @c anton: this should be in the input stream subsection (or below it)
 7418: 
 7419: @cindex parse area
 7420: The text interpreter keeps track of its position in the input buffer by
 7421: updating a variable called @code{>IN} (pronounced ``to-in''). The value
 7422: of @code{>IN} starts out as 0, indicating an offset of 0 from the start
 7423: of the input buffer. The region from offset @code{>IN @@} to the end of
 7424: the input buffer is called the @dfn{parse area}@footnote{In other words,
 7425: the text interpreter processes the contents of the input buffer by
 7426: parsing strings from the parse area until the parse area is empty.}.
 7427: This example shows how @code{>IN} changes as the text interpreter parses
 7428: the input buffer:
 7429: 
 7430: @example
 7431: : remaining >IN @@ SOURCE 2 PICK - -ROT + SWAP
 7432:   CR ." ->" TYPE ." <-" ; IMMEDIATE 
 7433: 
 7434: 1 2 3 remaining + remaining . 
 7435: 
 7436: : foo 1 2 3 remaining SWAP remaining ;
 7437: @end example
 7438: 
 7439: @noindent
 7440: The result is:
 7441: 
 7442: @example
 7443: ->+ remaining .<-
 7444: ->.<-5  ok
 7445: 
 7446: ->SWAP remaining ;-<
 7447: ->;<-  ok
 7448: @end example
 7449: 
 7450: @cindex parsing words
 7451: The value of @code{>IN} can also be modified by a word in the input
 7452: buffer that is executed by the text interpreter.  This means that a word
 7453: can ``trick'' the text interpreter into either skipping a section of the
 7454: input buffer@footnote{This is how parsing words work.} or into parsing a
 7455: section twice. For example:
 7456: 
 7457: @example
 7458: : lat ." <<foo>>" ;
 7459: : flat ." <<bar>>" >IN DUP @@ 3 - SWAP ! ;
 7460: @end example
 7461: 
 7462: @noindent
 7463: When @code{flat} is executed, this output is produced@footnote{Exercise
 7464: for the reader: what would happen if the @code{3} were replaced with
 7465: @code{4}?}:
 7466: 
 7467: @example
 7468: <<bar>><<foo>>
 7469: @end example
 7470: 
 7471: This technique can be used to work around some of the interoperability
 7472: problems of parsing words.  Of course, it's better to avoid parsing
 7473: words where possible.
 7474: 
 7475: @noindent
 7476: Two important notes about the behaviour of the text interpreter:
 7477: 
 7478: @itemize @bullet
 7479: @item
 7480: It processes each input string to completion before parsing additional
 7481: characters from the input buffer.
 7482: @item
 7483: It treats the input buffer as a read-only region (and so must your code).
 7484: @end itemize
 7485: 
 7486: @noindent
 7487: When the text interpreter is in compile state, its behaviour changes in
 7488: these ways:
 7489: 
 7490: @itemize @bullet
 7491: @item
 7492: If a parsed string is found in the dictionary, the text interpreter will
 7493: perform the word's @dfn{compilation semantics}. In most cases, this
 7494: simply means that the execution semantics of the word will be appended
 7495: to the current definition.
 7496: @item
 7497: When a number is encountered, it is compiled into the current definition
 7498: (as a literal) rather than being pushed onto a parameter stack.
 7499: @item
 7500: If an error occurs, @code{state} is modified to put the text interpreter
 7501: back into interpret state.
 7502: @item
 7503: Each time a line is entered from the keyboard, Gforth prints
 7504: ``@code{ compiled}'' rather than `` @code{ok}''.
 7505: @end itemize
 7506: 
 7507: @cindex text interpreter - input sources
 7508: When the text interpreter is using an input device other than the
 7509: keyboard, its behaviour changes in these ways:
 7510: 
 7511: @itemize @bullet
 7512: @item
 7513: When the parse area is empty, the text interpreter attempts to refill
 7514: the input buffer from the input source. When the input source is
 7515: exhausted, the input source is set back to the previous input source.
 7516: @item
 7517: It doesn't print out ``@code{ ok}'' or ``@code{ compiled}'' messages each
 7518: time the parse area is emptied.
 7519: @item
 7520: If an error occurs, the input source is set back to the user input
 7521: device.
 7522: @end itemize
 7523: 
 7524: You can read about this in more detail in @ref{Input Sources}.
 7525: 
 7526: doc->in
 7527: doc-source
 7528: 
 7529: doc-tib
 7530: doc-#tib
 7531: 
 7532: 
 7533: @menu
 7534: * Input Sources::               
 7535: * Number Conversion::           
 7536: * Interpret/Compile states::    
 7537: * Interpreter Directives::      
 7538: @end menu
 7539: 
 7540: @node Input Sources, Number Conversion, The Text Interpreter, The Text Interpreter
 7541: @subsection Input Sources
 7542: @cindex input sources
 7543: @cindex text interpreter - input sources
 7544: 
 7545: By default, the text interpreter processes input from the user input
 7546: device (the keyboard) when Forth starts up. The text interpreter can
 7547: process input from any of these sources:
 7548: 
 7549: @itemize @bullet
 7550: @item
 7551: The user input device -- the keyboard.
 7552: @item
 7553: A file, using the words described in @ref{Forth source files}.
 7554: @item
 7555: A block, using the words described in @ref{Blocks}.
 7556: @item
 7557: A text string, using @code{evaluate}.
 7558: @end itemize
 7559: 
 7560: A program can identify the current input device from the values of
 7561: @code{source-id} and @code{blk}.
 7562: 
 7563: 
 7564: doc-source-id
 7565: doc-blk
 7566: 
 7567: doc-save-input
 7568: doc-restore-input
 7569: 
 7570: doc-evaluate
 7571: doc-query
 7572: 
 7573: 
 7574: 
 7575: @node Number Conversion, Interpret/Compile states, Input Sources, The Text Interpreter
 7576: @subsection Number Conversion
 7577: @cindex number conversion
 7578: @cindex double-cell numbers, input format
 7579: @cindex input format for double-cell numbers
 7580: @cindex single-cell numbers, input format
 7581: @cindex input format for single-cell numbers
 7582: @cindex floating-point numbers, input format
 7583: @cindex input format for floating-point numbers
 7584: 
 7585: This section describes the rules that the text interpreter uses when it
 7586: tries to convert a string into a number.
 7587: 
 7588: Let <digit> represent any character that is a legal digit in the current
 7589: number base@footnote{For example, 0-9 when the number base is decimal or
 7590: 0-9, A-F when the number base is hexadecimal.}.
 7591: 
 7592: Let <decimal digit> represent any character in the range 0-9.
 7593: 
 7594: Let @{@i{a b}@} represent the @i{optional} presence of any of the characters
 7595: in the braces (@i{a} or @i{b} or neither).
 7596: 
 7597: Let * represent any number of instances of the previous character
 7598: (including none).
 7599: 
 7600: Let any other character represent itself.
 7601: 
 7602: @noindent
 7603: Now, the conversion rules are:
 7604: 
 7605: @itemize @bullet
 7606: @item
 7607: A string of the form <digit><digit>* is treated as a single-precision
 7608: (cell-sized) positive integer. Examples are 0 123 6784532 32343212343456 42
 7609: @item
 7610: A string of the form -<digit><digit>* is treated as a single-precision
 7611: (cell-sized) negative integer, and is represented using 2's-complement
 7612: arithmetic. Examples are -45 -5681 -0
 7613: @item
 7614: A string of the form <digit><digit>*.<digit>* is treated as a double-precision
 7615: (double-cell-sized) positive integer. Examples are 3465. 3.465 34.65
 7616: (all three of these represent the same number).
 7617: @item
 7618: A string of the form -<digit><digit>*.<digit>* is treated as a
 7619: double-precision (double-cell-sized) negative integer, and is
 7620: represented using 2's-complement arithmetic. Examples are -3465. -3.465
 7621: -34.65 (all three of these represent the same number).
 7622: @item
 7623: A string of the form @{+ -@}<decimal digit>@{.@}<decimal digit>*@{e
 7624: E@}@{+ -@}<decimal digit><decimal digit>* is treated as a floating-point
 7625: number. Examples are 1e 1e0 1.e 1.e0 +1e+0 (which all represent the same
 7626: number) +12.E-4
 7627: @end itemize
 7628: 
 7629: By default, the number base used for integer number conversion is given
 7630: by the contents of the variable @code{base}.  Note that a lot of
 7631: confusion can result from unexpected values of @code{base}.  If you
 7632: change @code{base} anywhere, make sure to save the old value and restore
 7633: it afterwards.  In general I recommend keeping @code{base} decimal, and
 7634: using the prefixes described below for the popular non-decimal bases.
 7635: 
 7636: doc-dpl
 7637: doc-base
 7638: doc-hex
 7639: doc-decimal
 7640: 
 7641: @cindex '-prefix for character strings
 7642: @cindex &-prefix for decimal numbers
 7643: @cindex #-prefix for decimal numbers
 7644: @cindex %-prefix for binary numbers
 7645: @cindex $-prefix for hexadecimal numbers
 7646: @cindex 0x-prefix for hexadecimal numbers
 7647: Gforth allows you to override the value of @code{base} by using a
 7648: prefix@footnote{Some Forth implementations provide a similar scheme by
 7649: implementing @code{$} etc. as parsing words that process the subsequent
 7650: number in the input stream and push it onto the stack. For example, see
 7651: @cite{Number Conversion and Literals}, by Wil Baden; Forth Dimensions
 7652: 20(3) pages 26--27. In such implementations, unlike in Gforth, a space
 7653: is required between the prefix and the number.} before the first digit
 7654: of an (integer) number. The following prefixes are supported:
 7655: 
 7656: @itemize @bullet
 7657: @item
 7658: @code{&} -- decimal
 7659: @item
 7660: @code{#} -- decimal
 7661: @item
 7662: @code{%} -- binary
 7663: @item
 7664: @code{$} -- hexadecimal
 7665: @item
 7666: @code{0x} -- hexadecimal, if base<33.
 7667: @item
 7668: @code{'} -- numeric value (e.g., ASCII code) of next character; an
 7669: optional @code{'} may be present after the character.
 7670: @end itemize
 7671: 
 7672: Here are some examples, with the equivalent decimal number shown after
 7673: in braces:
 7674: 
 7675: -$41 (-65), %1001101 (205), %1001.0001 (145 - a double-precision number),
 7676: 'A (65),
 7677: -'a' (-97),
 7678: &905 (905), $abc (2478), $ABC (2478).
 7679: 
 7680: @cindex number conversion - traps for the unwary
 7681: @noindent
 7682: Number conversion has a number of traps for the unwary:
 7683: 
 7684: @itemize @bullet
 7685: @item
 7686: You cannot determine the current number base using the code sequence
 7687: @code{base @@ .} -- the number base is always 10 in the current number
 7688: base. Instead, use something like @code{base @@ dec.}
 7689: @item
 7690: If the number base is set to a value greater than 14 (for example,
 7691: hexadecimal), the number 123E4 is ambiguous; the conversion rules allow
 7692: it to be intepreted as either a single-precision integer or a
 7693: floating-point number (Gforth treats it as an integer). The ambiguity
 7694: can be resolved by explicitly stating the sign of the mantissa and/or
 7695: exponent: 123E+4 or +123E4 -- if the number base is decimal, no
 7696: ambiguity arises; either representation will be treated as a
 7697: floating-point number.
 7698: @item
 7699: There is a word @code{bin} but it does @i{not} set the number base!
 7700: It is used to specify file types.
 7701: @item
 7702: ANS Forth requires the @code{.} of a double-precision number to be the
 7703: final character in the string.  Gforth allows the @code{.} to be
 7704: anywhere after the first digit.
 7705: @item
 7706: The number conversion process does not check for overflow.
 7707: @item
 7708: In an ANS Forth program @code{base} is required to be decimal when
 7709: converting floating-point numbers.  In Gforth, number conversion to
 7710: floating-point numbers always uses base &10, irrespective of the value
 7711: of @code{base}.
 7712: @end itemize
 7713: 
 7714: You can read numbers into your programs with the words described in
 7715: @ref{Input}.
 7716: 
 7717: @node Interpret/Compile states, Interpreter Directives, Number Conversion, The Text Interpreter
 7718: @subsection Interpret/Compile states
 7719: @cindex Interpret/Compile states
 7720: 
 7721: A standard program is not permitted to change @code{state}
 7722: explicitly. However, it can change @code{state} implicitly, using the
 7723: words @code{[} and @code{]}. When @code{[} is executed it switches
 7724: @code{state} to interpret state, and therefore the text interpreter
 7725: starts interpreting. When @code{]} is executed it switches @code{state}
 7726: to compile state and therefore the text interpreter starts
 7727: compiling. The most common usage for these words is for switching into
 7728: interpret state and back from within a colon definition; this technique
 7729: can be used to compile a literal (for an example, @pxref{Literals}) or
 7730: for conditional compilation (for an example, @pxref{Interpreter
 7731: Directives}).
 7732: 
 7733: 
 7734: @c This is a bad example: It's non-standard, and it's not necessary.
 7735: @c However, I can't think of a good example for switching into compile
 7736: @c state when there is no current word (@code{state}-smart words are not a
 7737: @c good reason).  So maybe we should use an example for switching into
 7738: @c interpret @code{state} in a colon def. - anton
 7739: @c nac-> I agree. I started out by putting in the example, then realised
 7740: @c that it was non-ANS, so wrote more words around it. I hope this
 7741: @c re-written version is acceptable to you. I do want to keep the example
 7742: @c as it is helpful for showing what is and what is not portable, particularly
 7743: @c where it outlaws a style in common use.
 7744: 
 7745: @c anton: it's more important to show what's portable.  After we have done
 7746: @c that, we can also show what's not.  In any case, I have written a
 7747: @c section Compiling Words which also deals with [ ].
 7748: 
 7749: @c  !! The following example does not work in Gforth 0.5.9 or later.
 7750: 
 7751: @c  @code{[} and @code{]} also give you the ability to switch into compile
 7752: @c  state and back, but we cannot think of any useful Standard application
 7753: @c  for this ability. Pre-ANS Forth textbooks have examples like this:
 7754: 
 7755: @c  @example
 7756: @c  : AA ." this is A" ;
 7757: @c  : BB ." this is B" ;
 7758: @c  : CC ." this is C" ;
 7759: 
 7760: @c  create table ] aa bb cc [
 7761: 
 7762: @c  : go ( n -- ) \ n is offset into table.. 0 for 1st entry
 7763: @c    cells table + @@ execute ;
 7764: @c  @end example
 7765: 
 7766: @c  This example builds a jump table; @code{0 go} will display ``@code{this
 7767: @c  is A}''. Using @code{[} and @code{]} in this example is equivalent to
 7768: @c  defining @code{table} like this:
 7769: 
 7770: @c  @example
 7771: @c  create table ' aa COMPILE, ' bb COMPILE, ' cc COMPILE,
 7772: @c  @end example
 7773: 
 7774: @c  The problem with this code is that the definition of @code{table} is not
 7775: @c  portable -- it @i{compile}s execution tokens into code space. Whilst it
 7776: @c  @i{may} work on systems where code space and data space co-incide, the
 7777: @c  Standard only allows data space to be assigned for a @code{CREATE}d
 7778: @c  word. In addition, the Standard only allows @code{@@} to access data
 7779: @c  space, whilst this example is using it to access code space. The only
 7780: @c  portable, Standard way to build this table is to build it in data space,
 7781: @c  like this:
 7782: 
 7783: @c  @example
 7784: @c  create table ' aa , ' bb , ' cc ,
 7785: @c  @end example
 7786: 
 7787: @c  doc-state
 7788: 
 7789: 
 7790: @node Interpreter Directives,  , Interpret/Compile states, The Text Interpreter
 7791: @subsection Interpreter Directives
 7792: @cindex interpreter directives
 7793: @cindex conditional compilation
 7794: 
 7795: These words are usually used in interpret state; typically to control
 7796: which parts of a source file are processed by the text
 7797: interpreter. There are only a few ANS Forth Standard words, but Gforth
 7798: supplements these with a rich set of immediate control structure words
 7799: to compensate for the fact that the non-immediate versions can only be
 7800: used in compile state (@pxref{Control Structures}). Typical usages:
 7801: 
 7802: @example
 7803: FALSE Constant HAVE-ASSEMBLER
 7804: .
 7805: .
 7806: HAVE-ASSEMBLER [IF]
 7807: : ASSEMBLER-FEATURE
 7808:   ...
 7809: ;
 7810: [ENDIF]
 7811: .
 7812: .
 7813: : SEE
 7814:   ... \ general-purpose SEE code
 7815:   [ HAVE-ASSEMBLER [IF] ]
 7816:   ... \ assembler-specific SEE code
 7817:   [ [ENDIF] ]
 7818: ;
 7819: @end example
 7820: 
 7821: 
 7822: doc-[IF]
 7823: doc-[ELSE]
 7824: doc-[THEN]
 7825: doc-[ENDIF]
 7826: 
 7827: doc-[IFDEF]
 7828: doc-[IFUNDEF]
 7829: 
 7830: doc-[?DO]
 7831: doc-[DO]
 7832: doc-[FOR]
 7833: doc-[LOOP]
 7834: doc-[+LOOP]
 7835: doc-[NEXT]
 7836: 
 7837: doc-[BEGIN]
 7838: doc-[UNTIL]
 7839: doc-[AGAIN]
 7840: doc-[WHILE]
 7841: doc-[REPEAT]
 7842: 
 7843: 
 7844: @c -------------------------------------------------------------
 7845: @node The Input Stream, Word Lists, The Text Interpreter, Words
 7846: @section The Input Stream
 7847: @cindex input stream
 7848: 
 7849: @c !! integrate this better with the "Text Interpreter" section
 7850: The text interpreter reads from the input stream, which can come from
 7851: several sources (@pxref{Input Sources}).  Some words, in particular
 7852: defining words, but also words like @code{'}, read parameters from the
 7853: input stream instead of from the stack.
 7854: 
 7855: Such words are called parsing words, because they parse the input
 7856: stream.  Parsing words are hard to use in other words, because it is
 7857: hard to pass program-generated parameters through the input stream.
 7858: They also usually have an unintuitive combination of interpretation and
 7859: compilation semantics when implemented naively, leading to various
 7860: approaches that try to produce a more intuitive behaviour
 7861: (@pxref{Combined words}).
 7862: 
 7863: It should be obvious by now that parsing words are a bad idea.  If you
 7864: want to implement a parsing word for convenience, also provide a factor
 7865: of the word that does not parse, but takes the parameters on the stack.
 7866: To implement the parsing word on top if it, you can use the following
 7867: words:
 7868: 
 7869: @c anton: these belong in the input stream section
 7870: doc-parse
 7871: doc-parse-name
 7872: doc-parse-word
 7873: doc-name
 7874: doc-word
 7875: doc-\"-parse
 7876: doc-refill
 7877: 
 7878: Conversely, if you have the bad luck (or lack of foresight) to have to
 7879: deal with parsing words without having such factors, how do you pass a
 7880: string that is not in the input stream to it?
 7881: 
 7882: doc-execute-parsing
 7883: 
 7884: A definition of this word in ANS Forth is provided in
 7885: @file{compat/execute-parsing.fs}.
 7886: 
 7887: If you want to run a parsing word on a file, the following word should
 7888: help:
 7889: 
 7890: doc-execute-parsing-file
 7891: 
 7892: @c -------------------------------------------------------------
 7893: @node Word Lists, Environmental Queries, The Input Stream, Words
 7894: @section Word Lists
 7895: @cindex word lists
 7896: @cindex header space
 7897: 
 7898: A wordlist is a list of named words; you can add new words and look up
 7899: words by name (and you can remove words in a restricted way with
 7900: markers).  Every named (and @code{reveal}ed) word is in one wordlist.
 7901: 
 7902: @cindex search order stack
 7903: The text interpreter searches the wordlists present in the search order
 7904: (a stack of wordlists), from the top to the bottom.  Within each
 7905: wordlist, the search starts conceptually at the newest word; i.e., if
 7906: two words in a wordlist have the same name, the newer word is found.
 7907: 
 7908: @cindex compilation word list
 7909: New words are added to the @dfn{compilation wordlist} (aka current
 7910: wordlist).
 7911: 
 7912: @cindex wid
 7913: A word list is identified by a cell-sized word list identifier (@i{wid})
 7914: in much the same way as a file is identified by a file handle. The
 7915: numerical value of the wid has no (portable) meaning, and might change
 7916: from session to session.
 7917: 
 7918: The ANS Forth ``Search order'' word set is intended to provide a set of
 7919: low-level tools that allow various different schemes to be
 7920: implemented. Gforth also provides @code{vocabulary}, a traditional Forth
 7921: word.  @file{compat/vocabulary.fs} provides an implementation in ANS
 7922: Forth.
 7923: 
 7924: @comment TODO: locals section refers to here, saying that every word list (aka
 7925: @comment vocabulary) has its own methods for searching etc. Need to document that.
 7926: @c anton: but better in a separate subsection on wordlist internals
 7927: 
 7928: @comment TODO: document markers, reveal, tables, mappedwordlist
 7929: 
 7930: @comment the gforthman- prefix is used to pick out the true definition of a
 7931: @comment word from the source files, rather than some alias.
 7932: 
 7933: doc-forth-wordlist
 7934: doc-definitions
 7935: doc-get-current
 7936: doc-set-current
 7937: doc-get-order
 7938: doc---gforthman-set-order
 7939: doc-wordlist
 7940: doc-table
 7941: doc->order
 7942: doc-previous
 7943: doc-also
 7944: doc---gforthman-forth
 7945: doc-only
 7946: doc---gforthman-order
 7947: 
 7948: doc-find
 7949: doc-search-wordlist
 7950: 
 7951: doc-words
 7952: doc-vlist
 7953: @c doc-words-deferred
 7954: 
 7955: @c doc-mappedwordlist @c map-structure undefined, implemantation-specific
 7956: doc-root
 7957: doc-vocabulary
 7958: doc-seal
 7959: doc-vocs
 7960: doc-current
 7961: doc-context
 7962: 
 7963: 
 7964: @menu
 7965: * Vocabularies::                
 7966: * Why use word lists?::         
 7967: * Word list example::           
 7968: @end menu
 7969: 
 7970: @node Vocabularies, Why use word lists?, Word Lists, Word Lists
 7971: @subsection Vocabularies
 7972: @cindex Vocabularies, detailed explanation
 7973: 
 7974: Here is an example of creating and using a new wordlist using ANS
 7975: Forth words:
 7976: 
 7977: @example
 7978: wordlist constant my-new-words-wordlist
 7979: : my-new-words get-order nip my-new-words-wordlist swap set-order ;
 7980: 
 7981: \ add it to the search order
 7982: also my-new-words
 7983: 
 7984: \ alternatively, add it to the search order and make it
 7985: \ the compilation word list
 7986: also my-new-words definitions
 7987: \ type "order" to see the problem
 7988: @end example
 7989: 
 7990: The problem with this example is that @code{order} has no way to
 7991: associate the name @code{my-new-words} with the wid of the word list (in
 7992: Gforth, @code{order} and @code{vocs} will display @code{???}  for a wid
 7993: that has no associated name). There is no Standard way of associating a
 7994: name with a wid.
 7995: 
 7996: In Gforth, this example can be re-coded using @code{vocabulary}, which
 7997: associates a name with a wid:
 7998: 
 7999: @example
 8000: vocabulary my-new-words
 8001: 
 8002: \ add it to the search order
 8003: also my-new-words
 8004: 
 8005: \ alternatively, add it to the search order and make it
 8006: \ the compilation word list
 8007: my-new-words definitions
 8008: \ type "order" to see that the problem is solved
 8009: @end example
 8010: 
 8011: 
 8012: @node Why use word lists?, Word list example, Vocabularies, Word Lists
 8013: @subsection Why use word lists?
 8014: @cindex word lists - why use them?
 8015: 
 8016: Here are some reasons why people use wordlists:
 8017: 
 8018: @itemize @bullet
 8019: 
 8020: @c anton: Gforth's hashing implementation makes the search speed
 8021: @c independent from the number of words.  But it is linear with the number
 8022: @c of wordlists that have to be searched, so in effect using more wordlists
 8023: @c actually slows down compilation.
 8024: 
 8025: @c @item
 8026: @c To improve compilation speed by reducing the number of header space
 8027: @c entries that must be searched. This is achieved by creating a new
 8028: @c word list that contains all of the definitions that are used in the
 8029: @c definition of a Forth system but which would not usually be used by
 8030: @c programs running on that system. That word list would be on the search
 8031: @c list when the Forth system was compiled but would be removed from the
 8032: @c search list for normal operation. This can be a useful technique for
 8033: @c low-performance systems (for example, 8-bit processors in embedded
 8034: @c systems) but is unlikely to be necessary in high-performance desktop
 8035: @c systems.
 8036: 
 8037: @item
 8038: To prevent a set of words from being used outside the context in which
 8039: they are valid. Two classic examples of this are an integrated editor
 8040: (all of the edit commands are defined in a separate word list; the
 8041: search order is set to the editor word list when the editor is invoked;
 8042: the old search order is restored when the editor is terminated) and an
 8043: integrated assembler (the op-codes for the machine are defined in a
 8044: separate word list which is used when a @code{CODE} word is defined).
 8045: 
 8046: @item
 8047: To organize the words of an application or library into a user-visible
 8048: set (in @code{forth-wordlist} or some other common wordlist) and a set
 8049: of helper words used just for the implementation (hidden in a separate
 8050: wordlist).  This keeps @code{words}' output smaller, separates
 8051: implementation and interface, and reduces the chance of name conflicts
 8052: within the common wordlist.
 8053: 
 8054: @item
 8055: To prevent a name-space clash between multiple definitions with the same
 8056: name. For example, when building a cross-compiler you might have a word
 8057: @code{IF} that generates conditional code for your target system. By
 8058: placing this definition in a different word list you can control whether
 8059: the host system's @code{IF} or the target system's @code{IF} get used in
 8060: any particular context by controlling the order of the word lists on the
 8061: search order stack.
 8062: 
 8063: @end itemize
 8064: 
 8065: The downsides of using wordlists are:
 8066: 
 8067: @itemize
 8068: 
 8069: @item
 8070: Debugging becomes more cumbersome.
 8071: 
 8072: @item
 8073: Name conflicts worked around with wordlists are still there, and you
 8074: have to arrange the search order carefully to get the desired results;
 8075: if you forget to do that, you get hard-to-find errors (as in any case
 8076: where you read the code differently from the compiler; @code{see} can
 8077: help seeing which of several possible words the name resolves to in such
 8078: cases).  @code{See} displays just the name of the words, not what
 8079: wordlist they belong to, so it might be misleading.  Using unique names
 8080: is a better approach to avoid name conflicts.
 8081: 
 8082: @item
 8083: You have to explicitly undo any changes to the search order.  In many
 8084: cases it would be more convenient if this happened implicitly.  Gforth
 8085: currently does not provide such a feature, but it may do so in the
 8086: future.
 8087: @end itemize
 8088: 
 8089: 
 8090: @node Word list example,  , Why use word lists?, Word Lists
 8091: @subsection Word list example
 8092: @cindex word lists - example
 8093: 
 8094: The following example is from the
 8095: @uref{http://www.complang.tuwien.ac.at/forth/garbage-collection.zip,
 8096: garbage collector} and uses wordlists to separate public words from
 8097: helper words:
 8098: 
 8099: @example
 8100: get-current ( wid )
 8101: vocabulary garbage-collector also garbage-collector definitions
 8102: ... \ define helper words
 8103: ( wid ) set-current \ restore original (i.e., public) compilation wordlist
 8104: ... \ define the public (i.e., API) words
 8105:     \ they can refer to the helper words
 8106: previous \ restore original search order (helper words become invisible)
 8107: @end example
 8108: 
 8109: @c -------------------------------------------------------------
 8110: @node Environmental Queries, Files, Word Lists, Words
 8111: @section Environmental Queries
 8112: @cindex environmental queries
 8113: 
 8114: ANS Forth introduced the idea of ``environmental queries'' as a way
 8115: for a program running on a system to determine certain characteristics of the system.
 8116: The Standard specifies a number of strings that might be recognised by a system.
 8117: 
 8118: The Standard requires that the header space used for environmental queries
 8119: be distinct from the header space used for definitions.
 8120: 
 8121: Typically, environmental queries are supported by creating a set of
 8122: definitions in a word list that is @i{only} used during environmental
 8123: queries; that is what Gforth does. There is no Standard way of adding
 8124: definitions to the set of recognised environmental queries, but any
 8125: implementation that supports the loading of optional word sets must have
 8126: some mechanism for doing this (after loading the word set, the
 8127: associated environmental query string must return @code{true}). In
 8128: Gforth, the word list used to honour environmental queries can be
 8129: manipulated just like any other word list.
 8130: 
 8131: 
 8132: doc-environment?
 8133: doc-environment-wordlist
 8134: 
 8135: doc-gforth
 8136: doc-os-class
 8137: 
 8138: 
 8139: Note that, whilst the documentation for (e.g.) @code{gforth} shows it
 8140: returning two items on the stack, querying it using @code{environment?}
 8141: will return an additional item; the @code{true} flag that shows that the
 8142: string was recognised.
 8143: 
 8144: @comment TODO Document the standard strings or note where they are documented herein
 8145: 
 8146: Here are some examples of using environmental queries:
 8147: 
 8148: @example
 8149: s" address-unit-bits" environment? 0=
 8150: [IF]
 8151:      cr .( environmental attribute address-units-bits unknown... ) cr
 8152: [ELSE]
 8153:      drop \ ensure balanced stack effect
 8154: [THEN]
 8155: 
 8156: \ this might occur in the prelude of a standard program that uses THROW
 8157: s" exception" environment? [IF]
 8158:    0= [IF]
 8159:       : throw abort" exception thrown" ;
 8160:    [THEN]
 8161: [ELSE] \ we don't know, so make sure
 8162:    : throw abort" exception thrown" ;
 8163: [THEN]
 8164: 
 8165: s" gforth" environment? [IF] .( Gforth version ) TYPE
 8166:                         [ELSE] .( Not Gforth..) [THEN]
 8167: 
 8168: \ a program using v*
 8169: s" gforth" environment? [IF]
 8170:   s" 0.5.0" compare 0< [IF] \ v* is a primitive since 0.5.0
 8171:    : v* ( f_addr1 nstride1 f_addr2 nstride2 ucount -- r )
 8172:      >r swap 2swap swap 0e r> 0 ?DO
 8173:        dup f@ over + 2swap dup f@ f* f+ over + 2swap
 8174:      LOOP
 8175:      2drop 2drop ; 
 8176:   [THEN]
 8177: [ELSE] \ 
 8178:   : v* ( f_addr1 nstride1 f_addr2 nstride2 ucount -- r )
 8179:   ...
 8180: [THEN]
 8181: @end example
 8182: 
 8183: Here is an example of adding a definition to the environment word list:
 8184: 
 8185: @example
 8186: get-current environment-wordlist set-current
 8187: true constant block
 8188: true constant block-ext
 8189: set-current
 8190: @end example
 8191: 
 8192: You can see what definitions are in the environment word list like this:
 8193: 
 8194: @example
 8195: environment-wordlist >order words previous
 8196: @end example
 8197: 
 8198: 
 8199: @c -------------------------------------------------------------
 8200: @node Files, Blocks, Environmental Queries, Words
 8201: @section Files
 8202: @cindex files
 8203: @cindex I/O - file-handling
 8204: 
 8205: Gforth provides facilities for accessing files that are stored in the
 8206: host operating system's file-system. Files that are processed by Gforth
 8207: can be divided into two categories:
 8208: 
 8209: @itemize @bullet
 8210: @item
 8211: Files that are processed by the Text Interpreter (@dfn{Forth source files}).
 8212: @item
 8213: Files that are processed by some other program (@dfn{general files}).
 8214: @end itemize
 8215: 
 8216: @menu
 8217: * Forth source files::          
 8218: * General files::               
 8219: * Redirection::                 
 8220: * Search Paths::                
 8221: @end menu
 8222: 
 8223: @c -------------------------------------------------------------
 8224: @node Forth source files, General files, Files, Files
 8225: @subsection Forth source files
 8226: @cindex including files
 8227: @cindex Forth source files
 8228: 
 8229: The simplest way to interpret the contents of a file is to use one of
 8230: these two formats:
 8231: 
 8232: @example
 8233: include mysource.fs
 8234: s" mysource.fs" included
 8235: @end example
 8236: 
 8237: You usually want to include a file only if it is not included already
 8238: (by, say, another source file). In that case, you can use one of these
 8239: three formats:
 8240: 
 8241: @example
 8242: require mysource.fs
 8243: needs mysource.fs
 8244: s" mysource.fs" required
 8245: @end example
 8246: 
 8247: @cindex stack effect of included files
 8248: @cindex including files, stack effect
 8249: It is good practice to write your source files such that interpreting them
 8250: does not change the stack. Source files designed in this way can be used with
 8251: @code{required} and friends without complications. For example:
 8252: 
 8253: @example
 8254: 1024 require foo.fs drop
 8255: @end example
 8256: 
 8257: Here you want to pass the argument 1024 (e.g., a buffer size) to
 8258: @file{foo.fs}.  Interpreting @file{foo.fs} has the stack effect ( n -- n
 8259: ), which allows its use with @code{require}.  Of course with such
 8260: parameters to required files, you have to ensure that the first
 8261: @code{require} fits for all uses (i.e., @code{require} it early in the
 8262: master load file).
 8263: 
 8264: doc-include-file
 8265: doc-included
 8266: doc-included?
 8267: doc-include
 8268: doc-required
 8269: doc-require
 8270: doc-needs
 8271: @c doc-init-included-files @c internal
 8272: doc-sourcefilename
 8273: doc-sourceline#
 8274: 
 8275: A definition in ANS Forth for @code{required} is provided in
 8276: @file{compat/required.fs}.
 8277: 
 8278: @c -------------------------------------------------------------
 8279: @node General files, Redirection, Forth source files, Files
 8280: @subsection General files
 8281: @cindex general files
 8282: @cindex file-handling
 8283: 
 8284: Files are opened/created by name and type. The following file access
 8285: methods (FAMs) are recognised:
 8286: 
 8287: @cindex fam (file access method)
 8288: doc-r/o
 8289: doc-r/w
 8290: doc-w/o
 8291: doc-bin
 8292: 
 8293: 
 8294: When a file is opened/created, it returns a file identifier,
 8295: @i{wfileid} that is used for all other file commands. All file
 8296: commands also return a status value, @i{wior}, that is 0 for a
 8297: successful operation and an implementation-defined non-zero value in the
 8298: case of an error.
 8299: 
 8300: 
 8301: doc-open-file
 8302: doc-create-file
 8303: 
 8304: doc-close-file
 8305: doc-delete-file
 8306: doc-rename-file
 8307: doc-read-file
 8308: doc-read-line
 8309: doc-key-file
 8310: doc-key?-file
 8311: doc-write-file
 8312: doc-write-line
 8313: doc-emit-file
 8314: doc-flush-file
 8315: 
 8316: doc-file-status
 8317: doc-file-position
 8318: doc-reposition-file
 8319: doc-file-size
 8320: doc-resize-file
 8321: 
 8322: doc-slurp-file
 8323: doc-slurp-fid
 8324: doc-stdin
 8325: doc-stdout
 8326: doc-stderr
 8327: 
 8328: @c ---------------------------------------------------------
 8329: @node Redirection, Search Paths, General files, Files
 8330: @subsection Redirection
 8331: @cindex Redirection
 8332: @cindex Input Redirection
 8333: @cindex Output Redirection
 8334: 
 8335: You can redirect the output of @code{type} and @code{emit} and all the
 8336: words that use them (all output words that don't have an explicit
 8337: target file) to an arbitrary file with the @code{>outfile
 8338: ... outfile<} construct, used like this:
 8339: 
 8340: @example
 8341: : print-some-warning ( n -- )
 8342:   stderr >outfile cr ." warning# " . outfile< ;
 8343: @end example
 8344: 
 8345: After the @code{outfile<}, the original output direction is restored;
 8346: this construct is nestable and safe against exceptions.  Similarly,
 8347: there is a construct @code{>infile ... infile<} for redirecting the
 8348: input of @code{key} and its users (any input word that does not take a
 8349: file explicitly).
 8350: 
 8351: If you do not want to redirect the input or output to a file, you can
 8352: also make use of the fact that @code{key}, @code{emit} and @code{type}
 8353: are deferred words (@pxref{Deferred Words}).  However, in that case
 8354: you have to worry about the restoration and the protection against
 8355: exceptions yourself; also, note that for redirecting the output in
 8356: this way, you have to redirect both @code{emit} and @code{type}.
 8357: 
 8358: doc->outfile
 8359: doc-outfile<
 8360: doc->infile
 8361: doc-infile<
 8362: 
 8363: @c ---------------------------------------------------------
 8364: @node Search Paths,  , Redirection, Files
 8365: @subsection Search Paths
 8366: @cindex path for @code{included}
 8367: @cindex file search path
 8368: @cindex @code{include} search path
 8369: @cindex search path for files
 8370: 
 8371: If you specify an absolute filename (i.e., a filename starting with
 8372: @file{/} or @file{~}, or with @file{:} in the second position (as in
 8373: @samp{C:...})) for @code{included} and friends, that file is included
 8374: just as you would expect.
 8375: 
 8376: If the filename starts with @file{./}, this refers to the directory that
 8377: the present file was @code{included} from.  This allows files to include
 8378: other files relative to their own position (irrespective of the current
 8379: working directory or the absolute position).  This feature is essential
 8380: for libraries consisting of several files, where a file may include
 8381: other files from the library.  It corresponds to @code{#include "..."}
 8382: in C. If the current input source is not a file, @file{.} refers to the
 8383: directory of the innermost file being included, or, if there is no file
 8384: being included, to the current working directory.
 8385: 
 8386: For relative filenames (not starting with @file{./}), Gforth uses a
 8387: search path similar to Forth's search order (@pxref{Word Lists}). It
 8388: tries to find the given filename in the directories present in the path,
 8389: and includes the first one it finds. There are separate search paths for
 8390: Forth source files and general files.  If the search path contains the
 8391: directory @file{.}, this refers to the directory of the current file, or
 8392: the working directory, as if the file had been specified with @file{./}.
 8393: 
 8394: Use @file{~+} to refer to the current working directory (as in the
 8395: @code{bash}).
 8396: 
 8397: @c anton: fold the following subsubsections into this subsection?
 8398: 
 8399: @menu
 8400: * Source Search Paths::         
 8401: * General Search Paths::        
 8402: @end menu
 8403: 
 8404: @c ---------------------------------------------------------
 8405: @node Source Search Paths, General Search Paths, Search Paths, Search Paths
 8406: @subsubsection Source Search Paths
 8407: @cindex search path control, source files
 8408: 
 8409: The search path is initialized when you start Gforth (@pxref{Invoking
 8410: Gforth}). You can display it and change it using @code{fpath} in
 8411: combination with the general path handling words.
 8412: 
 8413: doc-fpath
 8414: @c the functionality of the following words is easily available through
 8415: @c   fpath and the general path words.  The may go away.
 8416: @c doc-.fpath
 8417: @c doc-fpath+
 8418: @c doc-fpath=
 8419: @c doc-open-fpath-file
 8420: 
 8421: @noindent
 8422: Here is an example of using @code{fpath} and @code{require}:
 8423: 
 8424: @example
 8425: fpath path= /usr/lib/forth/|./
 8426: require timer.fs
 8427: @end example
 8428: 
 8429: 
 8430: @c ---------------------------------------------------------
 8431: @node General Search Paths,  , Source Search Paths, Search Paths
 8432: @subsubsection General Search Paths
 8433: @cindex search path control, source files
 8434: 
 8435: Your application may need to search files in several directories, like
 8436: @code{included} does. To facilitate this, Gforth allows you to define
 8437: and use your own search paths, by providing generic equivalents of the
 8438: Forth search path words:
 8439: 
 8440: doc-open-path-file
 8441: doc-path-allot
 8442: doc-clear-path
 8443: doc-also-path
 8444: doc-.path
 8445: doc-path+
 8446: doc-path=
 8447: 
 8448: @c anton: better define a word for it, say "path-allot ( ucount -- path-addr )
 8449: 
 8450: Here's an example of creating an empty search path:
 8451: @c
 8452: @example
 8453: create mypath 500 path-allot \ maximum length 500 chars (is checked)
 8454: @end example
 8455: 
 8456: @c -------------------------------------------------------------
 8457: @node Blocks, Other I/O, Files, Words
 8458: @section Blocks
 8459: @cindex I/O - blocks
 8460: @cindex blocks
 8461: 
 8462: When you run Gforth on a modern desk-top computer, it runs under the
 8463: control of an operating system which provides certain services.  One of
 8464: these services is @var{file services}, which allows Forth source code
 8465: and data to be stored in files and read into Gforth (@pxref{Files}).
 8466: 
 8467: Traditionally, Forth has been an important programming language on
 8468: systems where it has interfaced directly to the underlying hardware with
 8469: no intervening operating system. Forth provides a mechanism, called
 8470: @dfn{blocks}, for accessing mass storage on such systems.
 8471: 
 8472: A block is a 1024-byte data area, which can be used to hold data or
 8473: Forth source code. No structure is imposed on the contents of the
 8474: block. A block is identified by its number; blocks are numbered
 8475: contiguously from 1 to an implementation-defined maximum.
 8476: 
 8477: A typical system that used blocks but no operating system might use a
 8478: single floppy-disk drive for mass storage, with the disks formatted to
 8479: provide 256-byte sectors. Blocks would be implemented by assigning the
 8480: first four sectors of the disk to block 1, the second four sectors to
 8481: block 2 and so on, up to the limit of the capacity of the disk. The disk
 8482: would not contain any file system information, just the set of blocks.
 8483: 
 8484: @cindex blocks file
 8485: On systems that do provide file services, blocks are typically
 8486: implemented by storing a sequence of blocks within a single @dfn{blocks
 8487: file}.  The size of the blocks file will be an exact multiple of 1024
 8488: bytes, corresponding to the number of blocks it contains. This is the
 8489: mechanism that Gforth uses.
 8490: 
 8491: @cindex @file{blocks.fb}
 8492: Only one blocks file can be open at a time. If you use block words without
 8493: having specified a blocks file, Gforth defaults to the blocks file
 8494: @file{blocks.fb}. Gforth uses the Forth search path when attempting to
 8495: locate a blocks file (@pxref{Source Search Paths}).
 8496: 
 8497: @cindex block buffers
 8498: When you read and write blocks under program control, Gforth uses a
 8499: number of @dfn{block buffers} as intermediate storage. These buffers are
 8500: not used when you use @code{load} to interpret the contents of a block.
 8501: 
 8502: The behaviour of the block buffers is analagous to that of a cache.
 8503: Each block buffer has three states:
 8504: 
 8505: @itemize @bullet
 8506: @item
 8507: Unassigned
 8508: @item
 8509: Assigned-clean
 8510: @item
 8511: Assigned-dirty
 8512: @end itemize
 8513: 
 8514: Initially, all block buffers are @i{unassigned}. In order to access a
 8515: block, the block (specified by its block number) must be assigned to a
 8516: block buffer.
 8517: 
 8518: The assignment of a block to a block buffer is performed by @code{block}
 8519: or @code{buffer}. Use @code{block} when you wish to modify the existing
 8520: contents of a block. Use @code{buffer} when you don't care about the
 8521: existing contents of the block@footnote{The ANS Forth definition of
 8522: @code{buffer} is intended not to cause disk I/O; if the data associated
 8523: with the particular block is already stored in a block buffer due to an
 8524: earlier @code{block} command, @code{buffer} will return that block
 8525: buffer and the existing contents of the block will be
 8526: available. Otherwise, @code{buffer} will simply assign a new, empty
 8527: block buffer for the block.}.
 8528: 
 8529: Once a block has been assigned to a block buffer using @code{block} or
 8530: @code{buffer}, that block buffer becomes the @i{current block
 8531: buffer}. Data may only be manipulated (read or written) within the
 8532: current block buffer.
 8533: 
 8534: When the contents of the current block buffer has been modified it is
 8535: necessary, @emph{before calling @code{block} or @code{buffer} again}, to
 8536: either abandon the changes (by doing nothing) or mark the block as
 8537: changed (assigned-dirty), using @code{update}. Using @code{update} does
 8538: not change the blocks file; it simply changes a block buffer's state to
 8539: @i{assigned-dirty}.  The block will be written implicitly when it's
 8540: buffer is needed for another block, or explicitly by @code{flush} or
 8541: @code{save-buffers}.
 8542: 
 8543: word @code{Flush} writes all @i{assigned-dirty} blocks back to the
 8544: blocks file on disk. Leaving Gforth with @code{bye} also performs a
 8545: @code{flush}.
 8546: 
 8547: In Gforth, @code{block} and @code{buffer} use a @i{direct-mapped}
 8548: algorithm to assign a block buffer to a block. That means that any
 8549: particular block can only be assigned to one specific block buffer,
 8550: called (for the particular operation) the @i{victim buffer}. If the
 8551: victim buffer is @i{unassigned} or @i{assigned-clean} it is allocated to
 8552: the new block immediately. If it is @i{assigned-dirty} its current
 8553: contents are written back to the blocks file on disk before it is
 8554: allocated to the new block.
 8555: 
 8556: Although no structure is imposed on the contents of a block, it is
 8557: traditional to display the contents as 16 lines each of 64 characters.  A
 8558: block provides a single, continuous stream of input (for example, it
 8559: acts as a single parse area) -- there are no end-of-line characters
 8560: within a block, and no end-of-file character at the end of a
 8561: block. There are two consequences of this:
 8562: 
 8563: @itemize @bullet
 8564: @item
 8565: The last character of one line wraps straight into the first character
 8566: of the following line
 8567: @item
 8568: The word @code{\} -- comment to end of line -- requires special
 8569: treatment; in the context of a block it causes all characters until the
 8570: end of the current 64-character ``line'' to be ignored.
 8571: @end itemize
 8572: 
 8573: In Gforth, when you use @code{block} with a non-existent block number,
 8574: the current blocks file will be extended to the appropriate size and the
 8575: block buffer will be initialised with spaces.
 8576: 
 8577: Gforth includes a simple block editor (type @code{use blocked.fb 0 list}
 8578: for details) but doesn't encourage the use of blocks; the mechanism is
 8579: only provided for backward compatibility -- ANS Forth requires blocks to
 8580: be available when files are.
 8581: 
 8582: Common techniques that are used when working with blocks include:
 8583: 
 8584: @itemize @bullet
 8585: @item
 8586: A screen editor that allows you to edit blocks without leaving the Forth
 8587: environment.
 8588: @item
 8589: Shadow screens; where every code block has an associated block
 8590: containing comments (for example: code in odd block numbers, comments in
 8591: even block numbers). Typically, the block editor provides a convenient
 8592: mechanism to toggle between code and comments.
 8593: @item
 8594: Load blocks; a single block (typically block 1) contains a number of
 8595: @code{thru} commands which @code{load} the whole of the application.
 8596: @end itemize
 8597: 
 8598: See Frank Sergeant's Pygmy Forth to see just how well blocks can be
 8599: integrated into a Forth programming environment.
 8600: 
 8601: @comment TODO what about errors on open-blocks?
 8602: 
 8603: doc-open-blocks
 8604: doc-use
 8605: doc-block-offset
 8606: doc-get-block-fid
 8607: doc-block-position
 8608: 
 8609: doc-list
 8610: doc-scr
 8611: 
 8612: doc---gforthman-block
 8613: doc-buffer
 8614: 
 8615: doc-empty-buffers
 8616: doc-empty-buffer
 8617: doc-update
 8618: doc-updated?
 8619: doc-save-buffers
 8620: doc-save-buffer
 8621: doc-flush
 8622: 
 8623: doc-load
 8624: doc-thru
 8625: doc-+load
 8626: doc-+thru
 8627: doc---gforthman--->
 8628: doc-block-included
 8629: 
 8630: 
 8631: @c -------------------------------------------------------------
 8632: @node Other I/O, OS command line arguments, Blocks, Words
 8633: @section Other I/O
 8634: @cindex I/O - keyboard and display
 8635: 
 8636: @menu
 8637: * Simple numeric output::       Predefined formats
 8638: * Formatted numeric output::    Formatted (pictured) output
 8639: * String Formats::              How Forth stores strings in memory
 8640: * Displaying characters and strings::  Other stuff
 8641: * Input::                       Input
 8642: * Pipes::                       How to create your own pipes
 8643: * Xchars and Unicode::          Non-ASCII characters
 8644: @end menu
 8645: 
 8646: @node Simple numeric output, Formatted numeric output, Other I/O, Other I/O
 8647: @subsection Simple numeric output
 8648: @cindex numeric output - simple/free-format
 8649: 
 8650: The simplest output functions are those that display numbers from the
 8651: data or floating-point stacks. Floating-point output is always displayed
 8652: using base 10. Numbers displayed from the data stack use the value stored
 8653: in @code{base}.
 8654: 
 8655: 
 8656: doc-.
 8657: doc-dec.
 8658: doc-hex.
 8659: doc-u.
 8660: doc-.r
 8661: doc-u.r
 8662: doc-d.
 8663: doc-ud.
 8664: doc-d.r
 8665: doc-ud.r
 8666: doc-f.
 8667: doc-fe.
 8668: doc-fs.
 8669: doc-f.rdp
 8670: 
 8671: Examples of printing the number 1234.5678E23 in the different floating-point output
 8672: formats are shown below:
 8673: 
 8674: @example
 8675: f. 123456779999999000000000000.
 8676: fe. 123.456779999999E24
 8677: fs. 1.23456779999999E26
 8678: @end example
 8679: 
 8680: 
 8681: @node Formatted numeric output, String Formats, Simple numeric output, Other I/O
 8682: @subsection Formatted numeric output
 8683: @cindex formatted numeric output
 8684: @cindex pictured numeric output
 8685: @cindex numeric output - formatted
 8686: 
 8687: Forth traditionally uses a technique called @dfn{pictured numeric
 8688: output} for formatted printing of integers.  In this technique, digits
 8689: are extracted from the number (using the current output radix defined by
 8690: @code{base}), converted to ASCII codes and appended to a string that is
 8691: built in a scratch-pad area of memory (@pxref{core-idef,
 8692: Implementation-defined options, Implementation-defined
 8693: options}). Arbitrary characters can be appended to the string during the
 8694: extraction process. The completed string is specified by an address
 8695: and length and can be manipulated (@code{TYPE}ed, copied, modified)
 8696: under program control.
 8697: 
 8698: All of the integer output words described in the previous section
 8699: (@pxref{Simple numeric output}) are implemented in Gforth using pictured
 8700: numeric output.
 8701: 
 8702: Three important things to remember about pictured numeric output:
 8703: 
 8704: @itemize @bullet
 8705: @item
 8706: It always operates on double-precision numbers; to display a
 8707: single-precision number, convert it first (for ways of doing this
 8708: @pxref{Double precision}).
 8709: @item
 8710: It always treats the double-precision number as though it were
 8711: unsigned. The examples below show ways of printing signed numbers.
 8712: @item
 8713: The string is built up from right to left; least significant digit first.
 8714: @end itemize
 8715: 
 8716: 
 8717: doc-<#
 8718: doc-<<#
 8719: doc-#
 8720: doc-#s
 8721: doc-hold
 8722: doc-sign
 8723: doc-#>
 8724: doc-#>>
 8725: 
 8726: doc-represent
 8727: doc-f>str-rdp
 8728: doc-f>buf-rdp
 8729: 
 8730: 
 8731: @noindent
 8732: Here are some examples of using pictured numeric output:
 8733: 
 8734: @example
 8735: : my-u. ( u -- )
 8736:   \ Simplest use of pns.. behaves like Standard u. 
 8737:   0              \ convert to unsigned double
 8738:   <<#            \ start conversion
 8739:   #s             \ convert all digits
 8740:   #>             \ complete conversion
 8741:   TYPE SPACE     \ display, with trailing space
 8742:   #>> ;          \ release hold area
 8743: 
 8744: : cents-only ( u -- )
 8745:   0              \ convert to unsigned double
 8746:   <<#            \ start conversion
 8747:   # #            \ convert two least-significant digits
 8748:   #>             \ complete conversion, discard other digits
 8749:   TYPE SPACE     \ display, with trailing space
 8750:   #>> ;          \ release hold area
 8751: 
 8752: : dollars-and-cents ( u -- )
 8753:   0              \ convert to unsigned double
 8754:   <<#            \ start conversion
 8755:   # #            \ convert two least-significant digits
 8756:   [char] . hold  \ insert decimal point
 8757:   #s             \ convert remaining digits
 8758:   [char] $ hold  \ append currency symbol
 8759:   #>             \ complete conversion
 8760:   TYPE SPACE     \ display, with trailing space
 8761:   #>> ;          \ release hold area
 8762: 
 8763: : my-. ( n -- )
 8764:   \ handling negatives.. behaves like Standard .
 8765:   s>d            \ convert to signed double
 8766:   swap over dabs \ leave sign byte followed by unsigned double
 8767:   <<#            \ start conversion
 8768:   #s             \ convert all digits
 8769:   rot sign       \ get at sign byte, append "-" if needed
 8770:   #>             \ complete conversion
 8771:   TYPE SPACE     \ display, with trailing space
 8772:   #>> ;          \ release hold area
 8773: 
 8774: : account. ( n -- )
 8775:   \ accountants don't like minus signs, they use parentheses
 8776:   \ for negative numbers
 8777:   s>d            \ convert to signed double
 8778:   swap over dabs \ leave sign byte followed by unsigned double
 8779:   <<#            \ start conversion
 8780:   2 pick         \ get copy of sign byte
 8781:   0< IF [char] ) hold THEN \ right-most character of output
 8782:   #s             \ convert all digits
 8783:   rot            \ get at sign byte
 8784:   0< IF [char] ( hold THEN
 8785:   #>             \ complete conversion
 8786:   TYPE SPACE     \ display, with trailing space
 8787:   #>> ;          \ release hold area
 8788: 
 8789: @end example
 8790: 
 8791: Here are some examples of using these words:
 8792: 
 8793: @example
 8794: 1 my-u. 1
 8795: hex -1 my-u. decimal FFFFFFFF
 8796: 1 cents-only 01
 8797: 1234 cents-only 34
 8798: 2 dollars-and-cents $0.02
 8799: 1234 dollars-and-cents $12.34
 8800: 123 my-. 123
 8801: -123 my. -123
 8802: 123 account. 123
 8803: -456 account. (456)
 8804: @end example
 8805: 
 8806: 
 8807: @node String Formats, Displaying characters and strings, Formatted numeric output, Other I/O
 8808: @subsection String Formats
 8809: @cindex strings - see character strings
 8810: @cindex character strings - formats
 8811: @cindex I/O - see character strings
 8812: @cindex counted strings
 8813: 
 8814: @c anton: this does not really belong here; maybe the memory section,
 8815: @c  or the principles chapter
 8816: 
 8817: Forth commonly uses two different methods for representing character
 8818: strings:
 8819: 
 8820: @itemize @bullet
 8821: @item
 8822: @cindex address of counted string
 8823: @cindex counted string
 8824: As a @dfn{counted string}, represented by a @i{c-addr}. The char
 8825: addressed by @i{c-addr} contains a character-count, @i{n}, of the
 8826: string and the string occupies the subsequent @i{n} char addresses in
 8827: memory.
 8828: @item
 8829: As cell pair on the stack; @i{c-addr u}, where @i{u} is the length
 8830: of the string in characters, and @i{c-addr} is the address of the
 8831: first byte of the string.
 8832: @end itemize
 8833: 
 8834: ANS Forth encourages the use of the second format when representing
 8835: strings.
 8836: 
 8837: 
 8838: doc-count
 8839: 
 8840: 
 8841: For words that move, copy and search for strings see @ref{Memory
 8842: Blocks}. For words that display characters and strings see
 8843: @ref{Displaying characters and strings}.
 8844: 
 8845: @node Displaying characters and strings, Input, String Formats, Other I/O
 8846: @subsection Displaying characters and strings
 8847: @cindex characters - compiling and displaying
 8848: @cindex character strings - compiling and displaying
 8849: 
 8850: This section starts with a glossary of Forth words and ends with a set
 8851: of examples.
 8852: 
 8853: 
 8854: doc-bl
 8855: doc-space
 8856: doc-spaces
 8857: doc-emit
 8858: doc-toupper
 8859: doc-."
 8860: doc-.(
 8861: doc-.\"
 8862: doc-type
 8863: doc-typewhite
 8864: doc-cr
 8865: @cindex cursor control
 8866: doc-at-xy
 8867: doc-page
 8868: doc-s"
 8869: doc-s\"
 8870: doc-c"
 8871: doc-char
 8872: doc-[char]
 8873: 
 8874: 
 8875: @noindent
 8876: As an example, consider the following text, stored in a file @file{test.fs}:
 8877: 
 8878: @example
 8879: .( text-1)
 8880: : my-word
 8881:   ." text-2" cr
 8882:   .( text-3)
 8883: ;
 8884: 
 8885: ." text-4"
 8886: 
 8887: : my-char
 8888:   [char] ALPHABET emit
 8889:   char emit
 8890: ;
 8891: @end example
 8892: 
 8893: When you load this code into Gforth, the following output is generated:
 8894: 
 8895: @example
 8896: @kbd{include test.fs @key{RET}} text-1text-3text-4 ok
 8897: @end example
 8898: 
 8899: @itemize @bullet
 8900: @item
 8901: Messages @code{text-1} and @code{text-3} are displayed because @code{.(} 
 8902: is an immediate word; it behaves in the same way whether it is used inside
 8903: or outside a colon definition.
 8904: @item
 8905: Message @code{text-4} is displayed because of Gforth's added interpretation
 8906: semantics for @code{."}.
 8907: @item
 8908: Message @code{text-2} is @i{not} displayed, because the text interpreter
 8909: performs the compilation semantics for @code{."} within the definition of
 8910: @code{my-word}.
 8911: @end itemize
 8912: 
 8913: Here are some examples of executing @code{my-word} and @code{my-char}:
 8914: 
 8915: @example
 8916: @kbd{my-word @key{RET}} text-2
 8917:  ok
 8918: @kbd{my-char fred @key{RET}} Af ok
 8919: @kbd{my-char jim @key{RET}} Aj ok
 8920: @end example
 8921: 
 8922: @itemize @bullet
 8923: @item
 8924: Message @code{text-2} is displayed because of the run-time behaviour of
 8925: @code{."}.
 8926: @item
 8927: @code{[char]} compiles the ``A'' from ``ALPHABET'' and puts its display code
 8928: on the stack at run-time. @code{emit} always displays the character
 8929: when @code{my-char} is executed.
 8930: @item
 8931: @code{char} parses a string at run-time and the second @code{emit} displays
 8932: the first character of the string.
 8933: @item
 8934: If you type @code{see my-char} you can see that @code{[char]} discarded
 8935: the text ``LPHABET'' and only compiled the display code for ``A'' into the
 8936: definition of @code{my-char}.
 8937: @end itemize
 8938: 
 8939: 
 8940: 
 8941: @node Input, Pipes, Displaying characters and strings, Other I/O
 8942: @subsection Input
 8943: @cindex input
 8944: @cindex I/O - see input
 8945: @cindex parsing a string
 8946: 
 8947: For ways of storing character strings in memory see @ref{String Formats}.
 8948: 
 8949: @comment TODO examples for >number >float accept key key? pad parse word refill
 8950: @comment then index them
 8951: 
 8952: 
 8953: doc-key
 8954: doc-key?
 8955: doc-ekey
 8956: doc-ekey>char
 8957: doc-ekey?
 8958: 
 8959: Gforth recognizes various keys available on ANSI terminals (in MS-DOS
 8960: you need the ANSI.SYS driver to get that behaviour).  These are the
 8961: keyboard events produced by various common keys:
 8962: 
 8963: doc-k-left
 8964: doc-k-right
 8965: doc-k-up	
 8966: doc-k-down	
 8967: doc-k-home	
 8968: doc-k-end	
 8969: doc-k-prior
 8970: doc-k-next
 8971: doc-k-insert
 8972: doc-k-delete
 8973: 
 8974: The function keys (aka keypad keys) are:
 8975: 
 8976: doc-k1
 8977: doc-k2
 8978: doc-k3
 8979: doc-k4
 8980: doc-k5
 8981: doc-k6
 8982: doc-k7
 8983: doc-k8
 8984: doc-k9
 8985: doc-k10
 8986: doc-k11
 8987: doc-k12
 8988: 
 8989: Note that K11 and K12 are not as widely available.  The shifted
 8990: function keys are also not very widely available:
 8991: 
 8992: doc-s-k1
 8993: doc-s-k2
 8994: doc-s-k3
 8995: doc-s-k4
 8996: doc-s-k5
 8997: doc-s-k6
 8998: doc-s-k7
 8999: doc-s-k8
 9000: doc-s-k9
 9001: doc-s-k10
 9002: doc-s-k11
 9003: doc-s-k12
 9004: 
 9005: Words for inputting one line from the keyboard:
 9006: 
 9007: doc-accept
 9008: doc-edit-line
 9009: 
 9010: Conversion words:
 9011: 
 9012: doc-s>number?
 9013: doc-s>unumber?
 9014: doc->number
 9015: doc->float
 9016: 
 9017: 
 9018: @comment obsolescent words..
 9019: Obsolescent input and conversion words:
 9020: 
 9021: doc-convert
 9022: doc-expect
 9023: doc-span
 9024: 
 9025: 
 9026: @node Pipes, Xchars and Unicode, Input, Other I/O
 9027: @subsection Pipes
 9028: @cindex pipes, creating your own
 9029: 
 9030: In addition to using Gforth in pipes created by other processes
 9031: (@pxref{Gforth in pipes}), you can create your own pipe with
 9032: @code{open-pipe}, and read from or write to it.
 9033: 
 9034: doc-open-pipe
 9035: doc-close-pipe
 9036: 
 9037: If you write to a pipe, Gforth can throw a @code{broken-pipe-error}; if
 9038: you don't catch this exception, Gforth will catch it and exit, usually
 9039: silently (@pxref{Gforth in pipes}).  Since you probably do not want
 9040: this, you should wrap a @code{catch} or @code{try} block around the code
 9041: from @code{open-pipe} to @code{close-pipe}, so you can deal with the
 9042: problem yourself, and then return to regular processing.
 9043: 
 9044: doc-broken-pipe-error
 9045: 
 9046: @node Xchars and Unicode,  , Pipes, Other I/O
 9047: @subsection Xchars and Unicode
 9048: 
 9049: This chapter needs completion
 9050: 
 9051: @node OS command line arguments, Locals, Other I/O, Words
 9052: @section OS command line arguments
 9053: @cindex OS command line arguments
 9054: @cindex command line arguments, OS
 9055: @cindex arguments, OS command line
 9056: 
 9057: The usual way to pass arguments to Gforth programs on the command line
 9058: is via the @option{-e} option, e.g.
 9059: 
 9060: @example
 9061: gforth -e "123 456" foo.fs -e bye
 9062: @end example
 9063: 
 9064: However, you may want to interpret the command-line arguments directly.
 9065: In that case, you can access the (image-specific) command-line arguments
 9066: through @code{next-arg}:
 9067: 
 9068: doc-next-arg
 9069: 
 9070: Here's an example program @file{echo.fs} for @code{next-arg}:
 9071: 
 9072: @example
 9073: : echo ( -- )
 9074:     begin
 9075: 	next-arg 2dup 0 0 d<> while
 9076: 	    type space
 9077:     repeat
 9078:     2drop ;
 9079: 
 9080: echo cr bye
 9081: @end example
 9082: 
 9083: This can be invoked with
 9084: 
 9085: @example
 9086: gforth echo.fs hello world
 9087: @end example
 9088: 
 9089: and it will print
 9090: 
 9091: @example
 9092: hello world
 9093: @end example
 9094: 
 9095: The next lower level of dealing with the OS command line are the
 9096: following words:
 9097: 
 9098: doc-arg
 9099: doc-shift-args
 9100: 
 9101: Finally, at the lowest level Gforth provides the following words:
 9102: 
 9103: doc-argc
 9104: doc-argv
 9105: 
 9106: @c -------------------------------------------------------------
 9107: @node Locals, Structures, OS command line arguments, Words
 9108: @section Locals
 9109: @cindex locals
 9110: 
 9111: Local variables can make Forth programming more enjoyable and Forth
 9112: programs easier to read. Unfortunately, the locals of ANS Forth are
 9113: laden with restrictions. Therefore, we provide not only the ANS Forth
 9114: locals wordset, but also our own, more powerful locals wordset (we
 9115: implemented the ANS Forth locals wordset through our locals wordset).
 9116: 
 9117: The ideas in this section have also been published in M. Anton Ertl,
 9118: @cite{@uref{http://www.complang.tuwien.ac.at/papers/ertl94l.ps.gz,
 9119: Automatic Scoping of Local Variables}}, EuroForth '94.
 9120: 
 9121: @menu
 9122: * Gforth locals::               
 9123: * ANS Forth locals::            
 9124: @end menu
 9125: 
 9126: @node Gforth locals, ANS Forth locals, Locals, Locals
 9127: @subsection Gforth locals
 9128: @cindex Gforth locals
 9129: @cindex locals, Gforth style
 9130: 
 9131: Locals can be defined with
 9132: 
 9133: @example
 9134: @{ local1 local2 ... -- comment @}
 9135: @end example
 9136: or
 9137: @example
 9138: @{ local1 local2 ... @}
 9139: @end example
 9140: 
 9141: E.g.,
 9142: @example
 9143: : max @{ n1 n2 -- n3 @}
 9144:  n1 n2 > if
 9145:    n1
 9146:  else
 9147:    n2
 9148:  endif ;
 9149: @end example
 9150: 
 9151: The similarity of locals definitions with stack comments is intended. A
 9152: locals definition often replaces the stack comment of a word. The order
 9153: of the locals corresponds to the order in a stack comment and everything
 9154: after the @code{--} is really a comment.
 9155: 
 9156: This similarity has one disadvantage: It is too easy to confuse locals
 9157: declarations with stack comments, causing bugs and making them hard to
 9158: find. However, this problem can be avoided by appropriate coding
 9159: conventions: Do not use both notations in the same program. If you do,
 9160: they should be distinguished using additional means, e.g. by position.
 9161: 
 9162: @cindex types of locals
 9163: @cindex locals types
 9164: The name of the local may be preceded by a type specifier, e.g.,
 9165: @code{F:} for a floating point value:
 9166: 
 9167: @example
 9168: : CX* @{ F: Ar F: Ai F: Br F: Bi -- Cr Ci @}
 9169: \ complex multiplication
 9170:  Ar Br f* Ai Bi f* f-
 9171:  Ar Bi f* Ai Br f* f+ ;
 9172: @end example
 9173: 
 9174: @cindex flavours of locals
 9175: @cindex locals flavours
 9176: @cindex value-flavoured locals
 9177: @cindex variable-flavoured locals
 9178: Gforth currently supports cells (@code{W:}, @code{W^}), doubles
 9179: (@code{D:}, @code{D^}), floats (@code{F:}, @code{F^}) and characters
 9180: (@code{C:}, @code{C^}) in two flavours: a value-flavoured local (defined
 9181: with @code{W:}, @code{D:} etc.) produces its value and can be changed
 9182: with @code{TO}. A variable-flavoured local (defined with @code{W^} etc.)
 9183: produces its address (which becomes invalid when the variable's scope is
 9184: left). E.g., the standard word @code{emit} can be defined in terms of
 9185: @code{type} like this:
 9186: 
 9187: @example
 9188: : emit @{ C^ char* -- @}
 9189:     char* 1 type ;
 9190: @end example
 9191: 
 9192: @cindex default type of locals
 9193: @cindex locals, default type
 9194: A local without type specifier is a @code{W:} local. Both flavours of
 9195: locals are initialized with values from the data or FP stack.
 9196: 
 9197: Currently there is no way to define locals with user-defined data
 9198: structures, but we are working on it.
 9199: 
 9200: Gforth allows defining locals everywhere in a colon definition. This
 9201: poses the following questions:
 9202: 
 9203: @menu
 9204: * Where are locals visible by name?::  
 9205: * How long do locals live?::    
 9206: * Locals programming style::    
 9207: * Locals implementation::       
 9208: @end menu
 9209: 
 9210: @node Where are locals visible by name?, How long do locals live?, Gforth locals, Gforth locals
 9211: @subsubsection Where are locals visible by name?
 9212: @cindex locals visibility
 9213: @cindex visibility of locals
 9214: @cindex scope of locals
 9215: 
 9216: Basically, the answer is that locals are visible where you would expect
 9217: it in block-structured languages, and sometimes a little longer. If you
 9218: want to restrict the scope of a local, enclose its definition in
 9219: @code{SCOPE}...@code{ENDSCOPE}.
 9220: 
 9221: 
 9222: doc-scope
 9223: doc-endscope
 9224: 
 9225: 
 9226: These words behave like control structure words, so you can use them
 9227: with @code{CS-PICK} and @code{CS-ROLL} to restrict the scope in
 9228: arbitrary ways.
 9229: 
 9230: If you want a more exact answer to the visibility question, here's the
 9231: basic principle: A local is visible in all places that can only be
 9232: reached through the definition of the local@footnote{In compiler
 9233: construction terminology, all places dominated by the definition of the
 9234: local.}. In other words, it is not visible in places that can be reached
 9235: without going through the definition of the local. E.g., locals defined
 9236: in @code{IF}...@code{ENDIF} are visible until the @code{ENDIF}, locals
 9237: defined in @code{BEGIN}...@code{UNTIL} are visible after the
 9238: @code{UNTIL} (until, e.g., a subsequent @code{ENDSCOPE}).
 9239: 
 9240: The reasoning behind this solution is: We want to have the locals
 9241: visible as long as it is meaningful. The user can always make the
 9242: visibility shorter by using explicit scoping. In a place that can
 9243: only be reached through the definition of a local, the meaning of a
 9244: local name is clear. In other places it is not: How is the local
 9245: initialized at the control flow path that does not contain the
 9246: definition? Which local is meant, if the same name is defined twice in
 9247: two independent control flow paths?
 9248: 
 9249: This should be enough detail for nearly all users, so you can skip the
 9250: rest of this section. If you really must know all the gory details and
 9251: options, read on.
 9252: 
 9253: In order to implement this rule, the compiler has to know which places
 9254: are unreachable. It knows this automatically after @code{AHEAD},
 9255: @code{AGAIN}, @code{EXIT} and @code{LEAVE}; in other cases (e.g., after
 9256: most @code{THROW}s), you can use the word @code{UNREACHABLE} to tell the
 9257: compiler that the control flow never reaches that place. If
 9258: @code{UNREACHABLE} is not used where it could, the only consequence is
 9259: that the visibility of some locals is more limited than the rule above
 9260: says. If @code{UNREACHABLE} is used where it should not (i.e., if you
 9261: lie to the compiler), buggy code will be produced.
 9262: 
 9263: 
 9264: doc-unreachable
 9265: 
 9266: 
 9267: Another problem with this rule is that at @code{BEGIN}, the compiler
 9268: does not know which locals will be visible on the incoming
 9269: back-edge. All problems discussed in the following are due to this
 9270: ignorance of the compiler (we discuss the problems using @code{BEGIN}
 9271: loops as examples; the discussion also applies to @code{?DO} and other
 9272: loops). Perhaps the most insidious example is:
 9273: @example
 9274: AHEAD
 9275: BEGIN
 9276:   x
 9277: [ 1 CS-ROLL ] THEN
 9278:   @{ x @}
 9279:   ...
 9280: UNTIL
 9281: @end example
 9282: 
 9283: This should be legal according to the visibility rule. The use of
 9284: @code{x} can only be reached through the definition; but that appears
 9285: textually below the use.
 9286: 
 9287: From this example it is clear that the visibility rules cannot be fully
 9288: implemented without major headaches. Our implementation treats common
 9289: cases as advertised and the exceptions are treated in a safe way: The
 9290: compiler makes a reasonable guess about the locals visible after a
 9291: @code{BEGIN}; if it is too pessimistic, the
 9292: user will get a spurious error about the local not being defined; if the
 9293: compiler is too optimistic, it will notice this later and issue a
 9294: warning. In the case above the compiler would complain about @code{x}
 9295: being undefined at its use. You can see from the obscure examples in
 9296: this section that it takes quite unusual control structures to get the
 9297: compiler into trouble, and even then it will often do fine.
 9298: 
 9299: If the @code{BEGIN} is reachable from above, the most optimistic guess
 9300: is that all locals visible before the @code{BEGIN} will also be
 9301: visible after the @code{BEGIN}. This guess is valid for all loops that
 9302: are entered only through the @code{BEGIN}, in particular, for normal
 9303: @code{BEGIN}...@code{WHILE}...@code{REPEAT} and
 9304: @code{BEGIN}...@code{UNTIL} loops and it is implemented in our
 9305: compiler. When the branch to the @code{BEGIN} is finally generated by
 9306: @code{AGAIN} or @code{UNTIL}, the compiler checks the guess and
 9307: warns the user if it was too optimistic:
 9308: @example
 9309: IF
 9310:   @{ x @}
 9311: BEGIN
 9312:   \ x ? 
 9313: [ 1 cs-roll ] THEN
 9314:   ...
 9315: UNTIL
 9316: @end example
 9317: 
 9318: Here, @code{x} lives only until the @code{BEGIN}, but the compiler
 9319: optimistically assumes that it lives until the @code{THEN}. It notices
 9320: this difference when it compiles the @code{UNTIL} and issues a
 9321: warning. The user can avoid the warning, and make sure that @code{x}
 9322: is not used in the wrong area by using explicit scoping:
 9323: @example
 9324: IF
 9325:   SCOPE
 9326:   @{ x @}
 9327:   ENDSCOPE
 9328: BEGIN
 9329: [ 1 cs-roll ] THEN
 9330:   ...
 9331: UNTIL
 9332: @end example
 9333: 
 9334: Since the guess is optimistic, there will be no spurious error messages
 9335: about undefined locals.
 9336: 
 9337: If the @code{BEGIN} is not reachable from above (e.g., after
 9338: @code{AHEAD} or @code{EXIT}), the compiler cannot even make an
 9339: optimistic guess, as the locals visible after the @code{BEGIN} may be
 9340: defined later. Therefore, the compiler assumes that no locals are
 9341: visible after the @code{BEGIN}. However, the user can use
 9342: @code{ASSUME-LIVE} to make the compiler assume that the same locals are
 9343: visible at the BEGIN as at the point where the top control-flow stack
 9344: item was created.
 9345: 
 9346: 
 9347: doc-assume-live
 9348: 
 9349: 
 9350: @noindent
 9351: E.g.,
 9352: @example
 9353: @{ x @}
 9354: AHEAD
 9355: ASSUME-LIVE
 9356: BEGIN
 9357:   x
 9358: [ 1 CS-ROLL ] THEN
 9359:   ...
 9360: UNTIL
 9361: @end example
 9362: 
 9363: Other cases where the locals are defined before the @code{BEGIN} can be
 9364: handled by inserting an appropriate @code{CS-ROLL} before the
 9365: @code{ASSUME-LIVE} (and changing the control-flow stack manipulation
 9366: behind the @code{ASSUME-LIVE}).
 9367: 
 9368: Cases where locals are defined after the @code{BEGIN} (but should be
 9369: visible immediately after the @code{BEGIN}) can only be handled by
 9370: rearranging the loop. E.g., the ``most insidious'' example above can be
 9371: arranged into:
 9372: @example
 9373: BEGIN
 9374:   @{ x @}
 9375:   ... 0=
 9376: WHILE
 9377:   x
 9378: REPEAT
 9379: @end example
 9380: 
 9381: @node How long do locals live?, Locals programming style, Where are locals visible by name?, Gforth locals
 9382: @subsubsection How long do locals live?
 9383: @cindex locals lifetime
 9384: @cindex lifetime of locals
 9385: 
 9386: The right answer for the lifetime question would be: A local lives at
 9387: least as long as it can be accessed. For a value-flavoured local this
 9388: means: until the end of its visibility. However, a variable-flavoured
 9389: local could be accessed through its address far beyond its visibility
 9390: scope. Ultimately, this would mean that such locals would have to be
 9391: garbage collected. Since this entails un-Forth-like implementation
 9392: complexities, I adopted the same cowardly solution as some other
 9393: languages (e.g., C): The local lives only as long as it is visible;
 9394: afterwards its address is invalid (and programs that access it
 9395: afterwards are erroneous).
 9396: 
 9397: @node Locals programming style, Locals implementation, How long do locals live?, Gforth locals
 9398: @subsubsection Locals programming style
 9399: @cindex locals programming style
 9400: @cindex programming style, locals
 9401: 
 9402: The freedom to define locals anywhere has the potential to change
 9403: programming styles dramatically. In particular, the need to use the
 9404: return stack for intermediate storage vanishes. Moreover, all stack
 9405: manipulations (except @code{PICK}s and @code{ROLL}s with run-time
 9406: determined arguments) can be eliminated: If the stack items are in the
 9407: wrong order, just write a locals definition for all of them; then
 9408: write the items in the order you want.
 9409: 
 9410: This seems a little far-fetched and eliminating stack manipulations is
 9411: unlikely to become a conscious programming objective. Still, the number
 9412: of stack manipulations will be reduced dramatically if local variables
 9413: are used liberally (e.g., compare @code{max} (@pxref{Gforth locals}) with
 9414: a traditional implementation of @code{max}).
 9415: 
 9416: This shows one potential benefit of locals: making Forth programs more
 9417: readable. Of course, this benefit will only be realized if the
 9418: programmers continue to honour the principle of factoring instead of
 9419: using the added latitude to make the words longer.
 9420: 
 9421: @cindex single-assignment style for locals
 9422: Using @code{TO} can and should be avoided.  Without @code{TO},
 9423: every value-flavoured local has only a single assignment and many
 9424: advantages of functional languages apply to Forth. I.e., programs are
 9425: easier to analyse, to optimize and to read: It is clear from the
 9426: definition what the local stands for, it does not turn into something
 9427: different later.
 9428: 
 9429: E.g., a definition using @code{TO} might look like this:
 9430: @example
 9431: : strcmp @{ addr1 u1 addr2 u2 -- n @}
 9432:  u1 u2 min 0
 9433:  ?do
 9434:    addr1 c@@ addr2 c@@ -
 9435:    ?dup-if
 9436:      unloop exit
 9437:    then
 9438:    addr1 char+ TO addr1
 9439:    addr2 char+ TO addr2
 9440:  loop
 9441:  u1 u2 - ;
 9442: @end example
 9443: Here, @code{TO} is used to update @code{addr1} and @code{addr2} at
 9444: every loop iteration. @code{strcmp} is a typical example of the
 9445: readability problems of using @code{TO}. When you start reading
 9446: @code{strcmp}, you think that @code{addr1} refers to the start of the
 9447: string. Only near the end of the loop you realize that it is something
 9448: else.
 9449: 
 9450: This can be avoided by defining two locals at the start of the loop that
 9451: are initialized with the right value for the current iteration.
 9452: @example
 9453: : strcmp @{ addr1 u1 addr2 u2 -- n @}
 9454:  addr1 addr2
 9455:  u1 u2 min 0 
 9456:  ?do @{ s1 s2 @}
 9457:    s1 c@@ s2 c@@ -
 9458:    ?dup-if
 9459:      unloop exit
 9460:    then
 9461:    s1 char+ s2 char+
 9462:  loop
 9463:  2drop
 9464:  u1 u2 - ;
 9465: @end example
 9466: Here it is clear from the start that @code{s1} has a different value
 9467: in every loop iteration.
 9468: 
 9469: @node Locals implementation,  , Locals programming style, Gforth locals
 9470: @subsubsection Locals implementation
 9471: @cindex locals implementation
 9472: @cindex implementation of locals
 9473: 
 9474: @cindex locals stack
 9475: Gforth uses an extra locals stack. The most compelling reason for
 9476: this is that the return stack is not float-aligned; using an extra stack
 9477: also eliminates the problems and restrictions of using the return stack
 9478: as locals stack. Like the other stacks, the locals stack grows toward
 9479: lower addresses. A few primitives allow an efficient implementation:
 9480: 
 9481: 
 9482: doc-@local#
 9483: doc-f@local#
 9484: doc-laddr#
 9485: doc-lp+!#
 9486: doc-lp!
 9487: doc->l
 9488: doc-f>l
 9489: 
 9490: 
 9491: In addition to these primitives, some specializations of these
 9492: primitives for commonly occurring inline arguments are provided for
 9493: efficiency reasons, e.g., @code{@@local0} as specialization of
 9494: @code{@@local#} for the inline argument 0. The following compiling words
 9495: compile the right specialized version, or the general version, as
 9496: appropriate:
 9497: 
 9498: 
 9499: @c doc-compile-@local
 9500: @c doc-compile-f@local
 9501: doc-compile-lp+!
 9502: 
 9503: 
 9504: Combinations of conditional branches and @code{lp+!#} like
 9505: @code{?branch-lp+!#} (the locals pointer is only changed if the branch
 9506: is taken) are provided for efficiency and correctness in loops.
 9507: 
 9508: A special area in the dictionary space is reserved for keeping the
 9509: local variable names. @code{@{} switches the dictionary pointer to this
 9510: area and @code{@}} switches it back and generates the locals
 9511: initializing code. @code{W:} etc.@ are normal defining words. This
 9512: special area is cleared at the start of every colon definition.
 9513: 
 9514: @cindex word list for defining locals
 9515: A special feature of Gforth's dictionary is used to implement the
 9516: definition of locals without type specifiers: every word list (aka
 9517: vocabulary) has its own methods for searching
 9518: etc. (@pxref{Word Lists}). For the present purpose we defined a word list
 9519: with a special search method: When it is searched for a word, it
 9520: actually creates that word using @code{W:}. @code{@{} changes the search
 9521: order to first search the word list containing @code{@}}, @code{W:} etc.,
 9522: and then the word list for defining locals without type specifiers.
 9523: 
 9524: The lifetime rules support a stack discipline within a colon
 9525: definition: The lifetime of a local is either nested with other locals
 9526: lifetimes or it does not overlap them.
 9527: 
 9528: At @code{BEGIN}, @code{IF}, and @code{AHEAD} no code for locals stack
 9529: pointer manipulation is generated. Between control structure words
 9530: locals definitions can push locals onto the locals stack. @code{AGAIN}
 9531: is the simplest of the other three control flow words. It has to
 9532: restore the locals stack depth of the corresponding @code{BEGIN}
 9533: before branching. The code looks like this:
 9534: @format
 9535: @code{lp+!#} current-locals-size @minus{} dest-locals-size
 9536: @code{branch} <begin>
 9537: @end format
 9538: 
 9539: @code{UNTIL} is a little more complicated: If it branches back, it
 9540: must adjust the stack just like @code{AGAIN}. But if it falls through,
 9541: the locals stack must not be changed. The compiler generates the
 9542: following code:
 9543: @format
 9544: @code{?branch-lp+!#} <begin> current-locals-size @minus{} dest-locals-size
 9545: @end format
 9546: The locals stack pointer is only adjusted if the branch is taken.
 9547: 
 9548: @code{THEN} can produce somewhat inefficient code:
 9549: @format
 9550: @code{lp+!#} current-locals-size @minus{} orig-locals-size
 9551: <orig target>:
 9552: @code{lp+!#} orig-locals-size @minus{} new-locals-size
 9553: @end format
 9554: The second @code{lp+!#} adjusts the locals stack pointer from the
 9555: level at the @i{orig} point to the level after the @code{THEN}. The
 9556: first @code{lp+!#} adjusts the locals stack pointer from the current
 9557: level to the level at the orig point, so the complete effect is an
 9558: adjustment from the current level to the right level after the
 9559: @code{THEN}.
 9560: 
 9561: @cindex locals information on the control-flow stack
 9562: @cindex control-flow stack items, locals information
 9563: In a conventional Forth implementation a dest control-flow stack entry
 9564: is just the target address and an orig entry is just the address to be
 9565: patched. Our locals implementation adds a word list to every orig or dest
 9566: item. It is the list of locals visible (or assumed visible) at the point
 9567: described by the entry. Our implementation also adds a tag to identify
 9568: the kind of entry, in particular to differentiate between live and dead
 9569: (reachable and unreachable) orig entries.
 9570: 
 9571: A few unusual operations have to be performed on locals word lists:
 9572: 
 9573: 
 9574: doc-common-list
 9575: doc-sub-list?
 9576: doc-list-size
 9577: 
 9578: 
 9579: Several features of our locals word list implementation make these
 9580: operations easy to implement: The locals word lists are organised as
 9581: linked lists; the tails of these lists are shared, if the lists
 9582: contain some of the same locals; and the address of a name is greater
 9583: than the address of the names behind it in the list.
 9584: 
 9585: Another important implementation detail is the variable
 9586: @code{dead-code}. It is used by @code{BEGIN} and @code{THEN} to
 9587: determine if they can be reached directly or only through the branch
 9588: that they resolve. @code{dead-code} is set by @code{UNREACHABLE},
 9589: @code{AHEAD}, @code{EXIT} etc., and cleared at the start of a colon
 9590: definition, by @code{BEGIN} and usually by @code{THEN}.
 9591: 
 9592: Counted loops are similar to other loops in most respects, but
 9593: @code{LEAVE} requires special attention: It performs basically the same
 9594: service as @code{AHEAD}, but it does not create a control-flow stack
 9595: entry. Therefore the information has to be stored elsewhere;
 9596: traditionally, the information was stored in the target fields of the
 9597: branches created by the @code{LEAVE}s, by organizing these fields into a
 9598: linked list. Unfortunately, this clever trick does not provide enough
 9599: space for storing our extended control flow information. Therefore, we
 9600: introduce another stack, the leave stack. It contains the control-flow
 9601: stack entries for all unresolved @code{LEAVE}s.
 9602: 
 9603: Local names are kept until the end of the colon definition, even if
 9604: they are no longer visible in any control-flow path. In a few cases
 9605: this may lead to increased space needs for the locals name area, but
 9606: usually less than reclaiming this space would cost in code size.
 9607: 
 9608: 
 9609: @node ANS Forth locals,  , Gforth locals, Locals
 9610: @subsection ANS Forth locals
 9611: @cindex locals, ANS Forth style
 9612: 
 9613: The ANS Forth locals wordset does not define a syntax for locals, but
 9614: words that make it possible to define various syntaxes. One of the
 9615: possible syntaxes is a subset of the syntax we used in the Gforth locals
 9616: wordset, i.e.:
 9617: 
 9618: @example
 9619: @{ local1 local2 ... -- comment @}
 9620: @end example
 9621: @noindent
 9622: or
 9623: @example
 9624: @{ local1 local2 ... @}
 9625: @end example
 9626: 
 9627: The order of the locals corresponds to the order in a stack comment. The
 9628: restrictions are:
 9629: 
 9630: @itemize @bullet
 9631: @item
 9632: Locals can only be cell-sized values (no type specifiers are allowed).
 9633: @item
 9634: Locals can be defined only outside control structures.
 9635: @item
 9636: Locals can interfere with explicit usage of the return stack. For the
 9637: exact (and long) rules, see the standard. If you don't use return stack
 9638: accessing words in a definition using locals, you will be all right. The
 9639: purpose of this rule is to make locals implementation on the return
 9640: stack easier.
 9641: @item
 9642: The whole definition must be in one line.
 9643: @end itemize
 9644: 
 9645: Locals defined in ANS Forth behave like @code{VALUE}s
 9646: (@pxref{Values}). I.e., they are initialized from the stack. Using their
 9647: name produces their value. Their value can be changed using @code{TO}.
 9648: 
 9649: Since the syntax above is supported by Gforth directly, you need not do
 9650: anything to use it. If you want to port a program using this syntax to
 9651: another ANS Forth system, use @file{compat/anslocal.fs} to implement the
 9652: syntax on the other system.
 9653: 
 9654: Note that a syntax shown in the standard, section A.13 looks
 9655: similar, but is quite different in having the order of locals
 9656: reversed. Beware!
 9657: 
 9658: The ANS Forth locals wordset itself consists of one word:
 9659: 
 9660: doc-(local)
 9661: 
 9662: The ANS Forth locals extension wordset defines a syntax using
 9663: @code{locals|}, but it is so awful that we strongly recommend not to use
 9664: it. We have implemented this syntax to make porting to Gforth easy, but
 9665: do not document it here. The problem with this syntax is that the locals
 9666: are defined in an order reversed with respect to the standard stack
 9667: comment notation, making programs harder to read, and easier to misread
 9668: and miswrite. The only merit of this syntax is that it is easy to
 9669: implement using the ANS Forth locals wordset.
 9670: 
 9671: 
 9672: @c ----------------------------------------------------------
 9673: @node Structures, Object-oriented Forth, Locals, Words
 9674: @section  Structures
 9675: @cindex structures
 9676: @cindex records
 9677: 
 9678: This section presents the structure package that comes with Gforth. A
 9679: version of the package implemented in ANS Forth is available in
 9680: @file{compat/struct.fs}. This package was inspired by a posting on
 9681: comp.lang.forth in 1989 (unfortunately I don't remember, by whom;
 9682: possibly John Hayes). A version of this section has been published in
 9683: M. Anton Ertl,
 9684: @uref{http://www.complang.tuwien.ac.at/forth/objects/structs.html, Yet
 9685: Another Forth Structures Package}, Forth Dimensions 19(3), pages
 9686: 13--16. Marcel Hendrix provided helpful comments.
 9687: 
 9688: @menu
 9689: * Why explicit structure support?::  
 9690: * Structure Usage::             
 9691: * Structure Naming Convention::  
 9692: * Structure Implementation::    
 9693: * Structure Glossary::          
 9694: @end menu
 9695: 
 9696: @node Why explicit structure support?, Structure Usage, Structures, Structures
 9697: @subsection Why explicit structure support?
 9698: 
 9699: @cindex address arithmetic for structures
 9700: @cindex structures using address arithmetic
 9701: If we want to use a structure containing several fields, we could simply
 9702: reserve memory for it, and access the fields using address arithmetic
 9703: (@pxref{Address arithmetic}). As an example, consider a structure with
 9704: the following fields
 9705: 
 9706: @table @code
 9707: @item a
 9708: is a float
 9709: @item b
 9710: is a cell
 9711: @item c
 9712: is a float
 9713: @end table
 9714: 
 9715: Given the (float-aligned) base address of the structure we get the
 9716: address of the field
 9717: 
 9718: @table @code
 9719: @item a
 9720: without doing anything further.
 9721: @item b
 9722: with @code{float+}
 9723: @item c
 9724: with @code{float+ cell+ faligned}
 9725: @end table
 9726: 
 9727: It is easy to see that this can become quite tiring. 
 9728: 
 9729: Moreover, it is not very readable, because seeing a
 9730: @code{cell+} tells us neither which kind of structure is
 9731: accessed nor what field is accessed; we have to somehow infer the kind
 9732: of structure, and then look up in the documentation, which field of
 9733: that structure corresponds to that offset.
 9734: 
 9735: Finally, this kind of address arithmetic also causes maintenance
 9736: troubles: If you add or delete a field somewhere in the middle of the
 9737: structure, you have to find and change all computations for the fields
 9738: afterwards.
 9739: 
 9740: So, instead of using @code{cell+} and friends directly, how
 9741: about storing the offsets in constants:
 9742: 
 9743: @example
 9744: 0 constant a-offset
 9745: 0 float+ constant b-offset
 9746: 0 float+ cell+ faligned c-offset
 9747: @end example
 9748: 
 9749: Now we can get the address of field @code{x} with @code{x-offset
 9750: +}. This is much better in all respects. Of course, you still
 9751: have to change all later offset definitions if you add a field. You can
 9752: fix this by declaring the offsets in the following way:
 9753: 
 9754: @example
 9755: 0 constant a-offset
 9756: a-offset float+ constant b-offset
 9757: b-offset cell+ faligned constant c-offset
 9758: @end example
 9759: 
 9760: Since we always use the offsets with @code{+}, we could use a defining
 9761: word @code{cfield} that includes the @code{+} in the action of the
 9762: defined word:
 9763: 
 9764: @example
 9765: : cfield ( n "name" -- )
 9766:     create ,
 9767: does> ( name execution: addr1 -- addr2 )
 9768:     @@ + ;
 9769: 
 9770: 0 cfield a
 9771: 0 a float+ cfield b
 9772: 0 b cell+ faligned cfield c
 9773: @end example
 9774: 
 9775: Instead of @code{x-offset +}, we now simply write @code{x}.
 9776: 
 9777: The structure field words now can be used quite nicely. However,
 9778: their definition is still a bit cumbersome: We have to repeat the
 9779: name, the information about size and alignment is distributed before
 9780: and after the field definitions etc.  The structure package presented
 9781: here addresses these problems.
 9782: 
 9783: @node Structure Usage, Structure Naming Convention, Why explicit structure support?, Structures
 9784: @subsection Structure Usage
 9785: @cindex structure usage
 9786: 
 9787: @cindex @code{field} usage
 9788: @cindex @code{struct} usage
 9789: @cindex @code{end-struct} usage
 9790: You can define a structure for a (data-less) linked list with:
 9791: @example
 9792: struct
 9793:     cell% field list-next
 9794: end-struct list%
 9795: @end example
 9796: 
 9797: With the address of the list node on the stack, you can compute the
 9798: address of the field that contains the address of the next node with
 9799: @code{list-next}. E.g., you can determine the length of a list
 9800: with:
 9801: 
 9802: @example
 9803: : list-length ( list -- n )
 9804: \ "list" is a pointer to the first element of a linked list
 9805: \ "n" is the length of the list
 9806:     0 BEGIN ( list1 n1 )
 9807:         over
 9808:     WHILE ( list1 n1 )
 9809:         1+ swap list-next @@ swap
 9810:     REPEAT
 9811:     nip ;
 9812: @end example
 9813: 
 9814: You can reserve memory for a list node in the dictionary with
 9815: @code{list% %allot}, which leaves the address of the list node on the
 9816: stack. For the equivalent allocation on the heap you can use @code{list%
 9817: %alloc} (or, for an @code{allocate}-like stack effect (i.e., with ior),
 9818: use @code{list% %allocate}). You can get the the size of a list
 9819: node with @code{list% %size} and its alignment with @code{list%
 9820: %alignment}.
 9821: 
 9822: Note that in ANS Forth the body of a @code{create}d word is
 9823: @code{aligned} but not necessarily @code{faligned};
 9824: therefore, if you do a:
 9825: 
 9826: @example
 9827: create @emph{name} foo% %allot drop
 9828: @end example
 9829: 
 9830: @noindent
 9831: then the memory alloted for @code{foo%} is guaranteed to start at the
 9832: body of @code{@emph{name}} only if @code{foo%} contains only character,
 9833: cell and double fields.  Therefore, if your structure contains floats,
 9834: better use
 9835: 
 9836: @example
 9837: foo% %allot constant @emph{name}
 9838: @end example
 9839: 
 9840: @cindex structures containing structures
 9841: You can include a structure @code{foo%} as a field of
 9842: another structure, like this:
 9843: @example
 9844: struct
 9845: ...
 9846:     foo% field ...
 9847: ...
 9848: end-struct ...
 9849: @end example
 9850: 
 9851: @cindex structure extension
 9852: @cindex extended records
 9853: Instead of starting with an empty structure, you can extend an
 9854: existing structure. E.g., a plain linked list without data, as defined
 9855: above, is hardly useful; You can extend it to a linked list of integers,
 9856: like this:@footnote{This feature is also known as @emph{extended
 9857: records}. It is the main innovation in the Oberon language; in other
 9858: words, adding this feature to Modula-2 led Wirth to create a new
 9859: language, write a new compiler etc.  Adding this feature to Forth just
 9860: required a few lines of code.}
 9861: 
 9862: @example
 9863: list%
 9864:     cell% field intlist-int
 9865: end-struct intlist%
 9866: @end example
 9867: 
 9868: @code{intlist%} is a structure with two fields:
 9869: @code{list-next} and @code{intlist-int}.
 9870: 
 9871: @cindex structures containing arrays
 9872: You can specify an array type containing @emph{n} elements of
 9873: type @code{foo%} like this:
 9874: 
 9875: @example
 9876: foo% @emph{n} *
 9877: @end example
 9878: 
 9879: You can use this array type in any place where you can use a normal
 9880: type, e.g., when defining a @code{field}, or with
 9881: @code{%allot}.
 9882: 
 9883: @cindex first field optimization
 9884: The first field is at the base address of a structure and the word for
 9885: this field (e.g., @code{list-next}) actually does not change the address
 9886: on the stack. You may be tempted to leave it away in the interest of
 9887: run-time and space efficiency. This is not necessary, because the
 9888: structure package optimizes this case: If you compile a first-field
 9889: words, no code is generated. So, in the interest of readability and
 9890: maintainability you should include the word for the field when accessing
 9891: the field.
 9892: 
 9893: 
 9894: @node Structure Naming Convention, Structure Implementation, Structure Usage, Structures
 9895: @subsection Structure Naming Convention
 9896: @cindex structure naming convention
 9897: 
 9898: The field names that come to (my) mind are often quite generic, and,
 9899: if used, would cause frequent name clashes. E.g., many structures
 9900: probably contain a @code{counter} field. The structure names
 9901: that come to (my) mind are often also the logical choice for the names
 9902: of words that create such a structure.
 9903: 
 9904: Therefore, I have adopted the following naming conventions: 
 9905: 
 9906: @itemize @bullet
 9907: @cindex field naming convention
 9908: @item
 9909: The names of fields are of the form
 9910: @code{@emph{struct}-@emph{field}}, where
 9911: @code{@emph{struct}} is the basic name of the structure, and
 9912: @code{@emph{field}} is the basic name of the field. You can
 9913: think of field words as converting the (address of the)
 9914: structure into the (address of the) field.
 9915: 
 9916: @cindex structure naming convention
 9917: @item
 9918: The names of structures are of the form
 9919: @code{@emph{struct}%}, where
 9920: @code{@emph{struct}} is the basic name of the structure.
 9921: @end itemize
 9922: 
 9923: This naming convention does not work that well for fields of extended
 9924: structures; e.g., the integer list structure has a field
 9925: @code{intlist-int}, but has @code{list-next}, not
 9926: @code{intlist-next}.
 9927: 
 9928: @node Structure Implementation, Structure Glossary, Structure Naming Convention, Structures
 9929: @subsection Structure Implementation
 9930: @cindex structure implementation
 9931: @cindex implementation of structures
 9932: 
 9933: The central idea in the implementation is to pass the data about the
 9934: structure being built on the stack, not in some global
 9935: variable. Everything else falls into place naturally once this design
 9936: decision is made.
 9937: 
 9938: The type description on the stack is of the form @emph{align
 9939: size}. Keeping the size on the top-of-stack makes dealing with arrays
 9940: very simple.
 9941: 
 9942: @code{field} is a defining word that uses @code{Create}
 9943: and @code{DOES>}. The body of the field contains the offset
 9944: of the field, and the normal @code{DOES>} action is simply:
 9945: 
 9946: @example
 9947: @@ +
 9948: @end example
 9949: 
 9950: @noindent
 9951: i.e., add the offset to the address, giving the stack effect
 9952: @i{addr1 -- addr2} for a field.
 9953: 
 9954: @cindex first field optimization, implementation
 9955: This simple structure is slightly complicated by the optimization
 9956: for fields with offset 0, which requires a different
 9957: @code{DOES>}-part (because we cannot rely on there being
 9958: something on the stack if such a field is invoked during
 9959: compilation). Therefore, we put the different @code{DOES>}-parts
 9960: in separate words, and decide which one to invoke based on the
 9961: offset. For a zero offset, the field is basically a noop; it is
 9962: immediate, and therefore no code is generated when it is compiled.
 9963: 
 9964: @node Structure Glossary,  , Structure Implementation, Structures
 9965: @subsection Structure Glossary
 9966: @cindex structure glossary
 9967: 
 9968: 
 9969: doc-%align
 9970: doc-%alignment
 9971: doc-%alloc
 9972: doc-%allocate
 9973: doc-%allot
 9974: doc-cell%
 9975: doc-char%
 9976: doc-dfloat%
 9977: doc-double%
 9978: doc-end-struct
 9979: doc-field
 9980: doc-float%
 9981: doc-naligned
 9982: doc-sfloat%
 9983: doc-%size
 9984: doc-struct
 9985: 
 9986: 
 9987: @c -------------------------------------------------------------
 9988: @node Object-oriented Forth, Programming Tools, Structures, Words
 9989: @section Object-oriented Forth
 9990: 
 9991: Gforth comes with three packages for object-oriented programming:
 9992: @file{objects.fs}, @file{oof.fs}, and @file{mini-oof.fs}; none of them
 9993: is preloaded, so you have to @code{include} them before use. The most
 9994: important differences between these packages (and others) are discussed
 9995: in @ref{Comparison with other object models}. All packages are written
 9996: in ANS Forth and can be used with any other ANS Forth.
 9997: 
 9998: @menu
 9999: * Why object-oriented programming?::  
10000: * Object-Oriented Terminology::  
10001: * Objects::                     
10002: * OOF::                         
10003: * Mini-OOF::                    
10004: * Comparison with other object models::  
10005: @end menu
10006: 
10007: @c ----------------------------------------------------------------
10008: @node Why object-oriented programming?, Object-Oriented Terminology, Object-oriented Forth, Object-oriented Forth
10009: @subsection Why object-oriented programming?
10010: @cindex object-oriented programming motivation
10011: @cindex motivation for object-oriented programming
10012: 
10013: Often we have to deal with several data structures (@emph{objects}),
10014: that have to be treated similarly in some respects, but differently in
10015: others. Graphical objects are the textbook example: circles, triangles,
10016: dinosaurs, icons, and others, and we may want to add more during program
10017: development. We want to apply some operations to any graphical object,
10018: e.g., @code{draw} for displaying it on the screen. However, @code{draw}
10019: has to do something different for every kind of object.
10020: @comment TODO add some other operations eg perimeter, area
10021: @comment and tie in to concrete examples later..
10022: 
10023: We could implement @code{draw} as a big @code{CASE}
10024: control structure that executes the appropriate code depending on the
10025: kind of object to be drawn. This would be not be very elegant, and,
10026: moreover, we would have to change @code{draw} every time we add
10027: a new kind of graphical object (say, a spaceship).
10028: 
10029: What we would rather do is: When defining spaceships, we would tell
10030: the system: ``Here's how you @code{draw} a spaceship; you figure
10031: out the rest''.
10032: 
10033: This is the problem that all systems solve that (rightfully) call
10034: themselves object-oriented; the object-oriented packages presented here
10035: solve this problem (and not much else).
10036: @comment TODO ?list properties of oo systems.. oo vs o-based?
10037: 
10038: @c ------------------------------------------------------------------------
10039: @node Object-Oriented Terminology, Objects, Why object-oriented programming?, Object-oriented Forth
10040: @subsection Object-Oriented Terminology
10041: @cindex object-oriented terminology
10042: @cindex terminology for object-oriented programming
10043: 
10044: This section is mainly for reference, so you don't have to understand
10045: all of it right away.  The terminology is mainly Smalltalk-inspired.  In
10046: short:
10047: 
10048: @table @emph
10049: @cindex class
10050: @item class
10051: a data structure definition with some extras.
10052: 
10053: @cindex object
10054: @item object
10055: an instance of the data structure described by the class definition.
10056: 
10057: @cindex instance variables
10058: @item instance variables
10059: fields of the data structure.
10060: 
10061: @cindex selector
10062: @cindex method selector
10063: @cindex virtual function
10064: @item selector
10065: (or @emph{method selector}) a word (e.g.,
10066: @code{draw}) that performs an operation on a variety of data
10067: structures (classes). A selector describes @emph{what} operation to
10068: perform. In C++ terminology: a (pure) virtual function.
10069: 
10070: @cindex method
10071: @item method
10072: the concrete definition that performs the operation
10073: described by the selector for a specific class. A method specifies
10074: @emph{how} the operation is performed for a specific class.
10075: 
10076: @cindex selector invocation
10077: @cindex message send
10078: @cindex invoking a selector
10079: @item selector invocation
10080: a call of a selector. One argument of the call (the TOS (top-of-stack))
10081: is used for determining which method is used. In Smalltalk terminology:
10082: a message (consisting of the selector and the other arguments) is sent
10083: to the object.
10084: 
10085: @cindex receiving object
10086: @item receiving object
10087: the object used for determining the method executed by a selector
10088: invocation. In the @file{objects.fs} model, it is the object that is on
10089: the TOS when the selector is invoked. (@emph{Receiving} comes from
10090: the Smalltalk @emph{message} terminology.)
10091: 
10092: @cindex child class
10093: @cindex parent class
10094: @cindex inheritance
10095: @item child class
10096: a class that has (@emph{inherits}) all properties (instance variables,
10097: selectors, methods) from a @emph{parent class}. In Smalltalk
10098: terminology: The subclass inherits from the superclass. In C++
10099: terminology: The derived class inherits from the base class.
10100: 
10101: @end table
10102: 
10103: @c If you wonder about the message sending terminology, it comes from
10104: @c a time when each object had it's own task and objects communicated via
10105: @c message passing; eventually the Smalltalk developers realized that
10106: @c they can do most things through simple (indirect) calls. They kept the
10107: @c terminology.
10108: 
10109: @c --------------------------------------------------------------
10110: @node Objects, OOF, Object-Oriented Terminology, Object-oriented Forth
10111: @subsection The @file{objects.fs} model
10112: @cindex objects
10113: @cindex object-oriented programming
10114: 
10115: @cindex @file{objects.fs}
10116: @cindex @file{oof.fs}
10117: 
10118: This section describes the @file{objects.fs} package. This material also
10119: has been published in M. Anton Ertl,
10120: @cite{@uref{http://www.complang.tuwien.ac.at/forth/objects/objects.html,
10121: Yet Another Forth Objects Package}}, Forth Dimensions 19(2), pages
10122: 37--43.
10123: @c McKewan's and Zsoter's packages
10124: 
10125: This section assumes that you have read @ref{Structures}.
10126: 
10127: The techniques on which this model is based have been used to implement
10128: the parser generator, Gray, and have also been used in Gforth for
10129: implementing the various flavours of word lists (hashed or not,
10130: case-sensitive or not, special-purpose word lists for locals etc.).
10131: 
10132: 
10133: @menu
10134: * Properties of the Objects model::  
10135: * Basic Objects Usage::         
10136: * The Objects base class::      
10137: * Creating objects::            
10138: * Object-Oriented Programming Style::  
10139: * Class Binding::               
10140: * Method conveniences::         
10141: * Classes and Scoping::         
10142: * Dividing classes::            
10143: * Object Interfaces::           
10144: * Objects Implementation::      
10145: * Objects Glossary::            
10146: @end menu
10147: 
10148: Marcel Hendrix provided helpful comments on this section.
10149: 
10150: @node Properties of the Objects model, Basic Objects Usage, Objects, Objects
10151: @subsubsection Properties of the @file{objects.fs} model
10152: @cindex @file{objects.fs} properties
10153: 
10154: @itemize @bullet
10155: @item
10156: It is straightforward to pass objects on the stack. Passing
10157: selectors on the stack is a little less convenient, but possible.
10158: 
10159: @item
10160: Objects are just data structures in memory, and are referenced by their
10161: address. You can create words for objects with normal defining words
10162: like @code{constant}. Likewise, there is no difference between instance
10163: variables that contain objects and those that contain other data.
10164: 
10165: @item
10166: Late binding is efficient and easy to use.
10167: 
10168: @item
10169: It avoids parsing, and thus avoids problems with state-smartness
10170: and reduced extensibility; for convenience there are a few parsing
10171: words, but they have non-parsing counterparts. There are also a few
10172: defining words that parse. This is hard to avoid, because all standard
10173: defining words parse (except @code{:noname}); however, such
10174: words are not as bad as many other parsing words, because they are not
10175: state-smart.
10176: 
10177: @item
10178: It does not try to incorporate everything. It does a few things and does
10179: them well (IMO). In particular, this model was not designed to support
10180: information hiding (although it has features that may help); you can use
10181: a separate package for achieving this.
10182: 
10183: @item
10184: It is layered; you don't have to learn and use all features to use this
10185: model. Only a few features are necessary (@pxref{Basic Objects Usage},
10186: @pxref{The Objects base class}, @pxref{Creating objects}.), the others
10187: are optional and independent of each other.
10188: 
10189: @item
10190: An implementation in ANS Forth is available.
10191: 
10192: @end itemize
10193: 
10194: 
10195: @node Basic Objects Usage, The Objects base class, Properties of the Objects model, Objects
10196: @subsubsection Basic @file{objects.fs} Usage
10197: @cindex basic objects usage
10198: @cindex objects, basic usage
10199: 
10200: You can define a class for graphical objects like this:
10201: 
10202: @cindex @code{class} usage
10203: @cindex @code{end-class} usage
10204: @cindex @code{selector} usage
10205: @example
10206: object class \ "object" is the parent class
10207:   selector draw ( x y graphical -- )
10208: end-class graphical
10209: @end example
10210: 
10211: This code defines a class @code{graphical} with an
10212: operation @code{draw}.  We can perform the operation
10213: @code{draw} on any @code{graphical} object, e.g.:
10214: 
10215: @example
10216: 100 100 t-rex draw
10217: @end example
10218: 
10219: @noindent
10220: where @code{t-rex} is a word (say, a constant) that produces a
10221: graphical object.
10222: 
10223: @comment TODO add a 2nd operation eg perimeter.. and use for
10224: @comment a concrete example
10225: 
10226: @cindex abstract class
10227: How do we create a graphical object? With the present definitions,
10228: we cannot create a useful graphical object. The class
10229: @code{graphical} describes graphical objects in general, but not
10230: any concrete graphical object type (C++ users would call it an
10231: @emph{abstract class}); e.g., there is no method for the selector
10232: @code{draw} in the class @code{graphical}.
10233: 
10234: For concrete graphical objects, we define child classes of the
10235: class @code{graphical}, e.g.:
10236: 
10237: @cindex @code{overrides} usage
10238: @cindex @code{field} usage in class definition
10239: @example
10240: graphical class \ "graphical" is the parent class
10241:   cell% field circle-radius
10242: 
10243: :noname ( x y circle -- )
10244:   circle-radius @@ draw-circle ;
10245: overrides draw
10246: 
10247: :noname ( n-radius circle -- )
10248:   circle-radius ! ;
10249: overrides construct
10250: 
10251: end-class circle
10252: @end example
10253: 
10254: Here we define a class @code{circle} as a child of @code{graphical},
10255: with field @code{circle-radius} (which behaves just like a field
10256: (@pxref{Structures}); it defines (using @code{overrides}) new methods
10257: for the selectors @code{draw} and @code{construct} (@code{construct} is
10258: defined in @code{object}, the parent class of @code{graphical}).
10259: 
10260: Now we can create a circle on the heap (i.e.,
10261: @code{allocate}d memory) with:
10262: 
10263: @cindex @code{heap-new} usage
10264: @example
10265: 50 circle heap-new constant my-circle
10266: @end example
10267: 
10268: @noindent
10269: @code{heap-new} invokes @code{construct}, thus
10270: initializing the field @code{circle-radius} with 50. We can draw
10271: this new circle at (100,100) with:
10272: 
10273: @example
10274: 100 100 my-circle draw
10275: @end example
10276: 
10277: @cindex selector invocation, restrictions
10278: @cindex class definition, restrictions
10279: Note: You can only invoke a selector if the object on the TOS
10280: (the receiving object) belongs to the class where the selector was
10281: defined or one of its descendents; e.g., you can invoke
10282: @code{draw} only for objects belonging to @code{graphical}
10283: or its descendents (e.g., @code{circle}).  Immediately before
10284: @code{end-class}, the search order has to be the same as
10285: immediately after @code{class}.
10286: 
10287: @node The Objects base class, Creating objects, Basic Objects Usage, Objects
10288: @subsubsection The @file{object.fs} base class
10289: @cindex @code{object} class
10290: 
10291: When you define a class, you have to specify a parent class.  So how do
10292: you start defining classes? There is one class available from the start:
10293: @code{object}. It is ancestor for all classes and so is the
10294: only class that has no parent. It has two selectors: @code{construct}
10295: and @code{print}.
10296: 
10297: @node Creating objects, Object-Oriented Programming Style, The Objects base class, Objects
10298: @subsubsection Creating objects
10299: @cindex creating objects
10300: @cindex object creation
10301: @cindex object allocation options
10302: 
10303: @cindex @code{heap-new} discussion
10304: @cindex @code{dict-new} discussion
10305: @cindex @code{construct} discussion
10306: You can create and initialize an object of a class on the heap with
10307: @code{heap-new} ( ... class -- object ) and in the dictionary
10308: (allocation with @code{allot}) with @code{dict-new} (
10309: ... class -- object ). Both words invoke @code{construct}, which
10310: consumes the stack items indicated by "..." above.
10311: 
10312: @cindex @code{init-object} discussion
10313: @cindex @code{class-inst-size} discussion
10314: If you want to allocate memory for an object yourself, you can get its
10315: alignment and size with @code{class-inst-size 2@@} ( class --
10316: align size ). Once you have memory for an object, you can initialize
10317: it with @code{init-object} ( ... class object -- );
10318: @code{construct} does only a part of the necessary work.
10319: 
10320: @node Object-Oriented Programming Style, Class Binding, Creating objects, Objects
10321: @subsubsection Object-Oriented Programming Style
10322: @cindex object-oriented programming style
10323: @cindex programming style, object-oriented
10324: 
10325: This section is not exhaustive.
10326: 
10327: @cindex stack effects of selectors
10328: @cindex selectors and stack effects
10329: In general, it is a good idea to ensure that all methods for the
10330: same selector have the same stack effect: when you invoke a selector,
10331: you often have no idea which method will be invoked, so, unless all
10332: methods have the same stack effect, you will not know the stack effect
10333: of the selector invocation.
10334: 
10335: One exception to this rule is methods for the selector
10336: @code{construct}. We know which method is invoked, because we
10337: specify the class to be constructed at the same place. Actually, I
10338: defined @code{construct} as a selector only to give the users a
10339: convenient way to specify initialization. The way it is used, a
10340: mechanism different from selector invocation would be more natural
10341: (but probably would take more code and more space to explain).
10342: 
10343: @node Class Binding, Method conveniences, Object-Oriented Programming Style, Objects
10344: @subsubsection Class Binding
10345: @cindex class binding
10346: @cindex early binding
10347: 
10348: @cindex late binding
10349: Normal selector invocations determine the method at run-time depending
10350: on the class of the receiving object. This run-time selection is called
10351: @i{late binding}.
10352: 
10353: Sometimes it's preferable to invoke a different method. For example,
10354: you might want to use the simple method for @code{print}ing
10355: @code{object}s instead of the possibly long-winded @code{print} method
10356: of the receiver class. You can achieve this by replacing the invocation
10357: of @code{print} with:
10358: 
10359: @cindex @code{[bind]} usage
10360: @example
10361: [bind] object print
10362: @end example
10363: 
10364: @noindent
10365: in compiled code or:
10366: 
10367: @cindex @code{bind} usage
10368: @example
10369: bind object print
10370: @end example
10371: 
10372: @cindex class binding, alternative to
10373: @noindent
10374: in interpreted code. Alternatively, you can define the method with a
10375: name (e.g., @code{print-object}), and then invoke it through the
10376: name. Class binding is just a (often more convenient) way to achieve
10377: the same effect; it avoids name clutter and allows you to invoke
10378: methods directly without naming them first.
10379: 
10380: @cindex superclass binding
10381: @cindex parent class binding
10382: A frequent use of class binding is this: When we define a method
10383: for a selector, we often want the method to do what the selector does
10384: in the parent class, and a little more. There is a special word for
10385: this purpose: @code{[parent]}; @code{[parent]
10386: @emph{selector}} is equivalent to @code{[bind] @emph{parent
10387: selector}}, where @code{@emph{parent}} is the parent
10388: class of the current class. E.g., a method definition might look like:
10389: 
10390: @cindex @code{[parent]} usage
10391: @example
10392: :noname
10393:   dup [parent] foo \ do parent's foo on the receiving object
10394:   ... \ do some more
10395: ; overrides foo
10396: @end example
10397: 
10398: @cindex class binding as optimization
10399: In @cite{Object-oriented programming in ANS Forth} (Forth Dimensions,
10400: March 1997), Andrew McKewan presents class binding as an optimization
10401: technique. I recommend not using it for this purpose unless you are in
10402: an emergency. Late binding is pretty fast with this model anyway, so the
10403: benefit of using class binding is small; the cost of using class binding
10404: where it is not appropriate is reduced maintainability.
10405: 
10406: While we are at programming style questions: You should bind
10407: selectors only to ancestor classes of the receiving object. E.g., say,
10408: you know that the receiving object is of class @code{foo} or its
10409: descendents; then you should bind only to @code{foo} and its
10410: ancestors.
10411: 
10412: @node Method conveniences, Classes and Scoping, Class Binding, Objects
10413: @subsubsection Method conveniences
10414: @cindex method conveniences
10415: 
10416: In a method you usually access the receiving object pretty often.  If
10417: you define the method as a plain colon definition (e.g., with
10418: @code{:noname}), you may have to do a lot of stack
10419: gymnastics. To avoid this, you can define the method with @code{m:
10420: ... ;m}. E.g., you could define the method for
10421: @code{draw}ing a @code{circle} with
10422: 
10423: @cindex @code{this} usage
10424: @cindex @code{m:} usage
10425: @cindex @code{;m} usage
10426: @example
10427: m: ( x y circle -- )
10428:   ( x y ) this circle-radius @@ draw-circle ;m
10429: @end example
10430: 
10431: @cindex @code{exit} in @code{m: ... ;m}
10432: @cindex @code{exitm} discussion
10433: @cindex @code{catch} in @code{m: ... ;m}
10434: When this method is executed, the receiver object is removed from the
10435: stack; you can access it with @code{this} (admittedly, in this
10436: example the use of @code{m: ... ;m} offers no advantage). Note
10437: that I specify the stack effect for the whole method (i.e. including
10438: the receiver object), not just for the code between @code{m:}
10439: and @code{;m}. You cannot use @code{exit} in
10440: @code{m:...;m}; instead, use
10441: @code{exitm}.@footnote{Moreover, for any word that calls
10442: @code{catch} and was defined before loading
10443: @code{objects.fs}, you have to redefine it like I redefined
10444: @code{catch}: @code{: catch this >r catch r> to-this ;}}
10445: 
10446: @cindex @code{inst-var} usage
10447: You will frequently use sequences of the form @code{this
10448: @emph{field}} (in the example above: @code{this
10449: circle-radius}). If you use the field only in this way, you can
10450: define it with @code{inst-var} and eliminate the
10451: @code{this} before the field name. E.g., the @code{circle}
10452: class above could also be defined with:
10453: 
10454: @example
10455: graphical class
10456:   cell% inst-var radius
10457: 
10458: m: ( x y circle -- )
10459:   radius @@ draw-circle ;m
10460: overrides draw
10461: 
10462: m: ( n-radius circle -- )
10463:   radius ! ;m
10464: overrides construct
10465: 
10466: end-class circle
10467: @end example
10468: 
10469: @code{radius} can only be used in @code{circle} and its
10470: descendent classes and inside @code{m:...;m}.
10471: 
10472: @cindex @code{inst-value} usage
10473: You can also define fields with @code{inst-value}, which is
10474: to @code{inst-var} what @code{value} is to
10475: @code{variable}.  You can change the value of such a field with
10476: @code{[to-inst]}.  E.g., we could also define the class
10477: @code{circle} like this:
10478: 
10479: @example
10480: graphical class
10481:   inst-value radius
10482: 
10483: m: ( x y circle -- )
10484:   radius draw-circle ;m
10485: overrides draw
10486: 
10487: m: ( n-radius circle -- )
10488:   [to-inst] radius ;m
10489: overrides construct
10490: 
10491: end-class circle
10492: @end example
10493: 
10494: @c !! :m is easy to confuse with m:.  Another name would be better.
10495: 
10496: @c Finally, you can define named methods with @code{:m}.  One use of this
10497: @c feature is the definition of words that occur only in one class and are
10498: @c not intended to be overridden, but which still need method context
10499: @c (e.g., for accessing @code{inst-var}s).  Another use is for methods that
10500: @c would be bound frequently, if defined anonymously.
10501: 
10502: 
10503: @node Classes and Scoping, Dividing classes, Method conveniences, Objects
10504: @subsubsection Classes and Scoping
10505: @cindex classes and scoping
10506: @cindex scoping and classes
10507: 
10508: Inheritance is frequent, unlike structure extension. This exacerbates
10509: the problem with the field name convention (@pxref{Structure Naming
10510: Convention}): One always has to remember in which class the field was
10511: originally defined; changing a part of the class structure would require
10512: changes for renaming in otherwise unaffected code.
10513: 
10514: @cindex @code{inst-var} visibility
10515: @cindex @code{inst-value} visibility
10516: To solve this problem, I added a scoping mechanism (which was not in my
10517: original charter): A field defined with @code{inst-var} (or
10518: @code{inst-value}) is visible only in the class where it is defined and in
10519: the descendent classes of this class.  Using such fields only makes
10520: sense in @code{m:}-defined methods in these classes anyway.
10521: 
10522: This scoping mechanism allows us to use the unadorned field name,
10523: because name clashes with unrelated words become much less likely.
10524: 
10525: @cindex @code{protected} discussion
10526: @cindex @code{private} discussion
10527: Once we have this mechanism, we can also use it for controlling the
10528: visibility of other words: All words defined after
10529: @code{protected} are visible only in the current class and its
10530: descendents. @code{public} restores the compilation
10531: (i.e. @code{current}) word list that was in effect before. If you
10532: have several @code{protected}s without an intervening
10533: @code{public} or @code{set-current}, @code{public}
10534: will restore the compilation word list in effect before the first of
10535: these @code{protected}s.
10536: 
10537: @node Dividing classes, Object Interfaces, Classes and Scoping, Objects
10538: @subsubsection Dividing classes
10539: @cindex Dividing classes
10540: @cindex @code{methods}...@code{end-methods}
10541: 
10542: You may want to do the definition of methods separate from the
10543: definition of the class, its selectors, fields, and instance variables,
10544: i.e., separate the implementation from the definition.  You can do this
10545: in the following way:
10546: 
10547: @example
10548: graphical class
10549:   inst-value radius
10550: end-class circle
10551: 
10552: ... \ do some other stuff
10553: 
10554: circle methods \ now we are ready
10555: 
10556: m: ( x y circle -- )
10557:   radius draw-circle ;m
10558: overrides draw
10559: 
10560: m: ( n-radius circle -- )
10561:   [to-inst] radius ;m
10562: overrides construct
10563: 
10564: end-methods
10565: @end example
10566: 
10567: You can use several @code{methods}...@code{end-methods} sections.  The
10568: only things you can do to the class in these sections are: defining
10569: methods, and overriding the class's selectors.  You must not define new
10570: selectors or fields.
10571: 
10572: Note that you often have to override a selector before using it.  In
10573: particular, you usually have to override @code{construct} with a new
10574: method before you can invoke @code{heap-new} and friends.  E.g., you
10575: must not create a circle before the @code{overrides construct} sequence
10576: in the example above.
10577: 
10578: @node Object Interfaces, Objects Implementation, Dividing classes, Objects
10579: @subsubsection Object Interfaces
10580: @cindex object interfaces
10581: @cindex interfaces for objects
10582: 
10583: In this model you can only call selectors defined in the class of the
10584: receiving objects or in one of its ancestors. If you call a selector
10585: with a receiving object that is not in one of these classes, the
10586: result is undefined; if you are lucky, the program crashes
10587: immediately.
10588: 
10589: @cindex selectors common to hardly-related classes
10590: Now consider the case when you want to have a selector (or several)
10591: available in two classes: You would have to add the selector to a
10592: common ancestor class, in the worst case to @code{object}. You
10593: may not want to do this, e.g., because someone else is responsible for
10594: this ancestor class.
10595: 
10596: The solution for this problem is interfaces. An interface is a
10597: collection of selectors. If a class implements an interface, the
10598: selectors become available to the class and its descendents. A class
10599: can implement an unlimited number of interfaces. For the problem
10600: discussed above, we would define an interface for the selector(s), and
10601: both classes would implement the interface.
10602: 
10603: As an example, consider an interface @code{storage} for
10604: writing objects to disk and getting them back, and a class
10605: @code{foo} that implements it. The code would look like this:
10606: 
10607: @cindex @code{interface} usage
10608: @cindex @code{end-interface} usage
10609: @cindex @code{implementation} usage
10610: @example
10611: interface
10612:   selector write ( file object -- )
10613:   selector read1 ( file object -- )
10614: end-interface storage
10615: 
10616: bar class
10617:   storage implementation
10618: 
10619: ... overrides write
10620: ... overrides read1
10621: ...
10622: end-class foo
10623: @end example
10624: 
10625: @noindent
10626: (I would add a word @code{read} @i{( file -- object )} that uses
10627: @code{read1} internally, but that's beyond the point illustrated
10628: here.)
10629: 
10630: Note that you cannot use @code{protected} in an interface; and
10631: of course you cannot define fields.
10632: 
10633: In the Neon model, all selectors are available for all classes;
10634: therefore it does not need interfaces. The price you pay in this model
10635: is slower late binding, and therefore, added complexity to avoid late
10636: binding.
10637: 
10638: @node Objects Implementation, Objects Glossary, Object Interfaces, Objects
10639: @subsubsection @file{objects.fs} Implementation
10640: @cindex @file{objects.fs} implementation
10641: 
10642: @cindex @code{object-map} discussion
10643: An object is a piece of memory, like one of the data structures
10644: described with @code{struct...end-struct}. It has a field
10645: @code{object-map} that points to the method map for the object's
10646: class.
10647: 
10648: @cindex method map
10649: @cindex virtual function table
10650: The @emph{method map}@footnote{This is Self terminology; in C++
10651: terminology: virtual function table.} is an array that contains the
10652: execution tokens (@i{xt}s) of the methods for the object's class. Each
10653: selector contains an offset into a method map.
10654: 
10655: @cindex @code{selector} implementation, class
10656: @code{selector} is a defining word that uses
10657: @code{CREATE} and @code{DOES>}. The body of the
10658: selector contains the offset; the @code{DOES>} action for a
10659: class selector is, basically:
10660: 
10661: @example
10662: ( object addr ) @@ over object-map @@ + @@ execute
10663: @end example
10664: 
10665: Since @code{object-map} is the first field of the object, it
10666: does not generate any code. As you can see, calling a selector has a
10667: small, constant cost.
10668: 
10669: @cindex @code{current-interface} discussion
10670: @cindex class implementation and representation
10671: A class is basically a @code{struct} combined with a method
10672: map. During the class definition the alignment and size of the class
10673: are passed on the stack, just as with @code{struct}s, so
10674: @code{field} can also be used for defining class
10675: fields. However, passing more items on the stack would be
10676: inconvenient, so @code{class} builds a data structure in memory,
10677: which is accessed through the variable
10678: @code{current-interface}. After its definition is complete, the
10679: class is represented on the stack by a pointer (e.g., as parameter for
10680: a child class definition).
10681: 
10682: A new class starts off with the alignment and size of its parent,
10683: and a copy of the parent's method map. Defining new fields extends the
10684: size and alignment; likewise, defining new selectors extends the
10685: method map. @code{overrides} just stores a new @i{xt} in the method
10686: map at the offset given by the selector.
10687: 
10688: @cindex class binding, implementation
10689: Class binding just gets the @i{xt} at the offset given by the selector
10690: from the class's method map and @code{compile,}s (in the case of
10691: @code{[bind]}) it.
10692: 
10693: @cindex @code{this} implementation
10694: @cindex @code{catch} and @code{this}
10695: @cindex @code{this} and @code{catch}
10696: I implemented @code{this} as a @code{value}. At the
10697: start of an @code{m:...;m} method the old @code{this} is
10698: stored to the return stack and restored at the end; and the object on
10699: the TOS is stored @code{TO this}. This technique has one
10700: disadvantage: If the user does not leave the method via
10701: @code{;m}, but via @code{throw} or @code{exit},
10702: @code{this} is not restored (and @code{exit} may
10703: crash). To deal with the @code{throw} problem, I have redefined
10704: @code{catch} to save and restore @code{this}; the same
10705: should be done with any word that can catch an exception. As for
10706: @code{exit}, I simply forbid it (as a replacement, there is
10707: @code{exitm}).
10708: 
10709: @cindex @code{inst-var} implementation
10710: @code{inst-var} is just the same as @code{field}, with
10711: a different @code{DOES>} action:
10712: @example
10713: @@ this +
10714: @end example
10715: Similar for @code{inst-value}.
10716: 
10717: @cindex class scoping implementation
10718: Each class also has a word list that contains the words defined with
10719: @code{inst-var} and @code{inst-value}, and its protected
10720: words. It also has a pointer to its parent. @code{class} pushes
10721: the word lists of the class and all its ancestors onto the search order stack,
10722: and @code{end-class} drops them.
10723: 
10724: @cindex interface implementation
10725: An interface is like a class without fields, parent and protected
10726: words; i.e., it just has a method map. If a class implements an
10727: interface, its method map contains a pointer to the method map of the
10728: interface. The positive offsets in the map are reserved for class
10729: methods, therefore interface map pointers have negative
10730: offsets. Interfaces have offsets that are unique throughout the
10731: system, unlike class selectors, whose offsets are only unique for the
10732: classes where the selector is available (invokable).
10733: 
10734: This structure means that interface selectors have to perform one
10735: indirection more than class selectors to find their method. Their body
10736: contains the interface map pointer offset in the class method map, and
10737: the method offset in the interface method map. The
10738: @code{does>} action for an interface selector is, basically:
10739: 
10740: @example
10741: ( object selector-body )
10742: 2dup selector-interface @@ ( object selector-body object interface-offset )
10743: swap object-map @@ + @@ ( object selector-body map )
10744: swap selector-offset @@ + @@ execute
10745: @end example
10746: 
10747: where @code{object-map} and @code{selector-offset} are
10748: first fields and generate no code.
10749: 
10750: As a concrete example, consider the following code:
10751: 
10752: @example
10753: interface
10754:   selector if1sel1
10755:   selector if1sel2
10756: end-interface if1
10757: 
10758: object class
10759:   if1 implementation
10760:   selector cl1sel1
10761:   cell% inst-var cl1iv1
10762: 
10763: ' m1 overrides construct
10764: ' m2 overrides if1sel1
10765: ' m3 overrides if1sel2
10766: ' m4 overrides cl1sel2
10767: end-class cl1
10768: 
10769: create obj1 object dict-new drop
10770: create obj2 cl1    dict-new drop
10771: @end example
10772: 
10773: The data structure created by this code (including the data structure
10774: for @code{object}) is shown in the
10775: @uref{objects-implementation.eps,figure}, assuming a cell size of 4.
10776: @comment TODO add this diagram..
10777: 
10778: @node Objects Glossary,  , Objects Implementation, Objects
10779: @subsubsection @file{objects.fs} Glossary
10780: @cindex @file{objects.fs} Glossary
10781: 
10782: 
10783: doc---objects-bind
10784: doc---objects-<bind>
10785: doc---objects-bind'
10786: doc---objects-[bind]
10787: doc---objects-class
10788: doc---objects-class->map
10789: doc---objects-class-inst-size
10790: doc---objects-class-override!
10791: doc---objects-class-previous
10792: doc---objects-class>order
10793: doc---objects-construct
10794: doc---objects-current'
10795: doc---objects-[current]
10796: doc---objects-current-interface
10797: doc---objects-dict-new
10798: doc---objects-end-class
10799: doc---objects-end-class-noname
10800: doc---objects-end-interface
10801: doc---objects-end-interface-noname
10802: doc---objects-end-methods
10803: doc---objects-exitm
10804: doc---objects-heap-new
10805: doc---objects-implementation
10806: doc---objects-init-object
10807: doc---objects-inst-value
10808: doc---objects-inst-var
10809: doc---objects-interface
10810: doc---objects-m:
10811: doc---objects-:m
10812: doc---objects-;m
10813: doc---objects-method
10814: doc---objects-methods
10815: doc---objects-object
10816: doc---objects-overrides
10817: doc---objects-[parent]
10818: doc---objects-print
10819: doc---objects-protected
10820: doc---objects-public
10821: doc---objects-selector
10822: doc---objects-this
10823: doc---objects-<to-inst>
10824: doc---objects-[to-inst]
10825: doc---objects-to-this
10826: doc---objects-xt-new
10827: 
10828: 
10829: @c -------------------------------------------------------------
10830: @node OOF, Mini-OOF, Objects, Object-oriented Forth
10831: @subsection The @file{oof.fs} model
10832: @cindex oof
10833: @cindex object-oriented programming
10834: 
10835: @cindex @file{objects.fs}
10836: @cindex @file{oof.fs}
10837: 
10838: This section describes the @file{oof.fs} package.
10839: 
10840: The package described in this section has been used in bigFORTH since 1991, and
10841: used for two large applications: a chromatographic system used to
10842: create new medicaments, and a graphic user interface library (MINOS).
10843: 
10844: You can find a description (in German) of @file{oof.fs} in @cite{Object
10845: oriented bigFORTH} by Bernd Paysan, published in @cite{Vierte Dimension}
10846: 10(2), 1994.
10847: 
10848: @menu
10849: * Properties of the OOF model::  
10850: * Basic OOF Usage::             
10851: * The OOF base class::          
10852: * Class Declaration::           
10853: * Class Implementation::        
10854: @end menu
10855: 
10856: @node Properties of the OOF model, Basic OOF Usage, OOF, OOF
10857: @subsubsection Properties of the @file{oof.fs} model
10858: @cindex @file{oof.fs} properties
10859: 
10860: @itemize @bullet
10861: @item
10862: This model combines object oriented programming with information
10863: hiding. It helps you writing large application, where scoping is
10864: necessary, because it provides class-oriented scoping.
10865: 
10866: @item
10867: Named objects, object pointers, and object arrays can be created,
10868: selector invocation uses the ``object selector'' syntax. Selector invocation
10869: to objects and/or selectors on the stack is a bit less convenient, but
10870: possible.
10871: 
10872: @item
10873: Selector invocation and instance variable usage of the active object is
10874: straightforward, since both make use of the active object.
10875: 
10876: @item
10877: Late binding is efficient and easy to use.
10878: 
10879: @item
10880: State-smart objects parse selectors. However, extensibility is provided
10881: using a (parsing) selector @code{postpone} and a selector @code{'}.
10882: 
10883: @item
10884: An implementation in ANS Forth is available.
10885: 
10886: @end itemize
10887: 
10888: 
10889: @node Basic OOF Usage, The OOF base class, Properties of the OOF model, OOF
10890: @subsubsection Basic @file{oof.fs} Usage
10891: @cindex @file{oof.fs} usage
10892: 
10893: This section uses the same example as for @code{objects} (@pxref{Basic Objects Usage}).
10894: 
10895: You can define a class for graphical objects like this:
10896: 
10897: @cindex @code{class} usage
10898: @cindex @code{class;} usage
10899: @cindex @code{method} usage
10900: @example
10901: object class graphical \ "object" is the parent class
10902:   method draw ( x y -- )
10903: class;
10904: @end example
10905: 
10906: This code defines a class @code{graphical} with an
10907: operation @code{draw}.  We can perform the operation
10908: @code{draw} on any @code{graphical} object, e.g.:
10909: 
10910: @example
10911: 100 100 t-rex draw
10912: @end example
10913: 
10914: @noindent
10915: where @code{t-rex} is an object or object pointer, created with e.g.
10916: @code{graphical : t-rex}.
10917: 
10918: @cindex abstract class
10919: How do we create a graphical object? With the present definitions,
10920: we cannot create a useful graphical object. The class
10921: @code{graphical} describes graphical objects in general, but not
10922: any concrete graphical object type (C++ users would call it an
10923: @emph{abstract class}); e.g., there is no method for the selector
10924: @code{draw} in the class @code{graphical}.
10925: 
10926: For concrete graphical objects, we define child classes of the
10927: class @code{graphical}, e.g.:
10928: 
10929: @example
10930: graphical class circle \ "graphical" is the parent class
10931:   cell var circle-radius
10932: how:
10933:   : draw ( x y -- )
10934:     circle-radius @@ draw-circle ;
10935: 
10936:   : init ( n-radius -- )
10937:     circle-radius ! ;
10938: class;
10939: @end example
10940: 
10941: Here we define a class @code{circle} as a child of @code{graphical},
10942: with a field @code{circle-radius}; it defines new methods for the
10943: selectors @code{draw} and @code{init} (@code{init} is defined in
10944: @code{object}, the parent class of @code{graphical}).
10945: 
10946: Now we can create a circle in the dictionary with:
10947: 
10948: @example
10949: 50 circle : my-circle
10950: @end example
10951: 
10952: @noindent
10953: @code{:} invokes @code{init}, thus initializing the field
10954: @code{circle-radius} with 50. We can draw this new circle at (100,100)
10955: with:
10956: 
10957: @example
10958: 100 100 my-circle draw
10959: @end example
10960: 
10961: @cindex selector invocation, restrictions
10962: @cindex class definition, restrictions
10963: Note: You can only invoke a selector if the receiving object belongs to
10964: the class where the selector was defined or one of its descendents;
10965: e.g., you can invoke @code{draw} only for objects belonging to
10966: @code{graphical} or its descendents (e.g., @code{circle}). The scoping
10967: mechanism will check if you try to invoke a selector that is not
10968: defined in this class hierarchy, so you'll get an error at compilation
10969: time.
10970: 
10971: 
10972: @node The OOF base class, Class Declaration, Basic OOF Usage, OOF
10973: @subsubsection The @file{oof.fs} base class
10974: @cindex @file{oof.fs} base class
10975: 
10976: When you define a class, you have to specify a parent class.  So how do
10977: you start defining classes? There is one class available from the start:
10978: @code{object}. You have to use it as ancestor for all classes. It is the
10979: only class that has no parent. Classes are also objects, except that
10980: they don't have instance variables; class manipulation such as
10981: inheritance or changing definitions of a class is handled through
10982: selectors of the class @code{object}.
10983: 
10984: @code{object} provides a number of selectors:
10985: 
10986: @itemize @bullet
10987: @item
10988: @code{class} for subclassing, @code{definitions} to add definitions
10989: later on, and @code{class?} to get type informations (is the class a
10990: subclass of the class passed on the stack?).
10991: 
10992: doc---object-class
10993: doc---object-definitions
10994: doc---object-class?
10995: 
10996: 
10997: @item
10998: @code{init} and @code{dispose} as constructor and destructor of the
10999: object. @code{init} is invocated after the object's memory is allocated,
11000: while @code{dispose} also handles deallocation. Thus if you redefine
11001: @code{dispose}, you have to call the parent's dispose with @code{super
11002: dispose}, too.
11003: 
11004: doc---object-init
11005: doc---object-dispose
11006: 
11007: 
11008: @item
11009: @code{new}, @code{new[]}, @code{:}, @code{ptr}, @code{asptr}, and
11010: @code{[]} to create named and unnamed objects and object arrays or
11011: object pointers.
11012: 
11013: doc---object-new
11014: doc---object-new[]
11015: doc---object-:
11016: doc---object-ptr
11017: doc---object-asptr
11018: doc---object-[]
11019: 
11020: 
11021: @item
11022: @code{::} and @code{super} for explicit scoping. You should use explicit
11023: scoping only for super classes or classes with the same set of instance
11024: variables. Explicitly-scoped selectors use early binding.
11025: 
11026: doc---object-::
11027: doc---object-super
11028: 
11029: 
11030: @item
11031: @code{self} to get the address of the object
11032: 
11033: doc---object-self
11034: 
11035: 
11036: @item
11037: @code{bind}, @code{bound}, @code{link}, and @code{is} to assign object
11038: pointers and instance defers.
11039: 
11040: doc---object-bind
11041: doc---object-bound
11042: doc---object-link
11043: doc---object-is
11044: 
11045: 
11046: @item
11047: @code{'} to obtain selector tokens, @code{send} to invocate selectors
11048: form the stack, and @code{postpone} to generate selector invocation code.
11049: 
11050: doc---object-'
11051: doc---object-postpone
11052: 
11053: 
11054: @item
11055: @code{with} and @code{endwith} to select the active object from the
11056: stack, and enable its scope. Using @code{with} and @code{endwith}
11057: also allows you to create code using selector @code{postpone} without being
11058: trapped by the state-smart objects.
11059: 
11060: doc---object-with
11061: doc---object-endwith
11062: 
11063: 
11064: @end itemize
11065: 
11066: @node Class Declaration, Class Implementation, The OOF base class, OOF
11067: @subsubsection Class Declaration
11068: @cindex class declaration
11069: 
11070: @itemize @bullet
11071: @item
11072: Instance variables
11073: 
11074: doc---oof-var
11075: 
11076: 
11077: @item
11078: Object pointers
11079: 
11080: doc---oof-ptr
11081: doc---oof-asptr
11082: 
11083: 
11084: @item
11085: Instance defers
11086: 
11087: doc---oof-defer
11088: 
11089: 
11090: @item
11091: Method selectors
11092: 
11093: doc---oof-early
11094: doc---oof-method
11095: 
11096: 
11097: @item
11098: Class-wide variables
11099: 
11100: doc---oof-static
11101: 
11102: 
11103: @item
11104: End declaration
11105: 
11106: doc---oof-how:
11107: doc---oof-class;
11108: 
11109: 
11110: @end itemize
11111: 
11112: @c -------------------------------------------------------------
11113: @node Class Implementation,  , Class Declaration, OOF
11114: @subsubsection Class Implementation
11115: @cindex class implementation
11116: 
11117: @c -------------------------------------------------------------
11118: @node Mini-OOF, Comparison with other object models, OOF, Object-oriented Forth
11119: @subsection The @file{mini-oof.fs} model
11120: @cindex mini-oof
11121: 
11122: Gforth's third object oriented Forth package is a 12-liner. It uses a
11123: mixture of the @file{objects.fs} and the @file{oof.fs} syntax,
11124: and reduces to the bare minimum of features. This is based on a posting
11125: of Bernd Paysan in comp.lang.forth.
11126: 
11127: @menu
11128: * Basic Mini-OOF Usage::        
11129: * Mini-OOF Example::            
11130: * Mini-OOF Implementation::     
11131: @end menu
11132: 
11133: @c -------------------------------------------------------------
11134: @node Basic Mini-OOF Usage, Mini-OOF Example, Mini-OOF, Mini-OOF
11135: @subsubsection Basic @file{mini-oof.fs} Usage
11136: @cindex mini-oof usage
11137: 
11138: There is a base class (@code{class}, which allocates one cell for the
11139: object pointer) plus seven other words: to define a method, a variable,
11140: a class; to end a class, to resolve binding, to allocate an object and
11141: to compile a class method.
11142: @comment TODO better description of the last one
11143: 
11144: 
11145: doc-object
11146: doc-method
11147: doc-var
11148: doc-class
11149: doc-end-class
11150: doc-defines
11151: doc-new
11152: doc-::
11153: 
11154: 
11155: 
11156: @c -------------------------------------------------------------
11157: @node Mini-OOF Example, Mini-OOF Implementation, Basic Mini-OOF Usage, Mini-OOF
11158: @subsubsection Mini-OOF Example
11159: @cindex mini-oof example
11160: 
11161: A short example shows how to use this package. This example, in slightly
11162: extended form, is supplied as @file{moof-exm.fs}
11163: @comment TODO could flesh this out with some comments from the Forthwrite article
11164: 
11165: @example
11166: object class
11167:   method init
11168:   method draw
11169: end-class graphical
11170: @end example
11171: 
11172: This code defines a class @code{graphical} with an
11173: operation @code{draw}.  We can perform the operation
11174: @code{draw} on any @code{graphical} object, e.g.:
11175: 
11176: @example
11177: 100 100 t-rex draw
11178: @end example
11179: 
11180: where @code{t-rex} is an object or object pointer, created with e.g.
11181: @code{graphical new Constant t-rex}.
11182: 
11183: For concrete graphical objects, we define child classes of the
11184: class @code{graphical}, e.g.:
11185: 
11186: @example
11187: graphical class
11188:   cell var circle-radius
11189: end-class circle \ "graphical" is the parent class
11190: 
11191: :noname ( x y -- )
11192:   circle-radius @@ draw-circle ; circle defines draw
11193: :noname ( r -- )
11194:   circle-radius ! ; circle defines init
11195: @end example
11196: 
11197: There is no implicit init method, so we have to define one. The creation
11198: code of the object now has to call init explicitely.
11199: 
11200: @example
11201: circle new Constant my-circle
11202: 50 my-circle init
11203: @end example
11204: 
11205: It is also possible to add a function to create named objects with
11206: automatic call of @code{init}, given that all objects have @code{init}
11207: on the same place:
11208: 
11209: @example
11210: : new: ( .. o "name" -- )
11211:     new dup Constant init ;
11212: 80 circle new: large-circle
11213: @end example
11214: 
11215: We can draw this new circle at (100,100) with:
11216: 
11217: @example
11218: 100 100 my-circle draw
11219: @end example
11220: 
11221: @node Mini-OOF Implementation,  , Mini-OOF Example, Mini-OOF
11222: @subsubsection @file{mini-oof.fs} Implementation
11223: 
11224: Object-oriented systems with late binding typically use a
11225: ``vtable''-approach: the first variable in each object is a pointer to a
11226: table, which contains the methods as function pointers. The vtable
11227: may also contain other information.
11228: 
11229: So first, let's declare selectors:
11230: 
11231: @example
11232: : method ( m v "name" -- m' v ) Create  over , swap cell+ swap
11233:   DOES> ( ... o -- ... ) @@ over @@ + @@ execute ;
11234: @end example
11235: 
11236: During selector declaration, the number of selectors and instance
11237: variables is on the stack (in address units). @code{method} creates one
11238: selector and increments the selector number. To execute a selector, it
11239: takes the object, fetches the vtable pointer, adds the offset, and
11240: executes the method @i{xt} stored there. Each selector takes the object
11241: it is invoked with as top of stack parameter; it passes the parameters
11242: (including the object) unchanged to the appropriate method which should
11243: consume that object.
11244: 
11245: Now, we also have to declare instance variables
11246: 
11247: @example
11248: : var ( m v size "name" -- m v' ) Create  over , +
11249:   DOES> ( o -- addr ) @@ + ;
11250: @end example
11251: 
11252: As before, a word is created with the current offset. Instance
11253: variables can have different sizes (cells, floats, doubles, chars), so
11254: all we do is take the size and add it to the offset. If your machine
11255: has alignment restrictions, put the proper @code{aligned} or
11256: @code{faligned} before the variable, to adjust the variable
11257: offset. That's why it is on the top of stack.
11258: 
11259: We need a starting point (the base object) and some syntactic sugar:
11260: 
11261: @example
11262: Create object  1 cells , 2 cells ,
11263: : class ( class -- class selectors vars ) dup 2@@ ;
11264: @end example
11265: 
11266: For inheritance, the vtable of the parent object has to be
11267: copied when a new, derived class is declared. This gives all the
11268: methods of the parent class, which can be overridden, though.
11269: 
11270: @example
11271: : end-class  ( class selectors vars "name" -- )
11272:   Create  here >r , dup , 2 cells ?DO ['] noop , 1 cells +LOOP
11273:   cell+ dup cell+ r> rot @@ 2 cells /string move ;
11274: @end example
11275: 
11276: The first line creates the vtable, initialized with
11277: @code{noop}s. The second line is the inheritance mechanism, it
11278: copies the xts from the parent vtable.
11279: 
11280: We still have no way to define new methods, let's do that now:
11281: 
11282: @example
11283: : defines ( xt class "name" -- ) ' >body @@ + ! ;
11284: @end example
11285: 
11286: To allocate a new object, we need a word, too:
11287: 
11288: @example
11289: : new ( class -- o )  here over @@ allot swap over ! ;
11290: @end example
11291: 
11292: Sometimes derived classes want to access the method of the
11293: parent object. There are two ways to achieve this with Mini-OOF:
11294: first, you could use named words, and second, you could look up the
11295: vtable of the parent object.
11296: 
11297: @example
11298: : :: ( class "name" -- ) ' >body @@ + @@ compile, ;
11299: @end example
11300: 
11301: 
11302: Nothing can be more confusing than a good example, so here is
11303: one. First let's declare a text object (called
11304: @code{button}), that stores text and position:
11305: 
11306: @example
11307: object class
11308:   cell var text
11309:   cell var len
11310:   cell var x
11311:   cell var y
11312:   method init
11313:   method draw
11314: end-class button
11315: @end example
11316: 
11317: @noindent
11318: Now, implement the two methods, @code{draw} and @code{init}:
11319: 
11320: @example
11321: :noname ( o -- )
11322:  >r r@@ x @@ r@@ y @@ at-xy  r@@ text @@ r> len @@ type ;
11323:  button defines draw
11324: :noname ( addr u o -- )
11325:  >r 0 r@@ x ! 0 r@@ y ! r@@ len ! r> text ! ;
11326:  button defines init
11327: @end example
11328: 
11329: @noindent
11330: To demonstrate inheritance, we define a class @code{bold-button}, with no
11331: new data and no new selectors:
11332: 
11333: @example
11334: button class
11335: end-class bold-button
11336: 
11337: : bold   27 emit ." [1m" ;
11338: : normal 27 emit ." [0m" ;
11339: @end example
11340: 
11341: @noindent
11342: The class @code{bold-button} has a different draw method to
11343: @code{button}, but the new method is defined in terms of the draw method
11344: for @code{button}:
11345: 
11346: @example
11347: :noname bold [ button :: draw ] normal ; bold-button defines draw
11348: @end example
11349: 
11350: @noindent
11351: Finally, create two objects and apply selectors:
11352: 
11353: @example
11354: button new Constant foo
11355: s" thin foo" foo init
11356: page
11357: foo draw
11358: bold-button new Constant bar
11359: s" fat bar" bar init
11360: 1 bar y !
11361: bar draw
11362: @end example
11363: 
11364: 
11365: @node Comparison with other object models,  , Mini-OOF, Object-oriented Forth
11366: @subsection Comparison with other object models
11367: @cindex comparison of object models
11368: @cindex object models, comparison
11369: 
11370: Many object-oriented Forth extensions have been proposed (@cite{A survey
11371: of object-oriented Forths} (SIGPLAN Notices, April 1996) by Bradford
11372: J. Rodriguez and W. F. S. Poehlman lists 17). This section discusses the
11373: relation of the object models described here to two well-known and two
11374: closely-related (by the use of method maps) models.  Andras Zsoter
11375: helped us with this section.
11376: 
11377: @cindex Neon model
11378: The most popular model currently seems to be the Neon model (see
11379: @cite{Object-oriented programming in ANS Forth} (Forth Dimensions, March
11380: 1997) by Andrew McKewan) but this model has a number of limitations
11381: @footnote{A longer version of this critique can be
11382: found in @cite{On Standardizing Object-Oriented Forth Extensions} (Forth
11383: Dimensions, May 1997) by Anton Ertl.}:
11384: 
11385: @itemize @bullet
11386: @item
11387: It uses a @code{@emph{selector object}} syntax, which makes it unnatural
11388: to pass objects on the stack.
11389: 
11390: @item
11391: It requires that the selector parses the input stream (at
11392: compile time); this leads to reduced extensibility and to bugs that are
11393: hard to find.
11394: 
11395: @item
11396: It allows using every selector on every object; this eliminates the
11397: need for interfaces, but makes it harder to create efficient
11398: implementations.
11399: @end itemize
11400: 
11401: @cindex Pountain's object-oriented model
11402: Another well-known publication is @cite{Object-Oriented Forth} (Academic
11403: Press, London, 1987) by Dick Pountain. However, it is not really about
11404: object-oriented programming, because it hardly deals with late
11405: binding. Instead, it focuses on features like information hiding and
11406: overloading that are characteristic of modular languages like Ada (83).
11407: 
11408: @cindex Zsoter's object-oriented model
11409: In @uref{http://www.forth.org/oopf.html, Does late binding have to be
11410: slow?} (Forth Dimensions 18(1) 1996, pages 31-35) Andras Zsoter
11411: describes a model that makes heavy use of an active object (like
11412: @code{this} in @file{objects.fs}): The active object is not only used
11413: for accessing all fields, but also specifies the receiving object of
11414: every selector invocation; you have to change the active object
11415: explicitly with @code{@{ ... @}}, whereas in @file{objects.fs} it
11416: changes more or less implicitly at @code{m: ... ;m}. Such a change at
11417: the method entry point is unnecessary with Zsoter's model, because the
11418: receiving object is the active object already. On the other hand, the
11419: explicit change is absolutely necessary in that model, because otherwise
11420: no one could ever change the active object. An ANS Forth implementation
11421: of this model is available through
11422: @uref{http://www.forth.org/oopf.html}.
11423: 
11424: @cindex @file{oof.fs}, differences to other models
11425: The @file{oof.fs} model combines information hiding and overloading
11426: resolution (by keeping names in various word lists) with object-oriented
11427: programming. It sets the active object implicitly on method entry, but
11428: also allows explicit changing (with @code{>o...o>} or with
11429: @code{with...endwith}). It uses parsing and state-smart objects and
11430: classes for resolving overloading and for early binding: the object or
11431: class parses the selector and determines the method from this. If the
11432: selector is not parsed by an object or class, it performs a call to the
11433: selector for the active object (late binding), like Zsoter's model.
11434: Fields are always accessed through the active object. The big
11435: disadvantage of this model is the parsing and the state-smartness, which
11436: reduces extensibility and increases the opportunities for subtle bugs;
11437: essentially, you are only safe if you never tick or @code{postpone} an
11438: object or class (Bernd disagrees, but I (Anton) am not convinced).
11439: 
11440: @cindex @file{mini-oof.fs}, differences to other models
11441: The @file{mini-oof.fs} model is quite similar to a very stripped-down
11442: version of the @file{objects.fs} model, but syntactically it is a
11443: mixture of the @file{objects.fs} and @file{oof.fs} models.
11444: 
11445: 
11446: @c -------------------------------------------------------------
11447: @node Programming Tools, C Interface, Object-oriented Forth, Words
11448: @section Programming Tools
11449: @cindex programming tools
11450: 
11451: @c !! move this and assembler down below OO stuff.
11452: 
11453: @menu
11454: * Examining::                   Data and Code.
11455: * Forgetting words::            Usually before reloading.
11456: * Debugging::                   Simple and quick.
11457: * Assertions::                  Making your programs self-checking.
11458: * Singlestep Debugger::         Executing your program word by word.
11459: @end menu
11460: 
11461: @node Examining, Forgetting words, Programming Tools, Programming Tools
11462: @subsection Examining data and code
11463: @cindex examining data and code
11464: @cindex data examination
11465: @cindex code examination
11466: 
11467: The following words inspect the stack non-destructively:
11468: 
11469: doc-.s
11470: doc-f.s
11471: doc-maxdepth-.s
11472: 
11473: There is a word @code{.r} but it does @i{not} display the return stack!
11474: It is used for formatted numeric output (@pxref{Simple numeric output}).
11475: 
11476: doc-depth
11477: doc-fdepth
11478: doc-clearstack
11479: doc-clearstacks
11480: 
11481: The following words inspect memory.
11482: 
11483: doc-?
11484: doc-dump
11485: 
11486: And finally, @code{see} allows to inspect code:
11487: 
11488: doc-see
11489: doc-xt-see
11490: doc-simple-see
11491: doc-simple-see-range
11492: 
11493: @node Forgetting words, Debugging, Examining, Programming Tools
11494: @subsection Forgetting words
11495: @cindex words, forgetting
11496: @cindex forgeting words
11497: 
11498: @c  anton: other, maybe better places for this subsection: Defining Words;
11499: @c  Dictionary allocation.  At least a reference should be there.
11500: 
11501: Forth allows you to forget words (and everything that was alloted in the
11502: dictonary after them) in a LIFO manner.
11503: 
11504: doc-marker
11505: 
11506: The most common use of this feature is during progam development: when
11507: you change a source file, forget all the words it defined and load it
11508: again (since you also forget everything defined after the source file
11509: was loaded, you have to reload that, too).  Note that effects like
11510: storing to variables and destroyed system words are not undone when you
11511: forget words.  With a system like Gforth, that is fast enough at
11512: starting up and compiling, I find it more convenient to exit and restart
11513: Gforth, as this gives me a clean slate.
11514: 
11515: Here's an example of using @code{marker} at the start of a source file
11516: that you are debugging; it ensures that you only ever have one copy of
11517: the file's definitions compiled at any time:
11518: 
11519: @example
11520: [IFDEF] my-code
11521:     my-code
11522: [ENDIF]
11523: 
11524: marker my-code
11525: init-included-files
11526: 
11527: \ .. definitions start here
11528: \ .
11529: \ .
11530: \ end
11531: @end example
11532: 
11533: 
11534: @node Debugging, Assertions, Forgetting words, Programming Tools
11535: @subsection Debugging
11536: @cindex debugging
11537: 
11538: Languages with a slow edit/compile/link/test development loop tend to
11539: require sophisticated tracing/stepping debuggers to facilate debugging.
11540: 
11541: A much better (faster) way in fast-compiling languages is to add
11542: printing code at well-selected places, let the program run, look at
11543: the output, see where things went wrong, add more printing code, etc.,
11544: until the bug is found.
11545: 
11546: The simple debugging aids provided in @file{debugs.fs}
11547: are meant to support this style of debugging.
11548: 
11549: The word @code{~~} prints debugging information (by default the source
11550: location and the stack contents). It is easy to insert. If you use Emacs
11551: it is also easy to remove (@kbd{C-x ~} in the Emacs Forth mode to
11552: query-replace them with nothing). The deferred words
11553: @code{printdebugdata} and @code{.debugline} control the output of
11554: @code{~~}. The default source location output format works well with
11555: Emacs' compilation mode, so you can step through the program at the
11556: source level using @kbd{C-x `} (the advantage over a stepping debugger
11557: is that you can step in any direction and you know where the crash has
11558: happened or where the strange data has occurred).
11559: 
11560: doc-~~
11561: doc-printdebugdata
11562: doc-.debugline
11563: 
11564: @cindex filenames in @code{~~} output
11565: @code{~~} (and assertions) will usually print the wrong file name if a
11566: marker is executed in the same file after their occurance.  They will
11567: print @samp{*somewhere*} as file name if a marker is executed in the
11568: same file before their occurance.
11569: 
11570: 
11571: @node Assertions, Singlestep Debugger, Debugging, Programming Tools
11572: @subsection Assertions
11573: @cindex assertions
11574: 
11575: It is a good idea to make your programs self-checking, especially if you
11576: make an assumption that may become invalid during maintenance (for
11577: example, that a certain field of a data structure is never zero). Gforth
11578: supports @dfn{assertions} for this purpose. They are used like this:
11579: 
11580: @example
11581: assert( @i{flag} )
11582: @end example
11583: 
11584: The code between @code{assert(} and @code{)} should compute a flag, that
11585: should be true if everything is alright and false otherwise. It should
11586: not change anything else on the stack. The overall stack effect of the
11587: assertion is @code{( -- )}. E.g.
11588: 
11589: @example
11590: assert( 1 1 + 2 = ) \ what we learn in school
11591: assert( dup 0<> ) \ assert that the top of stack is not zero
11592: assert( false ) \ this code should not be reached
11593: @end example
11594: 
11595: The need for assertions is different at different times. During
11596: debugging, we want more checking, in production we sometimes care more
11597: for speed. Therefore, assertions can be turned off, i.e., the assertion
11598: becomes a comment. Depending on the importance of an assertion and the
11599: time it takes to check it, you may want to turn off some assertions and
11600: keep others turned on. Gforth provides several levels of assertions for
11601: this purpose:
11602: 
11603: 
11604: doc-assert0(
11605: doc-assert1(
11606: doc-assert2(
11607: doc-assert3(
11608: doc-assert(
11609: doc-)
11610: 
11611: 
11612: The variable @code{assert-level} specifies the highest assertions that
11613: are turned on. I.e., at the default @code{assert-level} of one,
11614: @code{assert0(} and @code{assert1(} assertions perform checking, while
11615: @code{assert2(} and @code{assert3(} assertions are treated as comments.
11616: 
11617: The value of @code{assert-level} is evaluated at compile-time, not at
11618: run-time. Therefore you cannot turn assertions on or off at run-time;
11619: you have to set the @code{assert-level} appropriately before compiling a
11620: piece of code. You can compile different pieces of code at different
11621: @code{assert-level}s (e.g., a trusted library at level 1 and
11622: newly-written code at level 3).
11623: 
11624: 
11625: doc-assert-level
11626: 
11627: 
11628: If an assertion fails, a message compatible with Emacs' compilation mode
11629: is produced and the execution is aborted (currently with @code{ABORT"}.
11630: If there is interest, we will introduce a special throw code. But if you
11631: intend to @code{catch} a specific condition, using @code{throw} is
11632: probably more appropriate than an assertion).
11633: 
11634: @cindex filenames in assertion output
11635: Assertions (and @code{~~}) will usually print the wrong file name if a
11636: marker is executed in the same file after their occurance.  They will
11637: print @samp{*somewhere*} as file name if a marker is executed in the
11638: same file before their occurance.
11639: 
11640: Definitions in ANS Forth for these assertion words are provided
11641: in @file{compat/assert.fs}.
11642: 
11643: 
11644: @node Singlestep Debugger,  , Assertions, Programming Tools
11645: @subsection Singlestep Debugger
11646: @cindex singlestep Debugger
11647: @cindex debugging Singlestep
11648: 
11649: The singlestep debugger works only with the engine @code{gforth-ditc}.
11650: 
11651: When you create a new word there's often the need to check whether it
11652: behaves correctly or not. You can do this by typing @code{dbg
11653: badword}. A debug session might look like this:
11654: 
11655: @example
11656: : badword 0 DO i . LOOP ;  ok
11657: 2 dbg badword 
11658: : badword  
11659: Scanning code...
11660: 
11661: Nesting debugger ready!
11662: 
11663: 400D4738  8049BC4 0              -> [ 2 ] 00002 00000 
11664: 400D4740  8049F68 DO             -> [ 0 ] 
11665: 400D4744  804A0C8 i              -> [ 1 ] 00000 
11666: 400D4748 400C5E60 .              -> 0 [ 0 ] 
11667: 400D474C  8049D0C LOOP           -> [ 0 ] 
11668: 400D4744  804A0C8 i              -> [ 1 ] 00001 
11669: 400D4748 400C5E60 .              -> 1 [ 0 ] 
11670: 400D474C  8049D0C LOOP           -> [ 0 ] 
11671: 400D4758  804B384 ;              ->  ok
11672: @end example
11673: 
11674: Each line displayed is one step. You always have to hit return to
11675: execute the next word that is displayed. If you don't want to execute
11676: the next word in a whole, you have to type @kbd{n} for @code{nest}. Here is
11677: an overview what keys are available:
11678: 
11679: @table @i
11680: 
11681: @item @key{RET}
11682: Next; Execute the next word.
11683: 
11684: @item n
11685: Nest; Single step through next word.
11686: 
11687: @item u
11688: Unnest; Stop debugging and execute rest of word. If we got to this word
11689: with nest, continue debugging with the calling word.
11690: 
11691: @item d
11692: Done; Stop debugging and execute rest.
11693: 
11694: @item s
11695: Stop; Abort immediately.
11696: 
11697: @end table
11698: 
11699: Debugging large application with this mechanism is very difficult, because
11700: you have to nest very deeply into the program before the interesting part
11701: begins. This takes a lot of time. 
11702: 
11703: To do it more directly put a @code{BREAK:} command into your source code.
11704: When program execution reaches @code{BREAK:} the single step debugger is
11705: invoked and you have all the features described above.
11706: 
11707: If you have more than one part to debug it is useful to know where the
11708: program has stopped at the moment. You can do this by the 
11709: @code{BREAK" string"} command. This behaves like @code{BREAK:} except that
11710: string is typed out when the ``breakpoint'' is reached.
11711: 
11712: 
11713: doc-dbg
11714: doc-break:
11715: doc-break"
11716: 
11717: @c ------------------------------------------------------------
11718: @node C Interface, Assembler and Code Words, Programming Tools, Words
11719: @section C Interface
11720: @cindex C interface
11721: @cindex foreign language interface
11722: @cindex interface to C functions
11723: 
11724: Note that the C interface is not yet complete; a better way of
11725: declaring C functions is planned, as well as a way of declaring
11726: structs, unions, and their fields.
11727: 
11728: @menu
11729: * Calling C Functions::         
11730: * Declaring C Functions::       
11731: * Callbacks::                   
11732: * Low-Level C Interface Words::  
11733: @end menu
11734: 
11735: @node Calling C Functions, Declaring C Functions, C Interface, C Interface
11736: @subsection Calling C functions
11737: @cindex C functions, calls to
11738: @cindex calling C functions
11739: 
11740: Once a C function is declared (see @pxref{Declaring C Functions}), you
11741: can call it as follows: You push the arguments on the stack(s), and
11742: then call the word for the C function.  The arguments have to be
11743: pushed in the same order as the arguments appear in the C
11744: documentation (i.e., the first argument is deepest on the stack).
11745: Integer and pointer arguments have to be pushed on the data stack,
11746: floating-point arguments on the FP stack; these arguments are consumed
11747: by the called C function.
11748: 
11749: On returning from the C function, the return value, if any, resides on
11750: the appropriate stack: an integer return value is pushed on the data
11751: stack, an FP return value on the FP stack, and a void return value
11752: results in not pushing anything.  Note that most C functions have a
11753: return value, even if that is often not used in C; in Forth, you have
11754: to @code{drop} this return value explicitly if you do not use it.
11755: 
11756: By default, an integer argument or return value corresponds to a
11757: single cell, and a floating-point argument or return value corresponds
11758: to a Forth float value; the C interface performs the appropriate
11759: conversions where necessary, on a best-effort basis (in some cases,
11760: there may be some loss).
11761: 
11762: As an example, consider the POSIX function @code{lseek()}:
11763: 
11764: @example
11765: off_t lseek(int fd, off_t offset, int whence);
11766: @end example
11767: 
11768: This function takes three integer arguments, and returns an integer
11769: argument, so a Forth call for setting the current file offset to the
11770: start of the file could look like this:
11771: 
11772: @example
11773: fd @@ 0 SEEK_SET lseek -1 = if
11774:   ... \ error handling
11775: then
11776: @end example
11777: 
11778: You might be worried that an @code{off_t} does not fit into a cell, so
11779: you could not pass larger offsets to lseek, and might get only a part
11780: of the return values.  In that case, in your declaration of the
11781: function (@pxref{Declaring C Functions}) you should declare it to use
11782: double-cells for the off_t argument and return value, and maybe give
11783: the resulting Forth word a different name, like @code{dlseek}; the
11784: result could be called like this:
11785: 
11786: @example
11787: fd @@ 0. SEEK_SET dlseek -1. d= if
11788:   ... \ error handling
11789: then
11790: @end example
11791: 
11792: Passing and returning structs or unions is currently not supported by
11793: our interface@footnote{If you know the calling convention of your C
11794: compiler, you usually can call such functions in some way, but that
11795: way is usually not portable between platforms, and sometimes not even
11796: between C compilers.}.
11797: 
11798: Calling functions with a variable number of arguments (e.g.,
11799: @code{printf()}) is currently only supported by having you declare one
11800: function-calling word for each argument pattern, and calling the
11801: appropriate word for the desired pattern.
11802: 
11803: 
11804: @node Declaring C Functions, Callbacks, Calling C Functions, C Interface
11805: @subsection Declaring C Functions
11806: @cindex C functions, declarations
11807: @cindex declaring C functions
11808: 
11809: Before you can call @code{lseek} or @code{dlseek}, you have to declare
11810: it.  You have to look up in your system what the concrete type for the
11811: abstract type @code{off_t} is; let's assume it is @code{long}.  Then
11812: the declarations for these words are:
11813: 
11814: @example
11815: library libc libc.so.6
11816: libc lseek  int  long int  (long) lseek ( fd noffset whence -- noffset2 )
11817: libc dlseek int dlong int (dlong) lseek ( fd doffset whence -- doffset2 ) 
11818: @end example
11819: 
11820: The first line defines a Forth word @code{libc} for accessing the C
11821: functions in the shared library @file{libc.so.6} (the name of the
11822: shared library depends on the library and the OS; this example is the
11823: standard C library (containing most of the standard C and Unix
11824: functions) for GNU/Linux systems since about 1998).
11825: 
11826: The next two lines define two Forth words for the same C function
11827: @code{lseek()}; the middle line defines @code{lseek ( n1 n2 n3 -- n
11828: )}, and the last line defines @code{dlseek ( n1 d2 n3 -- d )}.
11829: 
11830: As you can see, the declarations are relatively platform-dependent
11831: (e.g., on one platform @code{off_t} may be a @code{long}, whereas on
11832: another platform it may be a @code{long long}; actually, in this case
11833: you can have this difference even on the same platform), while the
11834: resulting function-calling words are platform-independent, and calls
11835: to them are portable.
11836: 
11837: At some point in the future this interface will be superseded by a
11838: more convenient one with fewer portability issues.  But the resulting
11839: words for calling the C function will still have the same interface,
11840: so you will not need to change the calls.
11841: 
11842: Anyway, here are the words for the current interface:
11843: 
11844: doc-library
11845: doc-int
11846: doc-dint
11847: doc-uint
11848: doc-udint
11849: doc-long
11850: doc-dlong
11851: doc-ulong
11852: doc-udlong
11853: doc-longlong
11854: doc-dlonglong
11855: doc-ulonglong
11856: doc-udlonglong
11857: doc-ptr
11858: doc-cfloat
11859: doc-cdouble
11860: doc-clongdouble
11861: doc-(int)
11862: doc-(dint)
11863: doc-(uint)
11864: doc-(udint)
11865: doc-(long)
11866: doc-(dlong)
11867: doc-(ulong)
11868: doc-(udlong)
11869: doc-(longlong)
11870: doc-(dlonglong)
11871: doc-(ulonglong)
11872: doc-(udlonglong)
11873: doc-(ptr)
11874: doc-(cfloat)
11875: doc-(cdouble)
11876: doc-(clongdouble)
11877: 
11878: 
11879: @node Callbacks, Low-Level C Interface Words, Declaring C Functions, C Interface
11880: @subsection Callbacks
11881: @cindex Callback functions written in Forth
11882: @cindex C function pointers to Forth words
11883: 
11884: In some cases you have to pass a function pointer to a C function,
11885: i.e., the library wants to call back to your application (and the
11886: pointed-to function is called a callback function).  You can pass the
11887: address of an existing C function (that you get with @code{lib-sym},
11888: @pxref{Low-Level C Interface Words}), but if there is no appropriate C
11889: function, you probably want to define the function as a Forth word.
11890: 
11891: !!!
11892: @c I don't understand the existing callback interface from the example - anton
11893: 
11894: doc-callback
11895: doc-callback;
11896: doc-fptr
11897: 
11898: 
11899: @c > > Und dann gibt's noch die fptr-Deklaration, die einem
11900: @c > > C-Funktionspointer entspricht (Deklaration gleich wie bei
11901: @c > > Library-Funktionen, nur ohne den C-Namen, Aufruf mit der
11902: @c > > C-Funktionsadresse auf dem TOS).
11903: @c >
11904: @c > Ja, da bin ich dann ausgestiegen, weil ich aus dem Beispiel nicht
11905: @c > gesehen habe, wozu das gut ist.
11906: @c 
11907: @c Irgendwie muss ich den Callback ja testen. Und es soll ja auch 
11908: @c vorkommen, dass man von irgendwelchen kranken Interfaces einen 
11909: @c Funktionspointer übergeben bekommt, den man dann bei Gelegenheit 
11910: @c aufrufen muss. Also kann man den deklarieren, und das damit deklarierte 
11911: @c Wort verhält sich dann wie ein EXECUTE für alle C-Funktionen mit 
11912: @c demselben Prototyp.
11913: 
11914: 
11915: @node Low-Level C Interface Words,  , Callbacks, C Interface
11916: @subsection Low-Level C Interface Words
11917: 
11918: doc-open-lib
11919: doc-lib-sym
11920: 
11921: @c -------------------------------------------------------------
11922: @node Assembler and Code Words, Threading Words, C Interface, Words
11923: @section Assembler and Code Words
11924: @cindex assembler
11925: @cindex code words
11926: 
11927: @menu
11928: * Code and ;code::              
11929: * Common Assembler::            Assembler Syntax
11930: * Common Disassembler::         
11931: * 386 Assembler::               Deviations and special cases
11932: * Alpha Assembler::             Deviations and special cases
11933: * MIPS assembler::              Deviations and special cases
11934: * PowerPC assembler::           Deviations and special cases
11935: * Other assemblers::            How to write them
11936: @end menu
11937: 
11938: @node Code and ;code, Common Assembler, Assembler and Code Words, Assembler and Code Words
11939: @subsection @code{Code} and @code{;code}
11940: 
11941: Gforth provides some words for defining primitives (words written in
11942: machine code), and for defining the machine-code equivalent of
11943: @code{DOES>}-based defining words. However, the machine-independent
11944: nature of Gforth poses a few problems: First of all, Gforth runs on
11945: several architectures, so it can provide no standard assembler. What's
11946: worse is that the register allocation not only depends on the processor,
11947: but also on the @code{gcc} version and options used.
11948: 
11949: The words that Gforth offers encapsulate some system dependences (e.g.,
11950: the header structure), so a system-independent assembler may be used in
11951: Gforth. If you do not have an assembler, you can compile machine code
11952: directly with @code{,} and @code{c,}@footnote{This isn't portable,
11953: because these words emit stuff in @i{data} space; it works because
11954: Gforth has unified code/data spaces. Assembler isn't likely to be
11955: portable anyway.}.
11956: 
11957: 
11958: doc-assembler
11959: doc-init-asm
11960: doc-code
11961: doc-end-code
11962: doc-;code
11963: doc-flush-icache
11964: 
11965: 
11966: If @code{flush-icache} does not work correctly, @code{code} words
11967: etc. will not work (reliably), either.
11968: 
11969: The typical usage of these @code{code} words can be shown most easily by
11970: analogy to the equivalent high-level defining words:
11971: 
11972: @example
11973: : foo                              code foo
11974:    <high-level Forth words>              <assembler>
11975: ;                                  end-code
11976:                                 
11977: : bar                              : bar
11978:    <high-level Forth words>           <high-level Forth words>
11979:    CREATE                             CREATE
11980:       <high-level Forth words>           <high-level Forth words>
11981:    DOES>                              ;code
11982:       <high-level Forth words>           <assembler>
11983: ;                                  end-code
11984: @end example
11985: 
11986: @c anton: the following stuff is also in "Common Assembler", in less detail.
11987: 
11988: @cindex registers of the inner interpreter
11989: In the assembly code you will want to refer to the inner interpreter's
11990: registers (e.g., the data stack pointer) and you may want to use other
11991: registers for temporary storage. Unfortunately, the register allocation
11992: is installation-dependent.
11993: 
11994: In particular, @code{ip} (Forth instruction pointer) and @code{rp}
11995: (return stack pointer) may be in different places in @code{gforth} and
11996: @code{gforth-fast}, or different installations.  This means that you
11997: cannot write a @code{NEXT} routine that works reliably on both versions
11998: or different installations; so for doing @code{NEXT}, I recommend
11999: jumping to @code{' noop >code-address}, which contains nothing but a
12000: @code{NEXT}.
12001: 
12002: For general accesses to the inner interpreter's registers, the easiest
12003: solution is to use explicit register declarations (@pxref{Explicit Reg
12004: Vars, , Variables in Specified Registers, gcc.info, GNU C Manual}) for
12005: all of the inner interpreter's registers: You have to compile Gforth
12006: with @code{-DFORCE_REG} (configure option @code{--enable-force-reg}) and
12007: the appropriate declarations must be present in the @code{machine.h}
12008: file (see @code{mips.h} for an example; you can find a full list of all
12009: declarable register symbols with @code{grep register engine.c}). If you
12010: give explicit registers to all variables that are declared at the
12011: beginning of @code{engine()}, you should be able to use the other
12012: caller-saved registers for temporary storage. Alternatively, you can use
12013: the @code{gcc} option @code{-ffixed-REG} (@pxref{Code Gen Options, ,
12014: Options for Code Generation Conventions, gcc.info, GNU C Manual}) to
12015: reserve a register (however, this restriction on register allocation may
12016: slow Gforth significantly).
12017: 
12018: If this solution is not viable (e.g., because @code{gcc} does not allow
12019: you to explicitly declare all the registers you need), you have to find
12020: out by looking at the code where the inner interpreter's registers
12021: reside and which registers can be used for temporary storage. You can
12022: get an assembly listing of the engine's code with @code{make engine.s}.
12023: 
12024: In any case, it is good practice to abstract your assembly code from the
12025: actual register allocation. E.g., if the data stack pointer resides in
12026: register @code{$17}, create an alias for this register called @code{sp},
12027: and use that in your assembly code.
12028: 
12029: @cindex code words, portable
12030: Another option for implementing normal and defining words efficiently
12031: is to add the desired functionality to the source of Gforth. For normal
12032: words you just have to edit @file{primitives} (@pxref{Automatic
12033: Generation}). Defining words (equivalent to @code{;CODE} words, for fast
12034: defined words) may require changes in @file{engine.c}, @file{kernel.fs},
12035: @file{prims2x.fs}, and possibly @file{cross.fs}.
12036: 
12037: @node Common Assembler, Common Disassembler, Code and ;code, Assembler and Code Words
12038: @subsection Common Assembler
12039: 
12040: The assemblers in Gforth generally use a postfix syntax, i.e., the
12041: instruction name follows the operands.
12042: 
12043: The operands are passed in the usual order (the same that is used in the
12044: manual of the architecture).  Since they all are Forth words, they have
12045: to be separated by spaces; you can also use Forth words to compute the
12046: operands.
12047: 
12048: The instruction names usually end with a @code{,}.  This makes it easier
12049: to visually separate instructions if you put several of them on one
12050: line; it also avoids shadowing other Forth words (e.g., @code{and}).
12051: 
12052: Registers are usually specified by number; e.g., (decimal) @code{11}
12053: specifies registers R11 and F11 on the Alpha architecture (which one,
12054: depends on the instruction).  The usual names are also available, e.g.,
12055: @code{s2} for R11 on Alpha.
12056: 
12057: Control flow is specified similar to normal Forth code (@pxref{Arbitrary
12058: control structures}), with @code{if,}, @code{ahead,}, @code{then,},
12059: @code{begin,}, @code{until,}, @code{again,}, @code{cs-roll},
12060: @code{cs-pick}, @code{else,}, @code{while,}, and @code{repeat,}.  The
12061: conditions are specified in a way specific to each assembler.
12062: 
12063: Note that the register assignments of the Gforth engine can change
12064: between Gforth versions, or even between different compilations of the
12065: same Gforth version (e.g., if you use a different GCC version).  So if
12066: you want to refer to Gforth's registers (e.g., the stack pointer or
12067: TOS), I recommend defining your own words for refering to these
12068: registers, and using them later on; then you can easily adapt to a
12069: changed register assignment.  The stability of the register assignment
12070: is usually better if you build Gforth with @code{--enable-force-reg}.
12071: 
12072: The most common use of these registers is to dispatch to the next word
12073: (the @code{next} routine).  A portable way to do this is to jump to
12074: @code{' noop >code-address} (of course, this is less efficient than
12075: integrating the @code{next} code and scheduling it well).
12076: 
12077: Another difference between Gforth version is that the top of stack is
12078: kept in memory in @code{gforth} and, on most platforms, in a register in
12079: @code{gforth-fast}.
12080: 
12081: @node  Common Disassembler, 386 Assembler, Common Assembler, Assembler and Code Words
12082: @subsection Common Disassembler
12083: @cindex disassembler, general
12084: @cindex gdb disassembler
12085: 
12086: You can disassemble a @code{code} word with @code{see}
12087: (@pxref{Debugging}).  You can disassemble a section of memory with
12088: 
12089: doc-discode
12090: 
12091: There are two kinds of disassembler for Gforth: The Forth disassembler
12092: (available on some CPUs) and the gdb disassembler (available on
12093: platforms with @command{gdb} and @command{mktemp}).  If both are
12094: available, the Forth disassembler is used by default.  If you prefer
12095: the gdb disassembler, say
12096: 
12097: @example
12098: ' disasm-gdb is discode
12099: @end example
12100: 
12101: If neither is available, @code{discode} performs @code{dump}.
12102: 
12103: The Forth disassembler generally produces output that can be fed into the
12104: assembler (i.e., same syntax, etc.).  It also includes additional
12105: information in comments.  In particular, the address of the instruction
12106: is given in a comment before the instruction.
12107: 
12108: The gdb disassembler produces output in the same format as the gdb
12109: @code{disassemble} command (@pxref{Machine Code,,Source and machine
12110: code,gdb,Debugging with GDB}), in the default flavour (AT&T syntax for
12111: the 386 and AMD64 architectures).
12112: 
12113: @code{See} may display more or less than the actual code of the word,
12114: because the recognition of the end of the code is unreliable.  You can
12115: use @code{discode} if it did not display enough.  It may display more, if
12116: the code word is not immediately followed by a named word.  If you have
12117: something else there, you can follow the word with @code{align latest ,}
12118: to ensure that the end is recognized.
12119: 
12120: @node 386 Assembler, Alpha Assembler, Common Disassembler, Assembler and Code Words
12121: @subsection 386 Assembler
12122: 
12123: The 386 assembler included in Gforth was written by Bernd Paysan, it's
12124: available under GPL, and originally part of bigFORTH.
12125: 
12126: The 386 disassembler included in Gforth was written by Andrew McKewan
12127: and is in the public domain.
12128: 
12129: The disassembler displays code in an Intel-like prefix syntax.
12130: 
12131: The assembler uses a postfix syntax with reversed parameters.
12132: 
12133: The assembler includes all instruction of the Athlon, i.e. 486 core
12134: instructions, Pentium and PPro extensions, floating point, MMX, 3Dnow!,
12135: but not ISSE. It's an integrated 16- and 32-bit assembler. Default is 32
12136: bit, you can switch to 16 bit with .86 and back to 32 bit with .386.
12137: 
12138: There are several prefixes to switch between different operation sizes,
12139: @code{.b} for byte accesses, @code{.w} for word accesses, @code{.d} for
12140: double-word accesses. Addressing modes can be switched with @code{.wa}
12141: for 16 bit addresses, and @code{.da} for 32 bit addresses. You don't
12142: need a prefix for byte register names (@code{AL} et al).
12143: 
12144: For floating point operations, the prefixes are @code{.fs} (IEEE
12145: single), @code{.fl} (IEEE double), @code{.fx} (extended), @code{.fw}
12146: (word), @code{.fd} (double-word), and @code{.fq} (quad-word).
12147: 
12148: The MMX opcodes don't have size prefixes, they are spelled out like in
12149: the Intel assembler. Instead of move from and to memory, there are
12150: PLDQ/PLDD and PSTQ/PSTD.
12151: 
12152: The registers lack the 'e' prefix; even in 32 bit mode, eax is called
12153: ax.  Immediate values are indicated by postfixing them with @code{#},
12154: e.g., @code{3 #}.  Here are some examples of addressing modes in various
12155: syntaxes:
12156: 
12157: @example
12158: Gforth          Intel (NASM)   AT&T (gas)      Name
12159: .w ax           ax             %ax             register (16 bit)
12160: ax              eax            %eax            register (32 bit)
12161: 3 #             offset 3       $3              immediate
12162: 1000 #)         byte ptr 1000  1000            displacement
12163: bx )            [ebx]          (%ebx)          base
12164: 100 di d)       100[edi]       100(%edi)       base+displacement
12165: 20 ax *4 i#)    20[eax*4]      20(,%eax,4)     (index*scale)+displacement
12166: di ax *4 i)     [edi][eax*4]   (%edi,%eax,4)   base+(index*scale)
12167: 4 bx cx di)     4[ebx][ecx]    4(%ebx,%ecx)    base+index+displacement
12168: 12 sp ax *2 di) 12[esp][eax*2] 12(%esp,%eax,2) base+(index*scale)+displacement
12169: @end example
12170: 
12171: You can use @code{L)} and @code{LI)} instead of @code{D)} and
12172: @code{DI)} to enforce 32-bit displacement fields (useful for
12173: later patching).
12174: 
12175: Some example of instructions are:
12176: 
12177: @example
12178: ax bx mov             \ move ebx,eax
12179: 3 # ax mov            \ mov eax,3
12180: 100 di d) ax mov      \ mov eax,100[edi]
12181: 4 bx cx di) ax mov    \ mov eax,4[ebx][ecx]
12182: .w ax bx mov          \ mov bx,ax
12183: @end example
12184: 
12185: The following forms are supported for binary instructions:
12186: 
12187: @example
12188: <reg> <reg> <inst>
12189: <n> # <reg> <inst>
12190: <mem> <reg> <inst>
12191: <reg> <mem> <inst>
12192: <n> # <mem> <inst>
12193: @end example
12194: 
12195: The shift/rotate syntax is:
12196: 
12197: @example
12198: <reg/mem> 1 # shl \ shortens to shift without immediate
12199: <reg/mem> 4 # shl
12200: <reg/mem> cl shl
12201: @end example
12202: 
12203: Precede string instructions (@code{movs} etc.) with @code{.b} to get
12204: the byte version.
12205: 
12206: The control structure words @code{IF} @code{UNTIL} etc. must be preceded
12207: by one of these conditions: @code{vs vc u< u>= 0= 0<> u<= u> 0< 0>= ps
12208: pc < >= <= >}. (Note that most of these words shadow some Forth words
12209: when @code{assembler} is in front of @code{forth} in the search path,
12210: e.g., in @code{code} words).  Currently the control structure words use
12211: one stack item, so you have to use @code{roll} instead of @code{cs-roll}
12212: to shuffle them (you can also use @code{swap} etc.).
12213: 
12214: Here is an example of a @code{code} word (assumes that the stack pointer
12215: is in esi and the TOS is in ebx):
12216: 
12217: @example
12218: code my+ ( n1 n2 -- n )
12219:     4 si D) bx add
12220:     4 # si add
12221:     Next
12222: end-code
12223: @end example
12224: 
12225: 
12226: @node Alpha Assembler, MIPS assembler, 386 Assembler, Assembler and Code Words
12227: @subsection Alpha Assembler
12228: 
12229: The Alpha assembler and disassembler were originally written by Bernd
12230: Thallner.
12231: 
12232: The register names @code{a0}--@code{a5} are not available to avoid
12233: shadowing hex numbers.
12234: 
12235: Immediate forms of arithmetic instructions are distinguished by a
12236: @code{#} just before the @code{,}, e.g., @code{and#,} (note: @code{lda,}
12237: does not count as arithmetic instruction).
12238: 
12239: You have to specify all operands to an instruction, even those that
12240: other assemblers consider optional, e.g., the destination register for
12241: @code{br,}, or the destination register and hint for @code{jmp,}.
12242: 
12243: You can specify conditions for @code{if,} by removing the first @code{b}
12244: and the trailing @code{,} from a branch with a corresponding name; e.g.,
12245: 
12246: @example
12247: 11 fgt if, \ if F11>0e
12248:   ...
12249: endif,
12250: @end example
12251: 
12252: @code{fbgt,} gives @code{fgt}.  
12253: 
12254: @node MIPS assembler, PowerPC assembler, Alpha Assembler, Assembler and Code Words
12255: @subsection MIPS assembler
12256: 
12257: The MIPS assembler was originally written by Christian Pirker.
12258: 
12259: Currently the assembler and disassembler only cover the MIPS-I
12260: architecture (R3000), and don't support FP instructions.
12261: 
12262: The register names @code{$a0}--@code{$a3} are not available to avoid
12263: shadowing hex numbers.
12264: 
12265: Because there is no way to distinguish registers from immediate values,
12266: you have to explicitly use the immediate forms of instructions, i.e.,
12267: @code{addiu,}, not just @code{addu,} (@command{as} does this
12268: implicitly).
12269: 
12270: If the architecture manual specifies several formats for the instruction
12271: (e.g., for @code{jalr,}), you usually have to use the one with more
12272: arguments (i.e., two for @code{jalr,}).  When in doubt, see
12273: @code{arch/mips/testasm.fs} for an example of correct use.
12274: 
12275: Branches and jumps in the MIPS architecture have a delay slot.  You have
12276: to fill it yourself (the simplest way is to use @code{nop,}), the
12277: assembler does not do it for you (unlike @command{as}).  Even
12278: @code{if,}, @code{ahead,}, @code{until,}, @code{again,}, @code{while,},
12279: @code{else,} and @code{repeat,} need a delay slot.  Since @code{begin,}
12280: and @code{then,} just specify branch targets, they are not affected.
12281: 
12282: Note that you must not put branches, jumps, or @code{li,} into the delay
12283: slot: @code{li,} may expand to several instructions, and control flow
12284: instructions may not be put into the branch delay slot in any case.
12285: 
12286: For branches the argument specifying the target is a relative address;
12287: You have to add the address of the delay slot to get the absolute
12288: address.
12289: 
12290: The MIPS architecture also has load delay slots and restrictions on
12291: using @code{mfhi,} and @code{mflo,}; you have to order the instructions
12292: yourself to satisfy these restrictions, the assembler does not do it for
12293: you.
12294: 
12295: You can specify the conditions for @code{if,} etc. by taking a
12296: conditional branch and leaving away the @code{b} at the start and the
12297: @code{,} at the end.  E.g.,
12298: 
12299: @example
12300: 4 5 eq if,
12301:   ... \ do something if $4 equals $5
12302: then,
12303: @end example
12304: 
12305: 
12306: @node PowerPC assembler, Other assemblers, MIPS assembler, Assembler and Code Words
12307: @subsection PowerPC assembler
12308: 
12309: The PowerPC assembler and disassembler were contributed by Michal
12310: Revucky.
12311: 
12312: This assembler does not follow the convention of ending mnemonic names
12313: with a ``,'', so some mnemonic names shadow regular Forth words (in
12314: particular: @code{and or xor fabs}); so if you want to use the Forth
12315: words, you have to make them visible first, e.g., with @code{also
12316: forth}.
12317: 
12318: Registers are referred to by their number, e.g., @code{9} means the
12319: integer register 9 or the FP register 9 (depending on the
12320: instruction).
12321: 
12322: Because there is no way to distinguish registers from immediate values,
12323: you have to explicitly use the immediate forms of instructions, i.e.,
12324: @code{addi,}, not just @code{add,}.
12325: 
12326: The assembler and disassembler usually support the most general form
12327: of an instruction, but usually not the shorter forms (especially for
12328: branches).
12329: 
12330: 
12331: 
12332: @node Other assemblers,  , PowerPC assembler, Assembler and Code Words
12333: @subsection Other assemblers
12334: 
12335: If you want to contribute another assembler/disassembler, please contact
12336: us (@email{anton@@mips.complang.tuwien.ac.at}) to check if we have such
12337: an assembler already.  If you are writing them from scratch, please use
12338: a similar syntax style as the one we use (i.e., postfix, commas at the
12339: end of the instruction names, @pxref{Common Assembler}); make the output
12340: of the disassembler be valid input for the assembler, and keep the style
12341: similar to the style we used.
12342: 
12343: Hints on implementation: The most important part is to have a good test
12344: suite that contains all instructions.  Once you have that, the rest is
12345: easy.  For actual coding you can take a look at
12346: @file{arch/mips/disasm.fs} to get some ideas on how to use data for both
12347: the assembler and disassembler, avoiding redundancy and some potential
12348: bugs.  You can also look at that file (and @pxref{Advanced does> usage
12349: example}) to get ideas how to factor a disassembler.
12350: 
12351: Start with the disassembler, because it's easier to reuse data from the
12352: disassembler for the assembler than the other way round.
12353: 
12354: For the assembler, take a look at @file{arch/alpha/asm.fs}, which shows
12355: how simple it can be.
12356: 
12357: 
12358: 
12359: 
12360: @c -------------------------------------------------------------
12361: @node Threading Words, Passing Commands to the OS, Assembler and Code Words, Words
12362: @section Threading Words
12363: @cindex threading words
12364: 
12365: @cindex code address
12366: These words provide access to code addresses and other threading stuff
12367: in Gforth (and, possibly, other interpretive Forths). It more or less
12368: abstracts away the differences between direct and indirect threading
12369: (and, for direct threading, the machine dependences). However, at
12370: present this wordset is still incomplete. It is also pretty low-level;
12371: some day it will hopefully be made unnecessary by an internals wordset
12372: that abstracts implementation details away completely.
12373: 
12374: The terminology used here stems from indirect threaded Forth systems; in
12375: such a system, the XT of a word is represented by the CFA (code field
12376: address) of a word; the CFA points to a cell that contains the code
12377: address.  The code address is the address of some machine code that
12378: performs the run-time action of invoking the word (e.g., the
12379: @code{dovar:} routine pushes the address of the body of the word (a
12380: variable) on the stack
12381: ).
12382: 
12383: @cindex code address
12384: @cindex code field address
12385: In an indirect threaded Forth, you can get the code address of @i{name}
12386: with @code{' @i{name} @@}; in Gforth you can get it with @code{' @i{name}
12387: >code-address}, independent of the threading method.
12388: 
12389: doc-threading-method
12390: doc->code-address
12391: doc-code-address!
12392: 
12393: @cindex @code{does>}-handler
12394: @cindex @code{does>}-code
12395: For a word defined with @code{DOES>}, the code address usually points to
12396: a jump instruction (the @dfn{does-handler}) that jumps to the dodoes
12397: routine (in Gforth on some platforms, it can also point to the dodoes
12398: routine itself).  What you are typically interested in, though, is
12399: whether a word is a @code{DOES>}-defined word, and what Forth code it
12400: executes; @code{>does-code} tells you that.
12401: 
12402: doc->does-code
12403: 
12404: To create a @code{DOES>}-defined word with the following basic words,
12405: you have to set up a @code{DOES>}-handler with @code{does-handler!};
12406: @code{/does-handler} aus behind you have to place your executable Forth
12407: code.  Finally you have to create a word and modify its behaviour with
12408: @code{does-handler!}.
12409: 
12410: doc-does-code!
12411: doc-does-handler!
12412: doc-/does-handler
12413: 
12414: The code addresses produced by various defining words are produced by
12415: the following words:
12416: 
12417: doc-docol:
12418: doc-docon:
12419: doc-dovar:
12420: doc-douser:
12421: doc-dodefer:
12422: doc-dofield:
12423: 
12424: @cindex definer
12425: The following two words generalize @code{>code-address},
12426: @code{>does-code}, @code{code-address!}, and @code{does-code!}:
12427: 
12428: doc->definer
12429: doc-definer!
12430: 
12431: @c -------------------------------------------------------------
12432: @node Passing Commands to the OS, Keeping track of Time, Threading Words, Words
12433: @section Passing Commands to the Operating System
12434: @cindex operating system - passing commands
12435: @cindex shell commands
12436: 
12437: Gforth allows you to pass an arbitrary string to the host operating
12438: system shell (if such a thing exists) for execution.
12439: 
12440: doc-sh
12441: doc-system
12442: doc-$?
12443: doc-getenv
12444: 
12445: @c -------------------------------------------------------------
12446: @node Keeping track of Time, Miscellaneous Words, Passing Commands to the OS, Words
12447: @section Keeping track of Time
12448: @cindex time-related words
12449: 
12450: doc-ms
12451: doc-time&date
12452: doc-utime
12453: doc-cputime
12454: 
12455: 
12456: @c -------------------------------------------------------------
12457: @node Miscellaneous Words,  , Keeping track of Time, Words
12458: @section Miscellaneous Words
12459: @cindex miscellaneous words
12460: 
12461: @comment TODO find homes for these
12462: 
12463: These section lists the ANS Forth words that are not documented
12464: elsewhere in this manual. Ultimately, they all need proper homes.
12465: 
12466: doc-quit
12467: 
12468: The following ANS Forth words are not currently supported by Gforth 
12469: (@pxref{ANS conformance}):
12470: 
12471: @code{EDITOR} 
12472: @code{EMIT?} 
12473: @code{FORGET} 
12474: 
12475: @c ******************************************************************
12476: @node Error messages, Tools, Words, Top
12477: @chapter Error messages
12478: @cindex error messages
12479: @cindex backtrace
12480: 
12481: A typical Gforth error message looks like this:
12482: 
12483: @example
12484: in file included from \evaluated string/:-1
12485: in file included from ./yyy.fs:1
12486: ./xxx.fs:4: Invalid memory address
12487: >>>bar<<<
12488: Backtrace:
12489: $400E664C @@
12490: $400E6664 foo
12491: @end example
12492: 
12493: The message identifying the error is @code{Invalid memory address}.  The
12494: error happened when text-interpreting line 4 of the file
12495: @file{./xxx.fs}. This line is given (it contains @code{bar}), and the
12496: word on the line where the error happened, is pointed out (with
12497: @code{>>>} and @code{<<<}).
12498: 
12499: The file containing the error was included in line 1 of @file{./yyy.fs},
12500: and @file{yyy.fs} was included from a non-file (in this case, by giving
12501: @file{yyy.fs} as command-line parameter to Gforth).
12502: 
12503: At the end of the error message you find a return stack dump that can be
12504: interpreted as a backtrace (possibly empty). On top you find the top of
12505: the return stack when the @code{throw} happened, and at the bottom you
12506: find the return stack entry just above the return stack of the topmost
12507: text interpreter.
12508: 
12509: To the right of most return stack entries you see a guess for the word
12510: that pushed that return stack entry as its return address. This gives a
12511: backtrace. In our case we see that @code{bar} called @code{foo}, and
12512: @code{foo} called @code{@@} (and @code{@@} had an @emph{Invalid memory
12513: address} exception).
12514: 
12515: Note that the backtrace is not perfect: We don't know which return stack
12516: entries are return addresses (so we may get false positives); and in
12517: some cases (e.g., for @code{abort"}) we cannot determine from the return
12518: address the word that pushed the return address, so for some return
12519: addresses you see no names in the return stack dump.
12520: 
12521: @cindex @code{catch} and backtraces
12522: The return stack dump represents the return stack at the time when a
12523: specific @code{throw} was executed.  In programs that make use of
12524: @code{catch}, it is not necessarily clear which @code{throw} should be
12525: used for the return stack dump (e.g., consider one @code{throw} that
12526: indicates an error, which is caught, and during recovery another error
12527: happens; which @code{throw} should be used for the stack dump?).
12528: Gforth presents the return stack dump for the first @code{throw} after
12529: the last executed (not returned-to) @code{catch} or @code{nothrow};
12530: this works well in the usual case. To get the right backtrace, you
12531: usually want to insert @code{nothrow} or @code{['] false catch drop}
12532: after a @code{catch} if the error is not rethrown.
12533: 
12534: @cindex @code{gforth-fast} and backtraces
12535: @cindex @code{gforth-fast}, difference from @code{gforth}
12536: @cindex backtraces with @code{gforth-fast}
12537: @cindex return stack dump with @code{gforth-fast}
12538: @code{Gforth} is able to do a return stack dump for throws generated
12539: from primitives (e.g., invalid memory address, stack empty etc.);
12540: @code{gforth-fast} is only able to do a return stack dump from a
12541: directly called @code{throw} (including @code{abort} etc.).  Given an
12542: exception caused by a primitive in @code{gforth-fast}, you will
12543: typically see no return stack dump at all; however, if the exception is
12544: caught by @code{catch} (e.g., for restoring some state), and then
12545: @code{throw}n again, the return stack dump will be for the first such
12546: @code{throw}.
12547: 
12548: @c ******************************************************************
12549: @node Tools, ANS conformance, Error messages, Top
12550: @chapter Tools
12551: 
12552: @menu
12553: * ANS Report::                  Report the words used, sorted by wordset.
12554: * Stack depth changes::         Where does this stack item come from?
12555: @end menu
12556: 
12557: See also @ref{Emacs and Gforth}.
12558: 
12559: @node ANS Report, Stack depth changes, Tools, Tools
12560: @section @file{ans-report.fs}: Report the words used, sorted by wordset
12561: @cindex @file{ans-report.fs}
12562: @cindex report the words used in your program
12563: @cindex words used in your program
12564: 
12565: If you want to label a Forth program as ANS Forth Program, you must
12566: document which wordsets the program uses; for extension wordsets, it is
12567: helpful to list the words the program requires from these wordsets
12568: (because Forth systems are allowed to provide only some words of them).
12569: 
12570: The @file{ans-report.fs} tool makes it easy for you to determine which
12571: words from which wordset and which non-ANS words your application
12572: uses. You simply have to include @file{ans-report.fs} before loading the
12573: program you want to check. After loading your program, you can get the
12574: report with @code{print-ans-report}. A typical use is to run this as
12575: batch job like this:
12576: @example
12577: gforth ans-report.fs myprog.fs -e "print-ans-report bye"
12578: @end example
12579: 
12580: The output looks like this (for @file{compat/control.fs}):
12581: @example
12582: The program uses the following words
12583: from CORE :
12584: : POSTPONE THEN ; immediate ?dup IF 0= 
12585: from BLOCK-EXT :
12586: \ 
12587: from FILE :
12588: ( 
12589: @end example
12590: 
12591: @subsection Caveats
12592: 
12593: Note that @file{ans-report.fs} just checks which words are used, not whether
12594: they are used in an ANS Forth conforming way!
12595: 
12596: Some words are defined in several wordsets in the
12597: standard. @file{ans-report.fs} reports them for only one of the
12598: wordsets, and not necessarily the one you expect. It depends on usage
12599: which wordset is the right one to specify. E.g., if you only use the
12600: compilation semantics of @code{S"}, it is a Core word; if you also use
12601: its interpretation semantics, it is a File word.
12602: 
12603: 
12604: @node Stack depth changes,  , ANS Report, Tools
12605: @section Stack depth changes during interpretation
12606: @cindex @file{depth-changes.fs}
12607: @cindex depth changes during interpretation
12608: @cindex stack depth changes during interpretation
12609: @cindex items on the stack after interpretation
12610: 
12611: Sometimes you notice that, after loading a file, there are items left
12612: on the stack.  The tool @file{depth-changes.fs} helps you find out
12613: quickly where in the file these stack items are coming from.
12614: 
12615: The simplest way of using @file{depth-changes.fs} is to include it
12616: before the file(s) you want to check, e.g.:
12617: 
12618: @example
12619: gforth depth-changes.fs my-file.fs
12620: @end example
12621: 
12622: This will compare the stack depths of the data and FP stack at every
12623: empty line (in interpretation state) against these depths at the last
12624: empty line (in interpretation state).  If the depths are not equal,
12625: the position in the file and the stack contents are printed with
12626: @code{~~} (@pxref{Debugging}).  This indicates that a stack depth
12627: change has occured in the paragraph of non-empty lines before the
12628: indicated line.  It is a good idea to leave an empty line at the end
12629: of the file, so the last paragraph is checked, too.
12630: 
12631: Checking only at empty lines usually works well, but sometimes you
12632: have big blocks of non-empty lines (e.g., when building a big table),
12633: and you want to know where in this block the stack depth changed.  You
12634: can check all interpreted lines with
12635: 
12636: @example
12637: gforth depth-changes.fs -e "' all-lines is depth-changes-filter" my-file.fs
12638: @end example
12639: 
12640: This checks the stack depth at every end-of-line.  So the depth change
12641: occured in the line reported by the @code{~~} (not in the line
12642: before).
12643: 
12644: Note that, while this offers better accuracy in indicating where the
12645: stack depth changes, it will often report many intentional stack depth
12646: changes (e.g., when an interpreted computation stretches across
12647: several lines).  You can suppress the checking of some lines by
12648: putting backslashes at the end of these lines (not followed by white
12649: space), and using
12650: 
12651: @example
12652: gforth depth-changes.fs -e "' most-lines is depth-changes-filter" my-file.fs
12653: @end example
12654: 
12655: @c ******************************************************************
12656: @node ANS conformance, Standard vs Extensions, Tools, Top
12657: @chapter ANS conformance
12658: @cindex ANS conformance of Gforth
12659: 
12660: To the best of our knowledge, Gforth is an
12661: 
12662: ANS Forth System
12663: @itemize @bullet
12664: @item providing the Core Extensions word set
12665: @item providing the Block word set
12666: @item providing the Block Extensions word set
12667: @item providing the Double-Number word set
12668: @item providing the Double-Number Extensions word set
12669: @item providing the Exception word set
12670: @item providing the Exception Extensions word set
12671: @item providing the Facility word set
12672: @item providing @code{EKEY}, @code{EKEY>CHAR}, @code{EKEY?}, @code{MS} and @code{TIME&DATE} from the Facility Extensions word set
12673: @item providing the File Access word set
12674: @item providing the File Access Extensions word set
12675: @item providing the Floating-Point word set
12676: @item providing the Floating-Point Extensions word set
12677: @item providing the Locals word set
12678: @item providing the Locals Extensions word set
12679: @item providing the Memory-Allocation word set
12680: @item providing the Memory-Allocation Extensions word set (that one's easy)
12681: @item providing the Programming-Tools word set
12682: @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
12683: @item providing the Search-Order word set
12684: @item providing the Search-Order Extensions word set
12685: @item providing the String word set
12686: @item providing the String Extensions word set (another easy one)
12687: @end itemize
12688: 
12689: Gforth has the following environmental restrictions:
12690: 
12691: @cindex environmental restrictions
12692: @itemize @bullet
12693: @item
12694: While processing the OS command line, if an exception is not caught,
12695: Gforth exits with a non-zero exit code instyead of performing QUIT.
12696: 
12697: @item
12698: When an @code{throw} is performed after a @code{query}, Gforth does not
12699: allways restore the input source specification in effect at the
12700: corresponding catch.
12701: 
12702: @end itemize
12703: 
12704: 
12705: @cindex system documentation
12706: In addition, ANS Forth systems are required to document certain
12707: implementation choices. This chapter tries to meet these
12708: requirements. In many cases it gives a way to ask the system for the
12709: information instead of providing the information directly, in
12710: particular, if the information depends on the processor, the operating
12711: system or the installation options chosen, or if they are likely to
12712: change during the maintenance of Gforth.
12713: 
12714: @comment The framework for the rest has been taken from pfe.
12715: 
12716: @menu
12717: * The Core Words::              
12718: * The optional Block word set::  
12719: * The optional Double Number word set::  
12720: * The optional Exception word set::  
12721: * The optional Facility word set::  
12722: * The optional File-Access word set::  
12723: * The optional Floating-Point word set::  
12724: * The optional Locals word set::  
12725: * The optional Memory-Allocation word set::  
12726: * The optional Programming-Tools word set::  
12727: * The optional Search-Order word set::  
12728: @end menu
12729: 
12730: 
12731: @c =====================================================================
12732: @node The Core Words, The optional Block word set, ANS conformance, ANS conformance
12733: @comment  node-name,  next,  previous,  up
12734: @section The Core Words
12735: @c =====================================================================
12736: @cindex core words, system documentation
12737: @cindex system documentation, core words
12738: 
12739: @menu
12740: * core-idef::                   Implementation Defined Options                   
12741: * core-ambcond::                Ambiguous Conditions                
12742: * core-other::                  Other System Documentation                  
12743: @end menu
12744: 
12745: @c ---------------------------------------------------------------------
12746: @node core-idef, core-ambcond, The Core Words, The Core Words
12747: @subsection Implementation Defined Options
12748: @c ---------------------------------------------------------------------
12749: @cindex core words, implementation-defined options
12750: @cindex implementation-defined options, core words
12751: 
12752: 
12753: @table @i
12754: @item (Cell) aligned addresses:
12755: @cindex cell-aligned addresses
12756: @cindex aligned addresses
12757: processor-dependent. Gforth's alignment words perform natural alignment
12758: (e.g., an address aligned for a datum of size 8 is divisible by
12759: 8). Unaligned accesses usually result in a @code{-23 THROW}.
12760: 
12761: @item @code{EMIT} and non-graphic characters:
12762: @cindex @code{EMIT} and non-graphic characters
12763: @cindex non-graphic characters and @code{EMIT}
12764: The character is output using the C library function (actually, macro)
12765: @code{putc}.
12766: 
12767: @item character editing of @code{ACCEPT} and @code{EXPECT}:
12768: @cindex character editing of @code{ACCEPT} and @code{EXPECT}
12769: @cindex editing in @code{ACCEPT} and @code{EXPECT}
12770: @cindex @code{ACCEPT}, editing
12771: @cindex @code{EXPECT}, editing
12772: This is modeled on the GNU readline library (@pxref{Readline
12773: Interaction, , Command Line Editing, readline, The GNU Readline
12774: Library}) with Emacs-like key bindings. @kbd{Tab} deviates a little by
12775: producing a full word completion every time you type it (instead of
12776: producing the common prefix of all completions). @xref{Command-line editing}.
12777: 
12778: @item character set:
12779: @cindex character set
12780: The character set of your computer and display device. Gforth is
12781: 8-bit-clean (but some other component in your system may make trouble).
12782: 
12783: @item Character-aligned address requirements:
12784: @cindex character-aligned address requirements
12785: installation-dependent. Currently a character is represented by a C
12786: @code{unsigned char}; in the future we might switch to @code{wchar_t}
12787: (Comments on that requested).
12788: 
12789: @item character-set extensions and matching of names:
12790: @cindex character-set extensions and matching of names
12791: @cindex case-sensitivity for name lookup
12792: @cindex name lookup, case-sensitivity
12793: @cindex locale and case-sensitivity
12794: Any character except the ASCII NUL character can be used in a
12795: name. Matching is case-insensitive (except in @code{TABLE}s). The
12796: matching is performed using the C library function @code{strncasecmp}, whose
12797: function is probably influenced by the locale. E.g., the @code{C} locale
12798: does not know about accents and umlauts, so they are matched
12799: case-sensitively in that locale. For portability reasons it is best to
12800: write programs such that they work in the @code{C} locale. Then one can
12801: use libraries written by a Polish programmer (who might use words
12802: containing ISO Latin-2 encoded characters) and by a French programmer
12803: (ISO Latin-1) in the same program (of course, @code{WORDS} will produce
12804: funny results for some of the words (which ones, depends on the font you
12805: are using)). Also, the locale you prefer may not be available in other
12806: operating systems. Hopefully, Unicode will solve these problems one day.
12807: 
12808: @item conditions under which control characters match a space delimiter:
12809: @cindex space delimiters
12810: @cindex control characters as delimiters
12811: If @code{word} is called with the space character as a delimiter, all
12812: white-space characters (as identified by the C macro @code{isspace()})
12813: are delimiters. @code{Parse}, on the other hand, treats space like other
12814: delimiters.  @code{Parse-name}, which is used by the outer
12815: interpreter (aka text interpreter) by default, treats all white-space
12816: characters as delimiters.
12817: 
12818: @item format of the control-flow stack:
12819: @cindex control-flow stack, format
12820: The data stack is used as control-flow stack. The size of a control-flow
12821: stack item in cells is given by the constant @code{cs-item-size}. At the
12822: time of this writing, an item consists of a (pointer to a) locals list
12823: (third), an address in the code (second), and a tag for identifying the
12824: item (TOS). The following tags are used: @code{defstart},
12825: @code{live-orig}, @code{dead-orig}, @code{dest}, @code{do-dest},
12826: @code{scopestart}.
12827: 
12828: @item conversion of digits > 35
12829: @cindex digits > 35
12830: The characters @code{[\]^_'} are the digits with the decimal value
12831: 36@minus{}41. There is no way to input many of the larger digits.
12832: 
12833: @item display after input terminates in @code{ACCEPT} and @code{EXPECT}:
12834: @cindex @code{EXPECT}, display after end of input
12835: @cindex @code{ACCEPT}, display after end of input
12836: The cursor is moved to the end of the entered string. If the input is
12837: terminated using the @kbd{Return} key, a space is typed.
12838: 
12839: @item exception abort sequence of @code{ABORT"}:
12840: @cindex exception abort sequence of @code{ABORT"}
12841: @cindex @code{ABORT"}, exception abort sequence
12842: The error string is stored into the variable @code{"error} and a
12843: @code{-2 throw} is performed.
12844: 
12845: @item input line terminator:
12846: @cindex input line terminator
12847: @cindex line terminator on input
12848: @cindex newline character on input
12849: For interactive input, @kbd{C-m} (CR) and @kbd{C-j} (LF) terminate
12850: lines. One of these characters is typically produced when you type the
12851: @kbd{Enter} or @kbd{Return} key.
12852: 
12853: @item maximum size of a counted string:
12854: @cindex maximum size of a counted string
12855: @cindex counted string, maximum size
12856: @code{s" /counted-string" environment? drop .}. Currently 255 characters
12857: on all platforms, but this may change.
12858: 
12859: @item maximum size of a parsed string:
12860: @cindex maximum size of a parsed string
12861: @cindex parsed string, maximum size
12862: Given by the constant @code{/line}. Currently 255 characters.
12863: 
12864: @item maximum size of a definition name, in characters:
12865: @cindex maximum size of a definition name, in characters
12866: @cindex name, maximum length
12867: MAXU/8
12868: 
12869: @item maximum string length for @code{ENVIRONMENT?}, in characters:
12870: @cindex maximum string length for @code{ENVIRONMENT?}, in characters
12871: @cindex @code{ENVIRONMENT?} string length, maximum
12872: MAXU/8
12873: 
12874: @item method of selecting the user input device:
12875: @cindex user input device, method of selecting
12876: The user input device is the standard input. There is currently no way to
12877: change it from within Gforth. However, the input can typically be
12878: redirected in the command line that starts Gforth.
12879: 
12880: @item method of selecting the user output device:
12881: @cindex user output device, method of selecting
12882: @code{EMIT} and @code{TYPE} output to the file-id stored in the value
12883: @code{outfile-id} (@code{stdout} by default). Gforth uses unbuffered
12884: output when the user output device is a terminal, otherwise the output
12885: is buffered.
12886: 
12887: @item methods of dictionary compilation:
12888: What are we expected to document here?
12889: 
12890: @item number of bits in one address unit:
12891: @cindex number of bits in one address unit
12892: @cindex address unit, size in bits
12893: @code{s" address-units-bits" environment? drop .}. 8 in all current
12894: platforms.
12895: 
12896: @item number representation and arithmetic:
12897: @cindex number representation and arithmetic
12898: Processor-dependent. Binary two's complement on all current platforms.
12899: 
12900: @item ranges for integer types:
12901: @cindex ranges for integer types
12902: @cindex integer types, ranges
12903: Installation-dependent. Make environmental queries for @code{MAX-N},
12904: @code{MAX-U}, @code{MAX-D} and @code{MAX-UD}. The lower bounds for
12905: unsigned (and positive) types is 0. The lower bound for signed types on
12906: two's complement and one's complement machines machines can be computed
12907: by adding 1 to the upper bound.
12908: 
12909: @item read-only data space regions:
12910: @cindex read-only data space regions
12911: @cindex data-space, read-only regions
12912: The whole Forth data space is writable.
12913: 
12914: @item size of buffer at @code{WORD}:
12915: @cindex size of buffer at @code{WORD}
12916: @cindex @code{WORD} buffer size
12917: @code{PAD HERE - .}. 104 characters on 32-bit machines. The buffer is
12918: shared with the pictured numeric output string. If overwriting
12919: @code{PAD} is acceptable, it is as large as the remaining dictionary
12920: space, although only as much can be sensibly used as fits in a counted
12921: string.
12922: 
12923: @item size of one cell in address units:
12924: @cindex cell size
12925: @code{1 cells .}.
12926: 
12927: @item size of one character in address units:
12928: @cindex char size
12929: @code{1 chars .}. 1 on all current platforms.
12930: 
12931: @item size of the keyboard terminal buffer:
12932: @cindex size of the keyboard terminal buffer
12933: @cindex terminal buffer, size
12934: Varies. You can determine the size at a specific time using @code{lp@@
12935: tib - .}. It is shared with the locals stack and TIBs of files that
12936: include the current file. You can change the amount of space for TIBs
12937: and locals stack at Gforth startup with the command line option
12938: @code{-l}.
12939: 
12940: @item size of the pictured numeric output buffer:
12941: @cindex size of the pictured numeric output buffer
12942: @cindex pictured numeric output buffer, size
12943: @code{PAD HERE - .}. 104 characters on 32-bit machines. The buffer is
12944: shared with @code{WORD}.
12945: 
12946: @item size of the scratch area returned by @code{PAD}:
12947: @cindex size of the scratch area returned by @code{PAD}
12948: @cindex @code{PAD} size
12949: The remainder of dictionary space. @code{unused pad here - - .}.
12950: 
12951: @item system case-sensitivity characteristics:
12952: @cindex case-sensitivity characteristics
12953: Dictionary searches are case-insensitive (except in
12954: @code{TABLE}s). However, as explained above under @i{character-set
12955: extensions}, the matching for non-ASCII characters is determined by the
12956: locale you are using. In the default @code{C} locale all non-ASCII
12957: characters are matched case-sensitively.
12958: 
12959: @item system prompt:
12960: @cindex system prompt
12961: @cindex prompt
12962: @code{ ok} in interpret state, @code{ compiled} in compile state.
12963: 
12964: @item division rounding:
12965: @cindex division rounding
12966: The ordinary division words @code{/ mod /mod */ */mod} perform floored
12967: division (with the default installation of Gforth).  You can check
12968: this with @code{s" floored" environment? drop .}.  If you write
12969: programs that need a specific division rounding, best use
12970: @code{fm/mod} or @code{sm/rem} for portability.
12971: 
12972: @item values of @code{STATE} when true:
12973: @cindex @code{STATE} values
12974: -1.
12975: 
12976: @item values returned after arithmetic overflow:
12977: On two's complement machines, arithmetic is performed modulo
12978: 2**bits-per-cell for single arithmetic and 4**bits-per-cell for double
12979: arithmetic (with appropriate mapping for signed types). Division by
12980: zero typically results in a @code{-55 throw} (Floating-point
12981: unidentified fault) or @code{-10 throw} (divide by zero).  Integer
12982: division overflow can result in these throws, or in @code{-11 throw};
12983: in @code{gforth-fast} division overflow and divide by zero may also
12984: result in returning bogus results without producing an exception.
12985: 
12986: @item whether the current definition can be found after @t{DOES>}:
12987: @cindex @t{DOES>}, visibility of current definition
12988: No.
12989: 
12990: @end table
12991: 
12992: @c ---------------------------------------------------------------------
12993: @node core-ambcond, core-other, core-idef, The Core Words
12994: @subsection Ambiguous conditions
12995: @c ---------------------------------------------------------------------
12996: @cindex core words, ambiguous conditions
12997: @cindex ambiguous conditions, core words
12998: 
12999: @table @i
13000: 
13001: @item a name is neither a word nor a number:
13002: @cindex name not found
13003: @cindex undefined word
13004: @code{-13 throw} (Undefined word).
13005: 
13006: @item a definition name exceeds the maximum length allowed:
13007: @cindex word name too long
13008: @code{-19 throw} (Word name too long)
13009: 
13010: @item addressing a region not inside the various data spaces of the forth system:
13011: @cindex Invalid memory address
13012: The stacks, code space and header space are accessible. Machine code space is
13013: typically readable. Accessing other addresses gives results dependent on
13014: the operating system. On decent systems: @code{-9 throw} (Invalid memory
13015: address).
13016: 
13017: @item argument type incompatible with parameter:
13018: @cindex argument type mismatch
13019: This is usually not caught. Some words perform checks, e.g., the control
13020: flow words, and issue a @code{ABORT"} or @code{-12 THROW} (Argument type
13021: mismatch).
13022: 
13023: @item attempting to obtain the execution token of a word with undefined execution semantics:
13024: @cindex Interpreting a compile-only word, for @code{'} etc.
13025: @cindex execution token of words with undefined execution semantics
13026: @code{-14 throw} (Interpreting a compile-only word). In some cases, you
13027: get an execution token for @code{compile-only-error} (which performs a
13028: @code{-14 throw} when executed).
13029: 
13030: @item dividing by zero:
13031: @cindex dividing by zero
13032: @cindex floating point unidentified fault, integer division
13033: On some platforms, this produces a @code{-10 throw} (Division by
13034: zero); on other systems, this typically results in a @code{-55 throw}
13035: (Floating-point unidentified fault).
13036: 
13037: @item insufficient data stack or return stack space:
13038: @cindex insufficient data stack or return stack space
13039: @cindex stack overflow
13040: @cindex address alignment exception, stack overflow
13041: @cindex Invalid memory address, stack overflow
13042: Depending on the operating system, the installation, and the invocation
13043: of Gforth, this is either checked by the memory management hardware, or
13044: it is not checked. If it is checked, you typically get a @code{-3 throw}
13045: (Stack overflow), @code{-5 throw} (Return stack overflow), or @code{-9
13046: throw} (Invalid memory address) (depending on the platform and how you
13047: achieved the overflow) as soon as the overflow happens. If it is not
13048: checked, overflows typically result in mysterious illegal memory
13049: accesses, producing @code{-9 throw} (Invalid memory address) or
13050: @code{-23 throw} (Address alignment exception); they might also destroy
13051: the internal data structure of @code{ALLOCATE} and friends, resulting in
13052: various errors in these words.
13053: 
13054: @item insufficient space for loop control parameters:
13055: @cindex insufficient space for loop control parameters
13056: Like other return stack overflows.
13057: 
13058: @item insufficient space in the dictionary:
13059: @cindex insufficient space in the dictionary
13060: @cindex dictionary overflow
13061: If you try to allot (either directly with @code{allot}, or indirectly
13062: with @code{,}, @code{create} etc.) more memory than available in the
13063: dictionary, you get a @code{-8 throw} (Dictionary overflow). If you try
13064: to access memory beyond the end of the dictionary, the results are
13065: similar to stack overflows.
13066: 
13067: @item interpreting a word with undefined interpretation semantics:
13068: @cindex interpreting a word with undefined interpretation semantics
13069: @cindex Interpreting a compile-only word
13070: For some words, we have defined interpretation semantics. For the
13071: others: @code{-14 throw} (Interpreting a compile-only word).
13072: 
13073: @item modifying the contents of the input buffer or a string literal:
13074: @cindex modifying the contents of the input buffer or a string literal
13075: These are located in writable memory and can be modified.
13076: 
13077: @item overflow of the pictured numeric output string:
13078: @cindex overflow of the pictured numeric output string
13079: @cindex pictured numeric output string, overflow
13080: @code{-17 throw} (Pictured numeric ouput string overflow).
13081: 
13082: @item parsed string overflow:
13083: @cindex parsed string overflow
13084: @code{PARSE} cannot overflow. @code{WORD} does not check for overflow.
13085: 
13086: @item producing a result out of range:
13087: @cindex result out of range
13088: On two's complement machines, arithmetic is performed modulo
13089: 2**bits-per-cell for single arithmetic and 4**bits-per-cell for double
13090: arithmetic (with appropriate mapping for signed types). Division by
13091: zero typically results in a @code{-10 throw} (divide by zero) or
13092: @code{-55 throw} (floating point unidentified fault). Overflow on
13093: division may result in these errors or in @code{-11 throw} (result out
13094: of range).  @code{Gforth-fast} may silently produce bogus results on
13095: division overflow or division by zero.  @code{Convert} and
13096: @code{>number} currently overflow silently.
13097: 
13098: @item reading from an empty data or return stack:
13099: @cindex stack empty
13100: @cindex stack underflow
13101: @cindex return stack underflow
13102: The data stack is checked by the outer (aka text) interpreter after
13103: every word executed. If it has underflowed, a @code{-4 throw} (Stack
13104: underflow) is performed. Apart from that, stacks may be checked or not,
13105: depending on operating system, installation, and invocation. If they are
13106: caught by a check, they typically result in @code{-4 throw} (Stack
13107: underflow), @code{-6 throw} (Return stack underflow) or @code{-9 throw}
13108: (Invalid memory address), depending on the platform and which stack
13109: underflows and by how much. Note that even if the system uses checking
13110: (through the MMU), your program may have to underflow by a significant
13111: number of stack items to trigger the reaction (the reason for this is
13112: that the MMU, and therefore the checking, works with a page-size
13113: granularity).  If there is no checking, the symptoms resulting from an
13114: underflow are similar to those from an overflow.  Unbalanced return
13115: stack errors can result in a variety of symptoms, including @code{-9 throw}
13116: (Invalid memory address) and Illegal Instruction (typically @code{-260
13117: throw}).
13118: 
13119: @item unexpected end of the input buffer, resulting in an attempt to use a zero-length string as a name:
13120: @cindex unexpected end of the input buffer
13121: @cindex zero-length string as a name
13122: @cindex Attempt to use zero-length string as a name
13123: @code{Create} and its descendants perform a @code{-16 throw} (Attempt to
13124: use zero-length string as a name). Words like @code{'} probably will not
13125: find what they search. Note that it is possible to create zero-length
13126: names with @code{nextname} (should it not?).
13127: 
13128: @item @code{>IN} greater than input buffer:
13129: @cindex @code{>IN} greater than input buffer
13130: The next invocation of a parsing word returns a string with length 0.
13131: 
13132: @item @code{RECURSE} appears after @code{DOES>}:
13133: @cindex @code{RECURSE} appears after @code{DOES>}
13134: Compiles a recursive call to the defining word, not to the defined word.
13135: 
13136: @item argument input source different than current input source for @code{RESTORE-INPUT}:
13137: @cindex argument input source different than current input source for @code{RESTORE-INPUT}
13138: @cindex argument type mismatch, @code{RESTORE-INPUT}
13139: @cindex @code{RESTORE-INPUT}, Argument type mismatch
13140: @code{-12 THROW}. Note that, once an input file is closed (e.g., because
13141: the end of the file was reached), its source-id may be
13142: reused. Therefore, restoring an input source specification referencing a
13143: closed file may lead to unpredictable results instead of a @code{-12
13144: THROW}.
13145: 
13146: In the future, Gforth may be able to restore input source specifications
13147: from other than the current input source.
13148: 
13149: @item data space containing definitions gets de-allocated:
13150: @cindex data space containing definitions gets de-allocated
13151: Deallocation with @code{allot} is not checked. This typically results in
13152: memory access faults or execution of illegal instructions.
13153: 
13154: @item data space read/write with incorrect alignment:
13155: @cindex data space read/write with incorrect alignment
13156: @cindex alignment faults
13157: @cindex address alignment exception
13158: Processor-dependent. Typically results in a @code{-23 throw} (Address
13159: alignment exception). Under Linux-Intel on a 486 or later processor with
13160: alignment turned on, incorrect alignment results in a @code{-9 throw}
13161: (Invalid memory address). There are reportedly some processors with
13162: alignment restrictions that do not report violations.
13163: 
13164: @item data space pointer not properly aligned, @code{,}, @code{C,}:
13165: @cindex data space pointer not properly aligned, @code{,}, @code{C,}
13166: Like other alignment errors.
13167: 
13168: @item less than u+2 stack items (@code{PICK} and @code{ROLL}):
13169: Like other stack underflows.
13170: 
13171: @item loop control parameters not available:
13172: @cindex loop control parameters not available
13173: Not checked. The counted loop words simply assume that the top of return
13174: stack items are loop control parameters and behave accordingly.
13175: 
13176: @item most recent definition does not have a name (@code{IMMEDIATE}):
13177: @cindex most recent definition does not have a name (@code{IMMEDIATE})
13178: @cindex last word was headerless
13179: @code{abort" last word was headerless"}.
13180: 
13181: @item name not defined by @code{VALUE} used by @code{TO}:
13182: @cindex name not defined by @code{VALUE} used by @code{TO}
13183: @cindex @code{TO} on non-@code{VALUE}s
13184: @cindex Invalid name argument, @code{TO}
13185: @code{-32 throw} (Invalid name argument) (unless name is a local or was
13186: defined by @code{CONSTANT}; in the latter case it just changes the constant).
13187: 
13188: @item name not found (@code{'}, @code{POSTPONE}, @code{[']}, @code{[COMPILE]}):
13189: @cindex name not found (@code{'}, @code{POSTPONE}, @code{[']}, @code{[COMPILE]})
13190: @cindex undefined word, @code{'}, @code{POSTPONE}, @code{[']}, @code{[COMPILE]}
13191: @code{-13 throw} (Undefined word)
13192: 
13193: @item parameters are not of the same type (@code{DO}, @code{?DO}, @code{WITHIN}):
13194: @cindex parameters are not of the same type (@code{DO}, @code{?DO}, @code{WITHIN})
13195: Gforth behaves as if they were of the same type. I.e., you can predict
13196: the behaviour by interpreting all parameters as, e.g., signed.
13197: 
13198: @item @code{POSTPONE} or @code{[COMPILE]} applied to @code{TO}:
13199: @cindex @code{POSTPONE} or @code{[COMPILE]} applied to @code{TO}
13200: Assume @code{: X POSTPONE TO ; IMMEDIATE}. @code{X} performs the
13201: compilation semantics of @code{TO}.
13202: 
13203: @item String longer than a counted string returned by @code{WORD}:
13204: @cindex string longer than a counted string returned by @code{WORD}
13205: @cindex @code{WORD}, string overflow
13206: Not checked. The string will be ok, but the count will, of course,
13207: contain only the least significant bits of the length.
13208: 
13209: @item u greater than or equal to the number of bits in a cell (@code{LSHIFT}, @code{RSHIFT}):
13210: @cindex @code{LSHIFT}, large shift counts
13211: @cindex @code{RSHIFT}, large shift counts
13212: Processor-dependent. Typical behaviours are returning 0 and using only
13213: the low bits of the shift count.
13214: 
13215: @item word not defined via @code{CREATE}:
13216: @cindex @code{>BODY} of non-@code{CREATE}d words
13217: @code{>BODY} produces the PFA of the word no matter how it was defined.
13218: 
13219: @cindex @code{DOES>} of non-@code{CREATE}d words
13220: @code{DOES>} changes the execution semantics of the last defined word no
13221: matter how it was defined. E.g., @code{CONSTANT DOES>} is equivalent to
13222: @code{CREATE , DOES>}.
13223: 
13224: @item words improperly used outside @code{<#} and @code{#>}:
13225: Not checked. As usual, you can expect memory faults.
13226: 
13227: @end table
13228: 
13229: 
13230: @c ---------------------------------------------------------------------
13231: @node core-other,  , core-ambcond, The Core Words
13232: @subsection Other system documentation
13233: @c ---------------------------------------------------------------------
13234: @cindex other system documentation, core words
13235: @cindex core words, other system documentation
13236: 
13237: @table @i
13238: @item nonstandard words using @code{PAD}:
13239: @cindex @code{PAD} use by nonstandard words
13240: None.
13241: 
13242: @item operator's terminal facilities available:
13243: @cindex operator's terminal facilities available
13244: After processing the OS's command line, Gforth goes into interactive mode,
13245: and you can give commands to Gforth interactively. The actual facilities
13246: available depend on how you invoke Gforth.
13247: 
13248: @item program data space available:
13249: @cindex program data space available
13250: @cindex data space available
13251: @code{UNUSED .} gives the remaining dictionary space. The total
13252: dictionary space can be specified with the @code{-m} switch
13253: (@pxref{Invoking Gforth}) when Gforth starts up.
13254: 
13255: @item return stack space available:
13256: @cindex return stack space available
13257: You can compute the total return stack space in cells with
13258: @code{s" RETURN-STACK-CELLS" environment? drop .}. You can specify it at
13259: startup time with the @code{-r} switch (@pxref{Invoking Gforth}).
13260: 
13261: @item stack space available:
13262: @cindex stack space available
13263: You can compute the total data stack space in cells with
13264: @code{s" STACK-CELLS" environment? drop .}. You can specify it at
13265: startup time with the @code{-d} switch (@pxref{Invoking Gforth}).
13266: 
13267: @item system dictionary space required, in address units:
13268: @cindex system dictionary space required, in address units
13269: Type @code{here forthstart - .} after startup. At the time of this
13270: writing, this gives 80080 (bytes) on a 32-bit system.
13271: @end table
13272: 
13273: 
13274: @c =====================================================================
13275: @node The optional Block word set, The optional Double Number word set, The Core Words, ANS conformance
13276: @section The optional Block word set
13277: @c =====================================================================
13278: @cindex system documentation, block words
13279: @cindex block words, system documentation
13280: 
13281: @menu
13282: * block-idef::                  Implementation Defined Options
13283: * block-ambcond::               Ambiguous Conditions               
13284: * block-other::                 Other System Documentation                 
13285: @end menu
13286: 
13287: 
13288: @c ---------------------------------------------------------------------
13289: @node block-idef, block-ambcond, The optional Block word set, The optional Block word set
13290: @subsection Implementation Defined Options
13291: @c ---------------------------------------------------------------------
13292: @cindex implementation-defined options, block words
13293: @cindex block words, implementation-defined options
13294: 
13295: @table @i
13296: @item the format for display by @code{LIST}:
13297: @cindex @code{LIST} display format
13298: First the screen number is displayed, then 16 lines of 64 characters,
13299: each line preceded by the line number.
13300: 
13301: @item the length of a line affected by @code{\}:
13302: @cindex length of a line affected by @code{\}
13303: @cindex @code{\}, line length in blocks
13304: 64 characters.
13305: @end table
13306: 
13307: 
13308: @c ---------------------------------------------------------------------
13309: @node block-ambcond, block-other, block-idef, The optional Block word set
13310: @subsection Ambiguous conditions
13311: @c ---------------------------------------------------------------------
13312: @cindex block words, ambiguous conditions
13313: @cindex ambiguous conditions, block words
13314: 
13315: @table @i
13316: @item correct block read was not possible:
13317: @cindex block read not possible
13318: Typically results in a @code{throw} of some OS-derived value (between
13319: -512 and -2048). If the blocks file was just not long enough, blanks are
13320: supplied for the missing portion.
13321: 
13322: @item I/O exception in block transfer:
13323: @cindex I/O exception in block transfer
13324: @cindex block transfer, I/O exception
13325: Typically results in a @code{throw} of some OS-derived value (between
13326: -512 and -2048).
13327: 
13328: @item invalid block number:
13329: @cindex invalid block number
13330: @cindex block number invalid
13331: @code{-35 throw} (Invalid block number)
13332: 
13333: @item a program directly alters the contents of @code{BLK}:
13334: @cindex @code{BLK}, altering @code{BLK}
13335: The input stream is switched to that other block, at the same
13336: position. If the storing to @code{BLK} happens when interpreting
13337: non-block input, the system will get quite confused when the block ends.
13338: 
13339: @item no current block buffer for @code{UPDATE}:
13340: @cindex @code{UPDATE}, no current block buffer
13341: @code{UPDATE} has no effect.
13342: 
13343: @end table
13344: 
13345: @c ---------------------------------------------------------------------
13346: @node block-other,  , block-ambcond, The optional Block word set
13347: @subsection Other system documentation
13348: @c ---------------------------------------------------------------------
13349: @cindex other system documentation, block words
13350: @cindex block words, other system documentation
13351: 
13352: @table @i
13353: @item any restrictions a multiprogramming system places on the use of buffer addresses:
13354: No restrictions (yet).
13355: 
13356: @item the number of blocks available for source and data:
13357: depends on your disk space.
13358: 
13359: @end table
13360: 
13361: 
13362: @c =====================================================================
13363: @node The optional Double Number word set, The optional Exception word set, The optional Block word set, ANS conformance
13364: @section The optional Double Number word set
13365: @c =====================================================================
13366: @cindex system documentation, double words
13367: @cindex double words, system documentation
13368: 
13369: @menu
13370: * double-ambcond::              Ambiguous Conditions              
13371: @end menu
13372: 
13373: 
13374: @c ---------------------------------------------------------------------
13375: @node double-ambcond,  , The optional Double Number word set, The optional Double Number word set
13376: @subsection Ambiguous conditions
13377: @c ---------------------------------------------------------------------
13378: @cindex double words, ambiguous conditions
13379: @cindex ambiguous conditions, double words
13380: 
13381: @table @i
13382: @item @i{d} outside of range of @i{n} in @code{D>S}:
13383: @cindex @code{D>S}, @i{d} out of range of @i{n} 
13384: The least significant cell of @i{d} is produced.
13385: 
13386: @end table
13387: 
13388: 
13389: @c =====================================================================
13390: @node The optional Exception word set, The optional Facility word set, The optional Double Number word set, ANS conformance
13391: @section The optional Exception word set
13392: @c =====================================================================
13393: @cindex system documentation, exception words
13394: @cindex exception words, system documentation
13395: 
13396: @menu
13397: * exception-idef::              Implementation Defined Options              
13398: @end menu
13399: 
13400: 
13401: @c ---------------------------------------------------------------------
13402: @node exception-idef,  , The optional Exception word set, The optional Exception word set
13403: @subsection Implementation Defined Options
13404: @c ---------------------------------------------------------------------
13405: @cindex implementation-defined options, exception words
13406: @cindex exception words, implementation-defined options
13407: 
13408: @table @i
13409: @item @code{THROW}-codes used in the system:
13410: @cindex @code{THROW}-codes used in the system
13411: The codes -256@minus{}-511 are used for reporting signals. The mapping
13412: from OS signal numbers to throw codes is -256@minus{}@i{signal}. The
13413: codes -512@minus{}-2047 are used for OS errors (for file and memory
13414: allocation operations). The mapping from OS error numbers to throw codes
13415: is -512@minus{}@code{errno}. One side effect of this mapping is that
13416: undefined OS errors produce a message with a strange number; e.g.,
13417: @code{-1000 THROW} results in @code{Unknown error 488} on my system.
13418: @end table
13419: 
13420: @c =====================================================================
13421: @node The optional Facility word set, The optional File-Access word set, The optional Exception word set, ANS conformance
13422: @section The optional Facility word set
13423: @c =====================================================================
13424: @cindex system documentation, facility words
13425: @cindex facility words, system documentation
13426: 
13427: @menu
13428: * facility-idef::               Implementation Defined Options               
13429: * facility-ambcond::            Ambiguous Conditions            
13430: @end menu
13431: 
13432: 
13433: @c ---------------------------------------------------------------------
13434: @node facility-idef, facility-ambcond, The optional Facility word set, The optional Facility word set
13435: @subsection Implementation Defined Options
13436: @c ---------------------------------------------------------------------
13437: @cindex implementation-defined options, facility words
13438: @cindex facility words, implementation-defined options
13439: 
13440: @table @i
13441: @item encoding of keyboard events (@code{EKEY}):
13442: @cindex keyboard events, encoding in @code{EKEY}
13443: @cindex @code{EKEY}, encoding of keyboard events
13444: Keys corresponding to ASCII characters are encoded as ASCII characters.
13445: Other keys are encoded with the constants @code{k-left}, @code{k-right},
13446: @code{k-up}, @code{k-down}, @code{k-home}, @code{k-end}, @code{k1},
13447: @code{k2}, @code{k3}, @code{k4}, @code{k5}, @code{k6}, @code{k7},
13448: @code{k8}, @code{k9}, @code{k10}, @code{k11}, @code{k12}.
13449: 
13450: 
13451: @item duration of a system clock tick:
13452: @cindex duration of a system clock tick
13453: @cindex clock tick duration
13454: System dependent. With respect to @code{MS}, the time is specified in
13455: microseconds. How well the OS and the hardware implement this, is
13456: another question.
13457: 
13458: @item repeatability to be expected from the execution of @code{MS}:
13459: @cindex repeatability to be expected from the execution of @code{MS}
13460: @cindex @code{MS}, repeatability to be expected
13461: System dependent. On Unix, a lot depends on load. If the system is
13462: lightly loaded, and the delay is short enough that Gforth does not get
13463: swapped out, the performance should be acceptable. Under MS-DOS and
13464: other single-tasking systems, it should be good.
13465: 
13466: @end table
13467: 
13468: 
13469: @c ---------------------------------------------------------------------
13470: @node facility-ambcond,  , facility-idef, The optional Facility word set
13471: @subsection Ambiguous conditions
13472: @c ---------------------------------------------------------------------
13473: @cindex facility words, ambiguous conditions
13474: @cindex ambiguous conditions, facility words
13475: 
13476: @table @i
13477: @item @code{AT-XY} can't be performed on user output device:
13478: @cindex @code{AT-XY} can't be performed on user output device
13479: Largely terminal dependent. No range checks are done on the arguments.
13480: No errors are reported. You may see some garbage appearing, you may see
13481: simply nothing happen.
13482: 
13483: @end table
13484: 
13485: 
13486: @c =====================================================================
13487: @node The optional File-Access word set, The optional Floating-Point word set, The optional Facility word set, ANS conformance
13488: @section The optional File-Access word set
13489: @c =====================================================================
13490: @cindex system documentation, file words
13491: @cindex file words, system documentation
13492: 
13493: @menu
13494: * file-idef::                   Implementation Defined Options
13495: * file-ambcond::                Ambiguous Conditions                
13496: @end menu
13497: 
13498: @c ---------------------------------------------------------------------
13499: @node file-idef, file-ambcond, The optional File-Access word set, The optional File-Access word set
13500: @subsection Implementation Defined Options
13501: @c ---------------------------------------------------------------------
13502: @cindex implementation-defined options, file words
13503: @cindex file words, implementation-defined options
13504: 
13505: @table @i
13506: @item file access methods used:
13507: @cindex file access methods used
13508: @code{R/O}, @code{R/W} and @code{BIN} work as you would
13509: expect. @code{W/O} translates into the C file opening mode @code{w} (or
13510: @code{wb}): The file is cleared, if it exists, and created, if it does
13511: not (with both @code{open-file} and @code{create-file}).  Under Unix
13512: @code{create-file} creates a file with 666 permissions modified by your
13513: umask.
13514: 
13515: @item file exceptions:
13516: @cindex file exceptions
13517: The file words do not raise exceptions (except, perhaps, memory access
13518: faults when you pass illegal addresses or file-ids).
13519: 
13520: @item file line terminator:
13521: @cindex file line terminator
13522: System-dependent. Gforth uses C's newline character as line
13523: terminator. What the actual character code(s) of this are is
13524: system-dependent.
13525: 
13526: @item file name format:
13527: @cindex file name format
13528: System dependent. Gforth just uses the file name format of your OS.
13529: 
13530: @item information returned by @code{FILE-STATUS}:
13531: @cindex @code{FILE-STATUS}, returned information
13532: @code{FILE-STATUS} returns the most powerful file access mode allowed
13533: for the file: Either @code{R/O}, @code{W/O} or @code{R/W}. If the file
13534: cannot be accessed, @code{R/O BIN} is returned. @code{BIN} is applicable
13535: along with the returned mode.
13536: 
13537: @item input file state after an exception when including source:
13538: @cindex exception when including source
13539: All files that are left via the exception are closed.
13540: 
13541: @item @i{ior} values and meaning:
13542: @cindex @i{ior} values and meaning
13543: @cindex @i{wior} values and meaning
13544: The @i{ior}s returned by the file and memory allocation words are
13545: intended as throw codes. They typically are in the range
13546: -512@minus{}-2047 of OS errors.  The mapping from OS error numbers to
13547: @i{ior}s is -512@minus{}@i{errno}.
13548: 
13549: @item maximum depth of file input nesting:
13550: @cindex maximum depth of file input nesting
13551: @cindex file input nesting, maximum depth
13552: limited by the amount of return stack, locals/TIB stack, and the number
13553: of open files available. This should not give you troubles.
13554: 
13555: @item maximum size of input line:
13556: @cindex maximum size of input line
13557: @cindex input line size, maximum
13558: @code{/line}. Currently 255.
13559: 
13560: @item methods of mapping block ranges to files:
13561: @cindex mapping block ranges to files
13562: @cindex files containing blocks
13563: @cindex blocks in files
13564: By default, blocks are accessed in the file @file{blocks.fb} in the
13565: current working directory. The file can be switched with @code{USE}.
13566: 
13567: @item number of string buffers provided by @code{S"}:
13568: @cindex @code{S"}, number of string buffers
13569: 1
13570: 
13571: @item size of string buffer used by @code{S"}:
13572: @cindex @code{S"}, size of string buffer
13573: @code{/line}. currently 255.
13574: 
13575: @end table
13576: 
13577: @c ---------------------------------------------------------------------
13578: @node file-ambcond,  , file-idef, The optional File-Access word set
13579: @subsection Ambiguous conditions
13580: @c ---------------------------------------------------------------------
13581: @cindex file words, ambiguous conditions
13582: @cindex ambiguous conditions, file words
13583: 
13584: @table @i
13585: @item attempting to position a file outside its boundaries:
13586: @cindex @code{REPOSITION-FILE}, outside the file's boundaries
13587: @code{REPOSITION-FILE} is performed as usual: Afterwards,
13588: @code{FILE-POSITION} returns the value given to @code{REPOSITION-FILE}.
13589: 
13590: @item attempting to read from file positions not yet written:
13591: @cindex reading from file positions not yet written
13592: End-of-file, i.e., zero characters are read and no error is reported.
13593: 
13594: @item @i{file-id} is invalid (@code{INCLUDE-FILE}):
13595: @cindex @code{INCLUDE-FILE}, @i{file-id} is invalid 
13596: An appropriate exception may be thrown, but a memory fault or other
13597: problem is more probable.
13598: 
13599: @item I/O exception reading or closing @i{file-id} (@code{INCLUDE-FILE}, @code{INCLUDED}):
13600: @cindex @code{INCLUDE-FILE}, I/O exception reading or closing @i{file-id}
13601: @cindex @code{INCLUDED}, I/O exception reading or closing @i{file-id}
13602: The @i{ior} produced by the operation, that discovered the problem, is
13603: thrown.
13604: 
13605: @item named file cannot be opened (@code{INCLUDED}):
13606: @cindex @code{INCLUDED}, named file cannot be opened
13607: The @i{ior} produced by @code{open-file} is thrown.
13608: 
13609: @item requesting an unmapped block number:
13610: @cindex unmapped block numbers
13611: There are no unmapped legal block numbers. On some operating systems,
13612: writing a block with a large number may overflow the file system and
13613: have an error message as consequence.
13614: 
13615: @item using @code{source-id} when @code{blk} is non-zero:
13616: @cindex @code{SOURCE-ID}, behaviour when @code{BLK} is non-zero
13617: @code{source-id} performs its function. Typically it will give the id of
13618: the source which loaded the block. (Better ideas?)
13619: 
13620: @end table
13621: 
13622: 
13623: @c =====================================================================
13624: @node  The optional Floating-Point word set, The optional Locals word set, The optional File-Access word set, ANS conformance
13625: @section The optional Floating-Point word set
13626: @c =====================================================================
13627: @cindex system documentation, floating-point words
13628: @cindex floating-point words, system documentation
13629: 
13630: @menu
13631: * floating-idef::               Implementation Defined Options
13632: * floating-ambcond::            Ambiguous Conditions            
13633: @end menu
13634: 
13635: 
13636: @c ---------------------------------------------------------------------
13637: @node floating-idef, floating-ambcond, The optional Floating-Point word set, The optional Floating-Point word set
13638: @subsection Implementation Defined Options
13639: @c ---------------------------------------------------------------------
13640: @cindex implementation-defined options, floating-point words
13641: @cindex floating-point words, implementation-defined options
13642: 
13643: @table @i
13644: @item format and range of floating point numbers:
13645: @cindex format and range of floating point numbers
13646: @cindex floating point numbers, format and range
13647: System-dependent; the @code{double} type of C.
13648: 
13649: @item results of @code{REPRESENT} when @i{float} is out of range:
13650: @cindex  @code{REPRESENT}, results when @i{float} is out of range
13651: System dependent; @code{REPRESENT} is implemented using the C library
13652: function @code{ecvt()} and inherits its behaviour in this respect.
13653: 
13654: @item rounding or truncation of floating-point numbers:
13655: @cindex rounding of floating-point numbers
13656: @cindex truncation of floating-point numbers
13657: @cindex floating-point numbers, rounding or truncation
13658: System dependent; the rounding behaviour is inherited from the hosting C
13659: compiler. IEEE-FP-based (i.e., most) systems by default round to
13660: nearest, and break ties by rounding to even (i.e., such that the last
13661: bit of the mantissa is 0).
13662: 
13663: @item size of floating-point stack:
13664: @cindex floating-point stack size
13665: @code{s" FLOATING-STACK" environment? drop .} gives the total size of
13666: the floating-point stack (in floats). You can specify this on startup
13667: with the command-line option @code{-f} (@pxref{Invoking Gforth}).
13668: 
13669: @item width of floating-point stack:
13670: @cindex floating-point stack width 
13671: @code{1 floats}.
13672: 
13673: @end table
13674: 
13675: 
13676: @c ---------------------------------------------------------------------
13677: @node floating-ambcond,  , floating-idef, The optional Floating-Point word set
13678: @subsection Ambiguous conditions
13679: @c ---------------------------------------------------------------------
13680: @cindex floating-point words, ambiguous conditions
13681: @cindex ambiguous conditions, floating-point words
13682: 
13683: @table @i
13684: @item @code{df@@} or @code{df!} used with an address that is not double-float  aligned:
13685: @cindex @code{df@@} or @code{df!} used with an address that is not double-float  aligned
13686: System-dependent. Typically results in a @code{-23 THROW} like other
13687: alignment violations.
13688: 
13689: @item @code{f@@} or @code{f!} used with an address that is not float  aligned:
13690: @cindex @code{f@@} used with an address that is not float aligned
13691: @cindex @code{f!} used with an address that is not float aligned
13692: System-dependent. Typically results in a @code{-23 THROW} like other
13693: alignment violations.
13694: 
13695: @item floating-point result out of range:
13696: @cindex floating-point result out of range
13697: System-dependent. Can result in a @code{-43 throw} (floating point
13698: overflow), @code{-54 throw} (floating point underflow), @code{-41 throw}
13699: (floating point inexact result), @code{-55 THROW} (Floating-point
13700: unidentified fault), or can produce a special value representing, e.g.,
13701: Infinity.
13702: 
13703: @item @code{sf@@} or @code{sf!} used with an address that is not single-float  aligned:
13704: @cindex @code{sf@@} or @code{sf!} used with an address that is not single-float  aligned
13705: System-dependent. Typically results in an alignment fault like other
13706: alignment violations.
13707: 
13708: @item @code{base} is not decimal (@code{REPRESENT}, @code{F.}, @code{FE.}, @code{FS.}):
13709: @cindex @code{base} is not decimal (@code{REPRESENT}, @code{F.}, @code{FE.}, @code{FS.})
13710: The floating-point number is converted into decimal nonetheless.
13711: 
13712: @item Both arguments are equal to zero (@code{FATAN2}):
13713: @cindex @code{FATAN2}, both arguments are equal to zero
13714: System-dependent. @code{FATAN2} is implemented using the C library
13715: function @code{atan2()}.
13716: 
13717: @item Using @code{FTAN} on an argument @i{r1} where cos(@i{r1}) is zero:
13718: @cindex @code{FTAN} on an argument @i{r1} where cos(@i{r1}) is zero
13719: System-dependent. Anyway, typically the cos of @i{r1} will not be zero
13720: because of small errors and the tan will be a very large (or very small)
13721: but finite number.
13722: 
13723: @item @i{d} cannot be presented precisely as a float in @code{D>F}:
13724: @cindex @code{D>F}, @i{d} cannot be presented precisely as a float
13725: The result is rounded to the nearest float.
13726: 
13727: @item dividing by zero:
13728: @cindex dividing by zero, floating-point
13729: @cindex floating-point dividing by zero
13730: @cindex floating-point unidentified fault, FP divide-by-zero
13731: Platform-dependent; can produce an Infinity, NaN, @code{-42 throw}
13732: (floating point divide by zero) or @code{-55 throw} (Floating-point
13733: unidentified fault).
13734: 
13735: @item exponent too big for conversion (@code{DF!}, @code{DF@@}, @code{SF!}, @code{SF@@}):
13736: @cindex exponent too big for conversion (@code{DF!}, @code{DF@@}, @code{SF!}, @code{SF@@})
13737: System dependent. On IEEE-FP based systems the number is converted into
13738: an infinity.
13739: 
13740: @item @i{float}<1 (@code{FACOSH}):
13741: @cindex @code{FACOSH}, @i{float}<1
13742: @cindex floating-point unidentified fault, @code{FACOSH}
13743: Platform-dependent; on IEEE-FP systems typically produces a NaN.
13744: 
13745: @item @i{float}=<-1 (@code{FLNP1}):
13746: @cindex @code{FLNP1}, @i{float}=<-1
13747: @cindex floating-point unidentified fault, @code{FLNP1}
13748: Platform-dependent; on IEEE-FP systems typically produces a NaN (or a
13749: negative infinity for @i{float}=-1).
13750: 
13751: @item @i{float}=<0 (@code{FLN}, @code{FLOG}):
13752: @cindex @code{FLN}, @i{float}=<0
13753: @cindex @code{FLOG}, @i{float}=<0
13754: @cindex floating-point unidentified fault, @code{FLN} or @code{FLOG}
13755: Platform-dependent; on IEEE-FP systems typically produces a NaN (or a
13756: negative infinity for @i{float}=0).
13757: 
13758: @item @i{float}<0 (@code{FASINH}, @code{FSQRT}):
13759: @cindex @code{FASINH}, @i{float}<0
13760: @cindex @code{FSQRT}, @i{float}<0
13761: @cindex floating-point unidentified fault, @code{FASINH} or @code{FSQRT}
13762: Platform-dependent; for @code{fsqrt} this typically gives a NaN, for
13763: @code{fasinh} some platforms produce a NaN, others a number (bug in the
13764: C library?).
13765: 
13766: @item |@i{float}|>1 (@code{FACOS}, @code{FASIN}, @code{FATANH}):
13767: @cindex @code{FACOS}, |@i{float}|>1
13768: @cindex @code{FASIN}, |@i{float}|>1
13769: @cindex @code{FATANH}, |@i{float}|>1
13770: @cindex floating-point unidentified fault, @code{FACOS}, @code{FASIN} or @code{FATANH}
13771: Platform-dependent; IEEE-FP systems typically produce a NaN.
13772: 
13773: @item integer part of float cannot be represented by @i{d} in @code{F>D}:
13774: @cindex @code{F>D}, integer part of float cannot be represented by @i{d}
13775: @cindex floating-point unidentified fault, @code{F>D}
13776: Platform-dependent; typically, some double number is produced and no
13777: error is reported.
13778: 
13779: @item string larger than pictured numeric output area (@code{f.}, @code{fe.}, @code{fs.}):
13780: @cindex string larger than pictured numeric output area (@code{f.}, @code{fe.}, @code{fs.})
13781: @code{Precision} characters of the numeric output area are used.  If
13782: @code{precision} is too high, these words will smash the data or code
13783: close to @code{here}.
13784: @end table
13785: 
13786: @c =====================================================================
13787: @node  The optional Locals word set, The optional Memory-Allocation word set, The optional Floating-Point word set, ANS conformance
13788: @section The optional Locals word set
13789: @c =====================================================================
13790: @cindex system documentation, locals words
13791: @cindex locals words, system documentation
13792: 
13793: @menu
13794: * locals-idef::                 Implementation Defined Options                 
13795: * locals-ambcond::              Ambiguous Conditions              
13796: @end menu
13797: 
13798: 
13799: @c ---------------------------------------------------------------------
13800: @node locals-idef, locals-ambcond, The optional Locals word set, The optional Locals word set
13801: @subsection Implementation Defined Options
13802: @c ---------------------------------------------------------------------
13803: @cindex implementation-defined options, locals words
13804: @cindex locals words, implementation-defined options
13805: 
13806: @table @i
13807: @item maximum number of locals in a definition:
13808: @cindex maximum number of locals in a definition
13809: @cindex locals, maximum number in a definition
13810: @code{s" #locals" environment? drop .}. Currently 15. This is a lower
13811: bound, e.g., on a 32-bit machine there can be 41 locals of up to 8
13812: characters. The number of locals in a definition is bounded by the size
13813: of locals-buffer, which contains the names of the locals.
13814: 
13815: @end table
13816: 
13817: 
13818: @c ---------------------------------------------------------------------
13819: @node locals-ambcond,  , locals-idef, The optional Locals word set
13820: @subsection Ambiguous conditions
13821: @c ---------------------------------------------------------------------
13822: @cindex locals words, ambiguous conditions
13823: @cindex ambiguous conditions, locals words
13824: 
13825: @table @i
13826: @item executing a named local in interpretation state:
13827: @cindex local in interpretation state
13828: @cindex Interpreting a compile-only word, for a local
13829: Locals have no interpretation semantics. If you try to perform the
13830: interpretation semantics, you will get a @code{-14 throw} somewhere
13831: (Interpreting a compile-only word). If you perform the compilation
13832: semantics, the locals access will be compiled (irrespective of state).
13833: 
13834: @item @i{name} not defined by @code{VALUE} or @code{(LOCAL)} (@code{TO}):
13835: @cindex name not defined by @code{VALUE} or @code{(LOCAL)} used by @code{TO}
13836: @cindex @code{TO} on non-@code{VALUE}s and non-locals
13837: @cindex Invalid name argument, @code{TO}
13838: @code{-32 throw} (Invalid name argument)
13839: 
13840: @end table
13841: 
13842: 
13843: @c =====================================================================
13844: @node  The optional Memory-Allocation word set, The optional Programming-Tools word set, The optional Locals word set, ANS conformance
13845: @section The optional Memory-Allocation word set
13846: @c =====================================================================
13847: @cindex system documentation, memory-allocation words
13848: @cindex memory-allocation words, system documentation
13849: 
13850: @menu
13851: * memory-idef::                 Implementation Defined Options                 
13852: @end menu
13853: 
13854: 
13855: @c ---------------------------------------------------------------------
13856: @node memory-idef,  , The optional Memory-Allocation word set, The optional Memory-Allocation word set
13857: @subsection Implementation Defined Options
13858: @c ---------------------------------------------------------------------
13859: @cindex implementation-defined options, memory-allocation words
13860: @cindex memory-allocation words, implementation-defined options
13861: 
13862: @table @i
13863: @item values and meaning of @i{ior}:
13864: @cindex  @i{ior} values and meaning
13865: The @i{ior}s returned by the file and memory allocation words are
13866: intended as throw codes. They typically are in the range
13867: -512@minus{}-2047 of OS errors.  The mapping from OS error numbers to
13868: @i{ior}s is -512@minus{}@i{errno}.
13869: 
13870: @end table
13871: 
13872: @c =====================================================================
13873: @node  The optional Programming-Tools word set, The optional Search-Order word set, The optional Memory-Allocation word set, ANS conformance
13874: @section The optional Programming-Tools word set
13875: @c =====================================================================
13876: @cindex system documentation, programming-tools words
13877: @cindex programming-tools words, system documentation
13878: 
13879: @menu
13880: * programming-idef::            Implementation Defined Options            
13881: * programming-ambcond::         Ambiguous Conditions         
13882: @end menu
13883: 
13884: 
13885: @c ---------------------------------------------------------------------
13886: @node programming-idef, programming-ambcond, The optional Programming-Tools word set, The optional Programming-Tools word set
13887: @subsection Implementation Defined Options
13888: @c ---------------------------------------------------------------------
13889: @cindex implementation-defined options, programming-tools words
13890: @cindex programming-tools words, implementation-defined options
13891: 
13892: @table @i
13893: @item ending sequence for input following @code{;CODE} and @code{CODE}:
13894: @cindex @code{;CODE} ending sequence
13895: @cindex @code{CODE} ending sequence
13896: @code{END-CODE}
13897: 
13898: @item manner of processing input following @code{;CODE} and @code{CODE}:
13899: @cindex @code{;CODE}, processing input
13900: @cindex @code{CODE}, processing input
13901: The @code{ASSEMBLER} vocabulary is pushed on the search order stack, and
13902: the input is processed by the text interpreter, (starting) in interpret
13903: state.
13904: 
13905: @item search order capability for @code{EDITOR} and @code{ASSEMBLER}:
13906: @cindex @code{ASSEMBLER}, search order capability
13907: The ANS Forth search order word set.
13908: 
13909: @item source and format of display by @code{SEE}:
13910: @cindex @code{SEE}, source and format of output
13911: The source for @code{see} is the executable code used by the inner
13912: interpreter.  The current @code{see} tries to output Forth source code
13913: (and on some platforms, assembly code for primitives) as well as
13914: possible.
13915: 
13916: @end table
13917: 
13918: @c ---------------------------------------------------------------------
13919: @node programming-ambcond,  , programming-idef, The optional Programming-Tools word set
13920: @subsection Ambiguous conditions
13921: @c ---------------------------------------------------------------------
13922: @cindex programming-tools words, ambiguous conditions
13923: @cindex ambiguous conditions, programming-tools words
13924: 
13925: @table @i
13926: 
13927: @item deleting the compilation word list (@code{FORGET}):
13928: @cindex @code{FORGET}, deleting the compilation word list
13929: Not implemented (yet).
13930: 
13931: @item fewer than @i{u}+1 items on the control-flow stack (@code{CS-PICK}, @code{CS-ROLL}):
13932: @cindex @code{CS-PICK}, fewer than @i{u}+1 items on the control flow-stack
13933: @cindex @code{CS-ROLL}, fewer than @i{u}+1 items on the control flow-stack
13934: @cindex control-flow stack underflow
13935: This typically results in an @code{abort"} with a descriptive error
13936: message (may change into a @code{-22 throw} (Control structure mismatch)
13937: in the future). You may also get a memory access error. If you are
13938: unlucky, this ambiguous condition is not caught.
13939: 
13940: @item @i{name} can't be found (@code{FORGET}):
13941: @cindex @code{FORGET}, @i{name} can't be found
13942: Not implemented (yet).
13943: 
13944: @item @i{name} not defined via @code{CREATE}:
13945: @cindex @code{;CODE}, @i{name} not defined via @code{CREATE}
13946: @code{;CODE} behaves like @code{DOES>} in this respect, i.e., it changes
13947: the execution semantics of the last defined word no matter how it was
13948: defined.
13949: 
13950: @item @code{POSTPONE} applied to @code{[IF]}:
13951: @cindex @code{POSTPONE} applied to @code{[IF]}
13952: @cindex @code{[IF]} and @code{POSTPONE}
13953: After defining @code{: X POSTPONE [IF] ; IMMEDIATE}. @code{X} is
13954: equivalent to @code{[IF]}.
13955: 
13956: @item reaching the end of the input source before matching @code{[ELSE]} or @code{[THEN]}:
13957: @cindex @code{[IF]}, end of the input source before matching @code{[ELSE]} or @code{[THEN]}
13958: Continue in the same state of conditional compilation in the next outer
13959: input source. Currently there is no warning to the user about this.
13960: 
13961: @item removing a needed definition (@code{FORGET}):
13962: @cindex @code{FORGET}, removing a needed definition
13963: Not implemented (yet).
13964: 
13965: @end table
13966: 
13967: 
13968: @c =====================================================================
13969: @node  The optional Search-Order word set,  , The optional Programming-Tools word set, ANS conformance
13970: @section The optional Search-Order word set
13971: @c =====================================================================
13972: @cindex system documentation, search-order words
13973: @cindex search-order words, system documentation
13974: 
13975: @menu
13976: * search-idef::                 Implementation Defined Options                 
13977: * search-ambcond::              Ambiguous Conditions              
13978: @end menu
13979: 
13980: 
13981: @c ---------------------------------------------------------------------
13982: @node search-idef, search-ambcond, The optional Search-Order word set, The optional Search-Order word set
13983: @subsection Implementation Defined Options
13984: @c ---------------------------------------------------------------------
13985: @cindex implementation-defined options, search-order words
13986: @cindex search-order words, implementation-defined options
13987: 
13988: @table @i
13989: @item maximum number of word lists in search order:
13990: @cindex maximum number of word lists in search order
13991: @cindex search order, maximum depth
13992: @code{s" wordlists" environment? drop .}. Currently 16.
13993: 
13994: @item minimum search order:
13995: @cindex minimum search order
13996: @cindex search order, minimum
13997: @code{root root}.
13998: 
13999: @end table
14000: 
14001: @c ---------------------------------------------------------------------
14002: @node search-ambcond,  , search-idef, The optional Search-Order word set
14003: @subsection Ambiguous conditions
14004: @c ---------------------------------------------------------------------
14005: @cindex search-order words, ambiguous conditions
14006: @cindex ambiguous conditions, search-order words
14007: 
14008: @table @i
14009: @item changing the compilation word list (during compilation):
14010: @cindex changing the compilation word list (during compilation)
14011: @cindex compilation word list, change before definition ends
14012: The word is entered into the word list that was the compilation word list
14013: at the start of the definition. Any changes to the name field (e.g.,
14014: @code{immediate}) or the code field (e.g., when executing @code{DOES>})
14015: are applied to the latest defined word (as reported by @code{latest} or
14016: @code{latestxt}), if possible, irrespective of the compilation word list.
14017: 
14018: @item search order empty (@code{previous}):
14019: @cindex @code{previous}, search order empty
14020: @cindex vocstack empty, @code{previous}
14021: @code{abort" Vocstack empty"}.
14022: 
14023: @item too many word lists in search order (@code{also}):
14024: @cindex @code{also}, too many word lists in search order
14025: @cindex vocstack full, @code{also}
14026: @code{abort" Vocstack full"}.
14027: 
14028: @end table
14029: 
14030: @c ***************************************************************
14031: @node Standard vs Extensions, Model, ANS conformance, Top
14032: @chapter Should I use Gforth extensions?
14033: @cindex Gforth extensions
14034: 
14035: As you read through the rest of this manual, you will see documentation
14036: for @i{Standard} words, and documentation for some appealing Gforth
14037: @i{extensions}. You might ask yourself the question: @i{``Should I
14038: restrict myself to the standard, or should I use the extensions?''}
14039: 
14040: The answer depends on the goals you have for the program you are working
14041: on:
14042: 
14043: @itemize @bullet
14044: 
14045: @item Is it just for yourself or do you want to share it with others?
14046: 
14047: @item
14048: If you want to share it, do the others all use Gforth?
14049: 
14050: @item
14051: If it is just for yourself, do you want to restrict yourself to Gforth?
14052: 
14053: @end itemize
14054: 
14055: If restricting the program to Gforth is ok, then there is no reason not
14056: to use extensions.  It is still a good idea to keep to the standard
14057: where it is easy, in case you want to reuse these parts in another
14058: program that you want to be portable.
14059: 
14060: If you want to be able to port the program to other Forth systems, there
14061: are the following points to consider:
14062: 
14063: @itemize @bullet
14064: 
14065: @item
14066: Most Forth systems that are being maintained support the ANS Forth
14067: standard.  So if your program complies with the standard, it will be
14068: portable among many systems.
14069: 
14070: @item
14071: A number of the Gforth extensions can be implemented in ANS Forth using
14072: public-domain files provided in the @file{compat/} directory. These are
14073: mentioned in the text in passing.  There is no reason not to use these
14074: extensions, your program will still be ANS Forth compliant; just include
14075: the appropriate compat files with your program.
14076: 
14077: @item
14078: The tool @file{ans-report.fs} (@pxref{ANS Report}) makes it easy to
14079: analyse your program and determine what non-Standard words it relies
14080: upon.  However, it does not check whether you use standard words in a
14081: non-standard way.
14082: 
14083: @item
14084: Some techniques are not standardized by ANS Forth, and are hard or
14085: impossible to implement in a standard way, but can be implemented in
14086: most Forth systems easily, and usually in similar ways (e.g., accessing
14087: word headers).  Forth has a rich historical precedent for programmers
14088: taking advantage of implementation-dependent features of their tools
14089: (for example, relying on a knowledge of the dictionary
14090: structure). Sometimes these techniques are necessary to extract every
14091: last bit of performance from the hardware, sometimes they are just a
14092: programming shorthand.
14093: 
14094: @item
14095: Does using a Gforth extension save more work than the porting this part
14096: to other Forth systems (if any) will cost?
14097: 
14098: @item
14099: Is the additional functionality worth the reduction in portability and
14100: the additional porting problems?
14101: 
14102: @end itemize
14103: 
14104: In order to perform these consideratios, you need to know what's
14105: standard and what's not.  This manual generally states if something is
14106: non-standard, but the authoritative source is the
14107: @uref{http://www.taygeta.com/forth/dpans.html,standard document}.
14108: Appendix A of the Standard (@var{Rationale}) provides a valuable insight
14109: into the thought processes of the technical committee.
14110: 
14111: Note also that portability between Forth systems is not the only
14112: portability issue; there is also the issue of portability between
14113: different platforms (processor/OS combinations).
14114: 
14115: @c ***************************************************************
14116: @node Model, Integrating Gforth, Standard vs Extensions, Top
14117: @chapter Model
14118: 
14119: This chapter has yet to be written. It will contain information, on
14120: which internal structures you can rely.
14121: 
14122: @c ***************************************************************
14123: @node Integrating Gforth, Emacs and Gforth, Model, Top
14124: @chapter Integrating Gforth into C programs
14125: 
14126: This is not yet implemented.
14127: 
14128: Several people like to use Forth as scripting language for applications
14129: that are otherwise written in C, C++, or some other language.
14130: 
14131: The Forth system ATLAST provides facilities for embedding it into
14132: applications; unfortunately it has several disadvantages: most
14133: importantly, it is not based on ANS Forth, and it is apparently dead
14134: (i.e., not developed further and not supported). The facilities
14135: provided by Gforth in this area are inspired by ATLAST's facilities, so
14136: making the switch should not be hard.
14137: 
14138: We also tried to design the interface such that it can easily be
14139: implemented by other Forth systems, so that we may one day arrive at a
14140: standardized interface. Such a standard interface would allow you to
14141: replace the Forth system without having to rewrite C code.
14142: 
14143: You embed the Gforth interpreter by linking with the library
14144: @code{libgforth.a} (give the compiler the option @code{-lgforth}).  All
14145: global symbols in this library that belong to the interface, have the
14146: prefix @code{forth_}. (Global symbols that are used internally have the
14147: prefix @code{gforth_}).
14148: 
14149: You can include the declarations of Forth types and the functions and
14150: variables of the interface with @code{#include <forth.h>}.
14151: 
14152: Types.
14153: 
14154: Variables.
14155: 
14156: Data and FP Stack pointer. Area sizes.
14157: 
14158: functions.
14159: 
14160: forth_init(imagefile)
14161: forth_evaluate(string) exceptions?
14162: forth_goto(address) (or forth_execute(xt)?)
14163: forth_continue() (a corountining mechanism)
14164: 
14165: Adding primitives.
14166: 
14167: No checking.
14168: 
14169: Signals?
14170: 
14171: Accessing the Stacks
14172: 
14173: @c ******************************************************************
14174: @node Emacs and Gforth, Image Files, Integrating Gforth, Top
14175: @chapter Emacs and Gforth
14176: @cindex Emacs and Gforth
14177: 
14178: @cindex @file{gforth.el}
14179: @cindex @file{forth.el}
14180: @cindex Rydqvist, Goran
14181: @cindex Kuehling, David
14182: @cindex comment editing commands
14183: @cindex @code{\}, editing with Emacs
14184: @cindex debug tracer editing commands
14185: @cindex @code{~~}, removal with Emacs
14186: @cindex Forth mode in Emacs
14187: 
14188: Gforth comes with @file{gforth.el}, an improved version of
14189: @file{forth.el} by Goran Rydqvist (included in the TILE package). The
14190: improvements are:
14191: 
14192: @itemize @bullet
14193: @item
14194: A better handling of indentation.
14195: @item
14196: A custom hilighting engine for Forth-code.
14197: @item
14198: Comment paragraph filling (@kbd{M-q})
14199: @item
14200: Commenting (@kbd{C-x \}) and uncommenting (@kbd{C-u C-x \}) of regions
14201: @item
14202: Removal of debugging tracers (@kbd{C-x ~}, @pxref{Debugging}).
14203: @item
14204: Support of the @code{info-lookup} feature for looking up the
14205: documentation of a word.
14206: @item
14207: Support for reading and writing blocks files.
14208: @end itemize
14209: 
14210: To get a basic description of these features, enter Forth mode and
14211: type @kbd{C-h m}.
14212: 
14213: @cindex source location of error or debugging output in Emacs
14214: @cindex error output, finding the source location in Emacs
14215: @cindex debugging output, finding the source location in Emacs
14216: In addition, Gforth supports Emacs quite well: The source code locations
14217: given in error messages, debugging output (from @code{~~}) and failed
14218: assertion messages are in the right format for Emacs' compilation mode
14219: (@pxref{Compilation, , Running Compilations under Emacs, emacs, Emacs
14220: Manual}) so the source location corresponding to an error or other
14221: message is only a few keystrokes away (@kbd{C-x `} for the next error,
14222: @kbd{C-c C-c} for the error under the cursor).
14223: 
14224: @cindex viewing the documentation of a word in Emacs
14225: @cindex context-sensitive help
14226: Moreover, for words documented in this manual, you can look up the
14227: glossary entry quickly by using @kbd{C-h TAB}
14228: (@code{info-lookup-symbol}, @pxref{Documentation, ,Documentation
14229: Commands, emacs, Emacs Manual}).  This feature requires Emacs 20.3 or
14230: later and does not work for words containing @code{:}.
14231: 
14232: @menu
14233: * Installing gforth.el::        Making Emacs aware of Forth.
14234: * Emacs Tags::                  Viewing the source of a word in Emacs.
14235: * Hilighting::                  Making Forth code look prettier.
14236: * Auto-Indentation::            Customizing auto-indentation.
14237: * Blocks Files::                Reading and writing blocks files.
14238: @end menu
14239: 
14240: @c ----------------------------------
14241: @node Installing gforth.el, Emacs Tags, Emacs and Gforth, Emacs and Gforth
14242: @section Installing gforth.el
14243: @cindex @file{.emacs}
14244: @cindex @file{gforth.el}, installation
14245: To make the features from @file{gforth.el} available in Emacs, add
14246: the following lines to your @file{.emacs} file:
14247: 
14248: @example
14249: (autoload 'forth-mode "gforth.el")
14250: (setq auto-mode-alist (cons '("\\.fs\\'" . forth-mode) 
14251: 			    auto-mode-alist))
14252: (autoload 'forth-block-mode "gforth.el")
14253: (setq auto-mode-alist (cons '("\\.fb\\'" . forth-block-mode) 
14254: 			    auto-mode-alist))
14255: (add-hook 'forth-mode-hook (function (lambda ()
14256:    ;; customize variables here:
14257:    (setq forth-indent-level 4)
14258:    (setq forth-minor-indent-level 2)
14259:    (setq forth-hilight-level 3)
14260:    ;;; ...
14261: )))
14262: @end example
14263: 
14264: @c ----------------------------------
14265: @node Emacs Tags, Hilighting, Installing gforth.el, Emacs and Gforth
14266: @section Emacs Tags
14267: @cindex @file{TAGS} file
14268: @cindex @file{etags.fs}
14269: @cindex viewing the source of a word in Emacs
14270: @cindex @code{require}, placement in files
14271: @cindex @code{include}, placement in files
14272: If you @code{require} @file{etags.fs}, a new @file{TAGS} file will be
14273: produced (@pxref{Tags, , Tags Tables, emacs, Emacs Manual}) that
14274: contains the definitions of all words defined afterwards. You can then
14275: find the source for a word using @kbd{M-.}. Note that Emacs can use
14276: several tags files at the same time (e.g., one for the Gforth sources
14277: and one for your program, @pxref{Select Tags Table,,Selecting a Tags
14278: Table,emacs, Emacs Manual}). The TAGS file for the preloaded words is
14279: @file{$(datadir)/gforth/$(VERSION)/TAGS} (e.g.,
14280: @file{/usr/local/share/gforth/0.2.0/TAGS}).  To get the best behaviour
14281: with @file{etags.fs}, you should avoid putting definitions both before
14282: and after @code{require} etc., otherwise you will see the same file
14283: visited several times by commands like @code{tags-search}.
14284: 
14285: @c ----------------------------------
14286: @node Hilighting, Auto-Indentation, Emacs Tags, Emacs and Gforth
14287: @section Hilighting
14288: @cindex hilighting Forth code in Emacs
14289: @cindex highlighting Forth code in Emacs
14290: @file{gforth.el} comes with a custom source hilighting engine.  When
14291: you open a file in @code{forth-mode}, it will be completely parsed,
14292: assigning faces to keywords, comments, strings etc.  While you edit
14293: the file, modified regions get parsed and updated on-the-fly. 
14294: 
14295: Use the variable `forth-hilight-level' to change the level of
14296: decoration from 0 (no hilighting at all) to 3 (the default).  Even if
14297: you set the hilighting level to 0, the parser will still work in the
14298: background, collecting information about whether regions of text are
14299: ``compiled'' or ``interpreted''.  Those information are required for
14300: auto-indentation to work properly.  Set `forth-disable-parser' to
14301: non-nil if your computer is too slow to handle parsing.  This will
14302: have an impact on the smartness of the auto-indentation engine,
14303: though.
14304: 
14305: Sometimes Forth sources define new features that should be hilighted,
14306: new control structures, defining-words etc.  You can use the variable
14307: `forth-custom-words' to make @code{forth-mode} hilight additional
14308: words and constructs.  See the docstring of `forth-words' for details
14309: (in Emacs, type @kbd{C-h v forth-words}).
14310: 
14311: `forth-custom-words' is meant to be customized in your
14312: @file{.emacs} file.  To customize hilighing in a file-specific manner,
14313: set `forth-local-words' in a local-variables section at the end of
14314: your source file (@pxref{Local Variables in Files,, Variables, emacs, Emacs Manual}).
14315: 
14316: Example:
14317: @example
14318: 0 [IF]
14319:    Local Variables:
14320:    forth-local-words:
14321:       ((("t:") definition-starter (font-lock-keyword-face . 1)
14322:         "[ \t\n]" t name (font-lock-function-name-face . 3))
14323:        ((";t") definition-ender (font-lock-keyword-face . 1)))
14324:    End:
14325: [THEN]
14326: @end example
14327: 
14328: @c ----------------------------------
14329: @node Auto-Indentation, Blocks Files, Hilighting, Emacs and Gforth
14330: @section Auto-Indentation
14331: @cindex auto-indentation of Forth code in Emacs
14332: @cindex indentation of Forth code in Emacs
14333: @code{forth-mode} automatically tries to indent lines in a smart way,
14334: whenever you type @key{TAB} or break a line with @kbd{C-m}.
14335: 
14336: Simple customization can be achieved by setting
14337: `forth-indent-level' and `forth-minor-indent-level' in your
14338: @file{.emacs} file. For historical reasons @file{gforth.el} indents
14339: per default by multiples of 4 columns.  To use the more traditional
14340: 3-column indentation, add the following lines to your @file{.emacs}:
14341: 
14342: @example
14343: (add-hook 'forth-mode-hook (function (lambda ()
14344:    ;; customize variables here:
14345:    (setq forth-indent-level 3)
14346:    (setq forth-minor-indent-level 1)
14347: )))
14348: @end example
14349: 
14350: If you want indentation to recognize non-default words, customize it
14351: by setting `forth-custom-indent-words' in your @file{.emacs}.  See the
14352: docstring of `forth-indent-words' for details (in Emacs, type @kbd{C-h
14353: v forth-indent-words}).
14354: 
14355: To customize indentation in a file-specific manner, set
14356: `forth-local-indent-words' in a local-variables section at the end of
14357: your source file (@pxref{Local Variables in Files, Variables,,emacs,
14358: Emacs Manual}).
14359: 
14360: Example:
14361: @example
14362: 0 [IF]
14363:    Local Variables:
14364:    forth-local-indent-words:
14365:       ((("t:") (0 . 2) (0 . 2))
14366:        ((";t") (-2 . 0) (0 . -2)))
14367:    End:
14368: [THEN]
14369: @end example
14370: 
14371: @c ----------------------------------
14372: @node Blocks Files,  , Auto-Indentation, Emacs and Gforth
14373: @section Blocks Files
14374: @cindex blocks files, use with Emacs
14375: @code{forth-mode} Autodetects blocks files by checking whether the
14376: length of the first line exceeds 1023 characters.  It then tries to
14377: convert the file into normal text format.  When you save the file, it
14378: will be written to disk as normal stream-source file.
14379: 
14380: If you want to write blocks files, use @code{forth-blocks-mode}.  It
14381: inherits all the features from @code{forth-mode}, plus some additions:
14382: 
14383: @itemize @bullet
14384: @item
14385: Files are written to disk in blocks file format.
14386: @item
14387: Screen numbers are displayed in the mode line (enumerated beginning
14388: with the value of `forth-block-base')
14389: @item
14390: Warnings are displayed when lines exceed 64 characters.
14391: @item
14392: The beginning of the currently edited block is marked with an
14393: overlay-arrow. 
14394: @end itemize
14395: 
14396: There are some restrictions you should be aware of.  When you open a
14397: blocks file that contains tabulator or newline characters, these
14398: characters will be translated into spaces when the file is written
14399: back to disk.  If tabs or newlines are encountered during blocks file
14400: reading, an error is output to the echo area. So have a look at the
14401: `*Messages*' buffer, when Emacs' bell rings during reading.
14402: 
14403: Please consult the docstring of @code{forth-blocks-mode} for more
14404: information by typing @kbd{C-h v forth-blocks-mode}).
14405: 
14406: @c ******************************************************************
14407: @node Image Files, Engine, Emacs and Gforth, Top
14408: @chapter Image Files
14409: @cindex image file
14410: @cindex @file{.fi} files
14411: @cindex precompiled Forth code
14412: @cindex dictionary in persistent form
14413: @cindex persistent form of dictionary
14414: 
14415: An image file is a file containing an image of the Forth dictionary,
14416: i.e., compiled Forth code and data residing in the dictionary.  By
14417: convention, we use the extension @code{.fi} for image files.
14418: 
14419: @menu
14420: * Image Licensing Issues::      Distribution terms for images.
14421: * Image File Background::       Why have image files?
14422: * Non-Relocatable Image Files::  don't always work.
14423: * Data-Relocatable Image Files::  are better.
14424: * Fully Relocatable Image Files::  better yet.
14425: * Stack and Dictionary Sizes::  Setting the default sizes for an image.
14426: * Running Image Files::         @code{gforth -i @i{file}} or @i{file}.
14427: * Modifying the Startup Sequence::  and turnkey applications.
14428: @end menu
14429: 
14430: @node Image Licensing Issues, Image File Background, Image Files, Image Files
14431: @section Image Licensing Issues
14432: @cindex license for images
14433: @cindex image license
14434: 
14435: An image created with @code{gforthmi} (@pxref{gforthmi}) or
14436: @code{savesystem} (@pxref{Non-Relocatable Image Files}) includes the
14437: original image; i.e., according to copyright law it is a derived work of
14438: the original image.
14439: 
14440: Since Gforth is distributed under the GNU GPL, the newly created image
14441: falls under the GNU GPL, too. In particular, this means that if you
14442: distribute the image, you have to make all of the sources for the image
14443: available, including those you wrote.  For details see @ref{Copying, ,
14444: GNU General Public License (Section 3)}.
14445: 
14446: If you create an image with @code{cross} (@pxref{cross.fs}), the image
14447: contains only code compiled from the sources you gave it; if none of
14448: these sources is under the GPL, the terms discussed above do not apply
14449: to the image. However, if your image needs an engine (a gforth binary)
14450: that is under the GPL, you should make sure that you distribute both in
14451: a way that is at most a @emph{mere aggregation}, if you don't want the
14452: terms of the GPL to apply to the image.
14453: 
14454: @node Image File Background, Non-Relocatable Image Files, Image Licensing Issues, Image Files
14455: @section Image File Background
14456: @cindex image file background
14457: 
14458: Gforth consists not only of primitives (in the engine), but also of
14459: definitions written in Forth. Since the Forth compiler itself belongs to
14460: those definitions, it is not possible to start the system with the
14461: engine and the Forth source alone. Therefore we provide the Forth
14462: code as an image file in nearly executable form. When Gforth starts up,
14463: a C routine loads the image file into memory, optionally relocates the
14464: addresses, then sets up the memory (stacks etc.) according to
14465: information in the image file, and (finally) starts executing Forth
14466: code.
14467: 
14468: The image file variants represent different compromises between the
14469: goals of making it easy to generate image files and making them
14470: portable.
14471: 
14472: @cindex relocation at run-time
14473: Win32Forth 3.4 and Mitch Bradley's @code{cforth} use relocation at
14474: run-time. This avoids many of the complications discussed below (image
14475: files are data relocatable without further ado), but costs performance
14476: (one addition per memory access).
14477: 
14478: @cindex relocation at load-time
14479: By contrast, the Gforth loader performs relocation at image load time. The
14480: loader also has to replace tokens that represent primitive calls with the
14481: appropriate code-field addresses (or code addresses in the case of
14482: direct threading).
14483: 
14484: There are three kinds of image files, with different degrees of
14485: relocatability: non-relocatable, data-relocatable, and fully relocatable
14486: image files.
14487: 
14488: @cindex image file loader
14489: @cindex relocating loader
14490: @cindex loader for image files
14491: These image file variants have several restrictions in common; they are
14492: caused by the design of the image file loader:
14493: 
14494: @itemize @bullet
14495: @item
14496: There is only one segment; in particular, this means, that an image file
14497: cannot represent @code{ALLOCATE}d memory chunks (and pointers to
14498: them). The contents of the stacks are not represented, either.
14499: 
14500: @item
14501: The only kinds of relocation supported are: adding the same offset to
14502: all cells that represent data addresses; and replacing special tokens
14503: with code addresses or with pieces of machine code.
14504: 
14505: If any complex computations involving addresses are performed, the
14506: results cannot be represented in the image file. Several applications that
14507: use such computations come to mind:
14508: @itemize @minus
14509: @item
14510: Hashing addresses (or data structures which contain addresses) for table
14511: lookup. If you use Gforth's @code{table}s or @code{wordlist}s for this
14512: purpose, you will have no problem, because the hash tables are
14513: recomputed automatically when the system is started. If you use your own
14514: hash tables, you will have to do something similar.
14515: 
14516: @item
14517: There's a cute implementation of doubly-linked lists that uses
14518: @code{XOR}ed addresses. You could represent such lists as singly-linked
14519: in the image file, and restore the doubly-linked representation on
14520: startup.@footnote{In my opinion, though, you should think thrice before
14521: using a doubly-linked list (whatever implementation).}
14522: 
14523: @item
14524: The code addresses of run-time routines like @code{docol:} cannot be
14525: represented in the image file (because their tokens would be replaced by
14526: machine code in direct threaded implementations). As a workaround,
14527: compute these addresses at run-time with @code{>code-address} from the
14528: executions tokens of appropriate words (see the definitions of
14529: @code{docol:} and friends in @file{kernel/getdoers.fs}).
14530: 
14531: @item
14532: On many architectures addresses are represented in machine code in some
14533: shifted or mangled form. You cannot put @code{CODE} words that contain
14534: absolute addresses in this form in a relocatable image file. Workarounds
14535: are representing the address in some relative form (e.g., relative to
14536: the CFA, which is present in some register), or loading the address from
14537: a place where it is stored in a non-mangled form.
14538: @end itemize
14539: @end itemize
14540: 
14541: @node  Non-Relocatable Image Files, Data-Relocatable Image Files, Image File Background, Image Files
14542: @section Non-Relocatable Image Files
14543: @cindex non-relocatable image files
14544: @cindex image file, non-relocatable
14545: 
14546: These files are simple memory dumps of the dictionary. They are specific
14547: to the executable (i.e., @file{gforth} file) they were created
14548: with. What's worse, they are specific to the place on which the
14549: dictionary resided when the image was created. Now, there is no
14550: guarantee that the dictionary will reside at the same place the next
14551: time you start Gforth, so there's no guarantee that a non-relocatable
14552: image will work the next time (Gforth will complain instead of crashing,
14553: though).
14554: 
14555: You can create a non-relocatable image file with
14556: 
14557: 
14558: doc-savesystem
14559: 
14560: 
14561: @node Data-Relocatable Image Files, Fully Relocatable Image Files, Non-Relocatable Image Files, Image Files
14562: @section Data-Relocatable Image Files
14563: @cindex data-relocatable image files
14564: @cindex image file, data-relocatable
14565: 
14566: These files contain relocatable data addresses, but fixed code addresses
14567: (instead of tokens). They are specific to the executable (i.e.,
14568: @file{gforth} file) they were created with. For direct threading on some
14569: architectures (e.g., the i386), data-relocatable images do not work. You
14570: get a data-relocatable image, if you use @file{gforthmi} with a
14571: Gforth binary that is not doubly indirect threaded (@pxref{Fully
14572: Relocatable Image Files}).
14573: 
14574: @node Fully Relocatable Image Files, Stack and Dictionary Sizes, Data-Relocatable Image Files, Image Files
14575: @section Fully Relocatable Image Files
14576: @cindex fully relocatable image files
14577: @cindex image file, fully relocatable
14578: 
14579: @cindex @file{kern*.fi}, relocatability
14580: @cindex @file{gforth.fi}, relocatability
14581: These image files have relocatable data addresses, and tokens for code
14582: addresses. They can be used with different binaries (e.g., with and
14583: without debugging) on the same machine, and even across machines with
14584: the same data formats (byte order, cell size, floating point
14585: format). However, they are usually specific to the version of Gforth
14586: they were created with. The files @file{gforth.fi} and @file{kernl*.fi}
14587: are fully relocatable.
14588: 
14589: There are two ways to create a fully relocatable image file:
14590: 
14591: @menu
14592: * gforthmi::                    The normal way
14593: * cross.fs::                    The hard way
14594: @end menu
14595: 
14596: @node gforthmi, cross.fs, Fully Relocatable Image Files, Fully Relocatable Image Files
14597: @subsection @file{gforthmi}
14598: @cindex @file{comp-i.fs}
14599: @cindex @file{gforthmi}
14600: 
14601: You will usually use @file{gforthmi}. If you want to create an
14602: image @i{file} that contains everything you would load by invoking
14603: Gforth with @code{gforth @i{options}}, you simply say:
14604: @example
14605: gforthmi @i{file} @i{options}
14606: @end example
14607: 
14608: E.g., if you want to create an image @file{asm.fi} that has the file
14609: @file{asm.fs} loaded in addition to the usual stuff, you could do it
14610: like this:
14611: 
14612: @example
14613: gforthmi asm.fi asm.fs
14614: @end example
14615: 
14616: @file{gforthmi} is implemented as a sh script and works like this: It
14617: produces two non-relocatable images for different addresses and then
14618: compares them. Its output reflects this: first you see the output (if
14619: any) of the two Gforth invocations that produce the non-relocatable image
14620: files, then you see the output of the comparing program: It displays the
14621: offset used for data addresses and the offset used for code addresses;
14622: moreover, for each cell that cannot be represented correctly in the
14623: image files, it displays a line like this:
14624: 
14625: @example
14626:      78DC         BFFFFA50         BFFFFA40
14627: @end example
14628: 
14629: This means that at offset $78dc from @code{forthstart}, one input image
14630: contains $bffffa50, and the other contains $bffffa40. Since these cells
14631: cannot be represented correctly in the output image, you should examine
14632: these places in the dictionary and verify that these cells are dead
14633: (i.e., not read before they are written).
14634: 
14635: @cindex --application, @code{gforthmi} option
14636: If you insert the option @code{--application} in front of the image file
14637: name, you will get an image that uses the @code{--appl-image} option
14638: instead of the @code{--image-file} option (@pxref{Invoking
14639: Gforth}). When you execute such an image on Unix (by typing the image
14640: name as command), the Gforth engine will pass all options to the image
14641: instead of trying to interpret them as engine options.
14642: 
14643: If you type @file{gforthmi} with no arguments, it prints some usage
14644: instructions.
14645: 
14646: @cindex @code{savesystem} during @file{gforthmi}
14647: @cindex @code{bye} during @file{gforthmi}
14648: @cindex doubly indirect threaded code
14649: @cindex environment variables
14650: @cindex @code{GFORTHD} -- environment variable
14651: @cindex @code{GFORTH} -- environment variable
14652: @cindex @code{gforth-ditc}
14653: There are a few wrinkles: After processing the passed @i{options}, the
14654: words @code{savesystem} and @code{bye} must be visible. A special doubly
14655: indirect threaded version of the @file{gforth} executable is used for
14656: creating the non-relocatable images; you can pass the exact filename of
14657: this executable through the environment variable @code{GFORTHD}
14658: (default: @file{gforth-ditc}); if you pass a version that is not doubly
14659: indirect threaded, you will not get a fully relocatable image, but a
14660: data-relocatable image (because there is no code address offset). The
14661: normal @file{gforth} executable is used for creating the relocatable
14662: image; you can pass the exact filename of this executable through the
14663: environment variable @code{GFORTH}.
14664: 
14665: @node cross.fs,  , gforthmi, Fully Relocatable Image Files
14666: @subsection @file{cross.fs}
14667: @cindex @file{cross.fs}
14668: @cindex cross-compiler
14669: @cindex metacompiler
14670: @cindex target compiler
14671: 
14672: You can also use @code{cross}, a batch compiler that accepts a Forth-like
14673: programming language (@pxref{Cross Compiler}).
14674: 
14675: @code{cross} allows you to create image files for machines with
14676: different data sizes and data formats than the one used for generating
14677: the image file. You can also use it to create an application image that
14678: does not contain a Forth compiler. These features are bought with
14679: restrictions and inconveniences in programming. E.g., addresses have to
14680: be stored in memory with special words (@code{A!}, @code{A,}, etc.) in
14681: order to make the code relocatable.
14682: 
14683: 
14684: @node Stack and Dictionary Sizes, Running Image Files, Fully Relocatable Image Files, Image Files
14685: @section Stack and Dictionary Sizes
14686: @cindex image file, stack and dictionary sizes
14687: @cindex dictionary size default
14688: @cindex stack size default
14689: 
14690: If you invoke Gforth with a command line flag for the size
14691: (@pxref{Invoking Gforth}), the size you specify is stored in the
14692: dictionary. If you save the dictionary with @code{savesystem} or create
14693: an image with @file{gforthmi}, this size will become the default
14694: for the resulting image file. E.g., the following will create a
14695: fully relocatable version of @file{gforth.fi} with a 1MB dictionary:
14696: 
14697: @example
14698: gforthmi gforth.fi -m 1M
14699: @end example
14700: 
14701: In other words, if you want to set the default size for the dictionary
14702: and the stacks of an image, just invoke @file{gforthmi} with the
14703: appropriate options when creating the image.
14704: 
14705: @cindex stack size, cache-friendly
14706: Note: For cache-friendly behaviour (i.e., good performance), you should
14707: make the sizes of the stacks modulo, say, 2K, somewhat different. E.g.,
14708: the default stack sizes are: data: 16k (mod 2k=0); fp: 15.5k (mod
14709: 2k=1.5k); return: 15k(mod 2k=1k); locals: 14.5k (mod 2k=0.5k).
14710: 
14711: @node Running Image Files, Modifying the Startup Sequence, Stack and Dictionary Sizes, Image Files
14712: @section Running Image Files
14713: @cindex running image files
14714: @cindex invoking image files
14715: @cindex image file invocation
14716: 
14717: @cindex -i, invoke image file
14718: @cindex --image file, invoke image file
14719: You can invoke Gforth with an image file @i{image} instead of the
14720: default @file{gforth.fi} with the @code{-i} flag (@pxref{Invoking Gforth}):
14721: @example
14722: gforth -i @i{image}
14723: @end example
14724: 
14725: @cindex executable image file
14726: @cindex image file, executable
14727: If your operating system supports starting scripts with a line of the
14728: form @code{#! ...}, you just have to type the image file name to start
14729: Gforth with this image file (note that the file extension @code{.fi} is
14730: just a convention). I.e., to run Gforth with the image file @i{image},
14731: you can just type @i{image} instead of @code{gforth -i @i{image}}.
14732: This works because every @code{.fi} file starts with a line of this
14733: format:
14734: 
14735: @example
14736: #! /usr/local/bin/gforth-0.4.0 -i
14737: @end example
14738: 
14739: The file and pathname for the Gforth engine specified on this line is
14740: the specific Gforth executable that it was built against; i.e. the value
14741: of the environment variable @code{GFORTH} at the time that
14742: @file{gforthmi} was executed.
14743: 
14744: You can make use of the same shell capability to make a Forth source
14745: file into an executable. For example, if you place this text in a file:
14746: 
14747: @example
14748: #! /usr/local/bin/gforth
14749: 
14750: ." Hello, world" CR
14751: bye
14752: @end example
14753: 
14754: @noindent
14755: and then make the file executable (chmod +x in Unix), you can run it
14756: directly from the command line. The sequence @code{#!} is used in two
14757: ways; firstly, it is recognised as a ``magic sequence'' by the operating
14758: system@footnote{The Unix kernel actually recognises two types of files:
14759: executable files and files of data, where the data is processed by an
14760: interpreter that is specified on the ``interpreter line'' -- the first
14761: line of the file, starting with the sequence #!. There may be a small
14762: limit (e.g., 32) on the number of characters that may be specified on
14763: the interpreter line.} secondly it is treated as a comment character by
14764: Gforth. Because of the second usage, a space is required between
14765: @code{#!} and the path to the executable (moreover, some Unixes
14766: require the sequence @code{#! /}).
14767: 
14768: The disadvantage of this latter technique, compared with using
14769: @file{gforthmi}, is that it is slightly slower; the Forth source code is
14770: compiled on-the-fly, each time the program is invoked.
14771: 
14772: doc-#!
14773: 
14774: 
14775: @node Modifying the Startup Sequence,  , Running Image Files, Image Files
14776: @section Modifying the Startup Sequence
14777: @cindex startup sequence for image file
14778: @cindex image file initialization sequence
14779: @cindex initialization sequence of image file
14780: 
14781: You can add your own initialization to the startup sequence of an image
14782: through the deferred word @code{'cold}. @code{'cold} is invoked just
14783: before the image-specific command line processing (i.e., loading files
14784: and evaluating (@code{-e}) strings) starts.
14785: 
14786: A sequence for adding your initialization usually looks like this:
14787: 
14788: @example
14789: :noname
14790:     Defers 'cold \ do other initialization stuff (e.g., rehashing wordlists)
14791:     ... \ your stuff
14792: ; IS 'cold
14793: @end example
14794: 
14795: After @code{'cold}, Gforth processes the image options
14796: (@pxref{Invoking Gforth}), and then it performs @code{bootmessage},
14797: another deferred word.  This normally prints Gforth's startup message
14798: and does nothing else.
14799: 
14800: @cindex turnkey image files
14801: @cindex image file, turnkey applications
14802: So, if you want to make a turnkey image (i.e., an image for an
14803: application instead of an extended Forth system), you can do this in
14804: two ways:
14805: 
14806: @itemize @bullet
14807: 
14808: @item
14809: If you want to do your interpretation of the OS command-line
14810: arguments, hook into @code{'cold}.  In that case you probably also
14811: want to build the image with @code{gforthmi --application}
14812: (@pxref{gforthmi}) to keep the engine from processing OS command line
14813: options.  You can then do your own command-line processing with
14814: @code{next-arg} 
14815: 
14816: @item
14817: If you want to have the normal Gforth processing of OS command-line
14818: arguments, hook into @code{bootmessage}.
14819: 
14820: @end itemize
14821: 
14822: In either case, you probably do not want the word that you execute in
14823: these hooks to exit normally, but use @code{bye} or @code{throw}.
14824: Otherwise the Gforth startup process would continue and eventually
14825: present the Forth command line to the user.
14826: 
14827: doc-'cold
14828: doc-bootmessage
14829: 
14830: @c ******************************************************************
14831: @node Engine, Cross Compiler, Image Files, Top
14832: @chapter Engine
14833: @cindex engine
14834: @cindex virtual machine
14835: 
14836: Reading this chapter is not necessary for programming with Gforth. It
14837: may be helpful for finding your way in the Gforth sources.
14838: 
14839: The ideas in this section have also been published in the following
14840: papers: Bernd Paysan, @cite{ANS fig/GNU/??? Forth} (in German),
14841: Forth-Tagung '93; M. Anton Ertl,
14842: @cite{@uref{http://www.complang.tuwien.ac.at/papers/ertl93.ps.Z, A
14843: Portable Forth Engine}}, EuroForth '93; M. Anton Ertl,
14844: @cite{@uref{http://www.complang.tuwien.ac.at/papers/ertl02.ps.gz,
14845: Threaded code variations and optimizations (extended version)}},
14846: Forth-Tagung '02.
14847: 
14848: @menu
14849: * Portability::                 
14850: * Threading::                   
14851: * Primitives::                  
14852: * Performance::                 
14853: @end menu
14854: 
14855: @node Portability, Threading, Engine, Engine
14856: @section Portability
14857: @cindex engine portability
14858: 
14859: An important goal of the Gforth Project is availability across a wide
14860: range of personal machines. fig-Forth, and, to a lesser extent, F83,
14861: achieved this goal by manually coding the engine in assembly language
14862: for several then-popular processors. This approach is very
14863: labor-intensive and the results are short-lived due to progress in
14864: computer architecture.
14865: 
14866: @cindex C, using C for the engine
14867: Others have avoided this problem by coding in C, e.g., Mitch Bradley
14868: (cforth), Mikael Patel (TILE) and Dirk Zoller (pfe). This approach is
14869: particularly popular for UNIX-based Forths due to the large variety of
14870: architectures of UNIX machines. Unfortunately an implementation in C
14871: does not mix well with the goals of efficiency and with using
14872: traditional techniques: Indirect or direct threading cannot be expressed
14873: in C, and switch threading, the fastest technique available in C, is
14874: significantly slower. Another problem with C is that it is very
14875: cumbersome to express double integer arithmetic.
14876: 
14877: @cindex GNU C for the engine
14878: @cindex long long
14879: Fortunately, there is a portable language that does not have these
14880: limitations: GNU C, the version of C processed by the GNU C compiler
14881: (@pxref{C Extensions, , Extensions to the C Language Family, gcc.info,
14882: GNU C Manual}). Its labels as values feature (@pxref{Labels as Values, ,
14883: Labels as Values, gcc.info, GNU C Manual}) makes direct and indirect
14884: threading possible, its @code{long long} type (@pxref{Long Long, ,
14885: Double-Word Integers, gcc.info, GNU C Manual}) corresponds to Forth's
14886: double numbers on many systems.  GNU C is freely available on all
14887: important (and many unimportant) UNIX machines, VMS, 80386s running
14888: MS-DOS, the Amiga, and the Atari ST, so a Forth written in GNU C can run
14889: on all these machines.
14890: 
14891: Writing in a portable language has the reputation of producing code that
14892: is slower than assembly. For our Forth engine we repeatedly looked at
14893: the code produced by the compiler and eliminated most compiler-induced
14894: inefficiencies by appropriate changes in the source code.
14895: 
14896: @cindex explicit register declarations
14897: @cindex --enable-force-reg, configuration flag
14898: @cindex -DFORCE_REG
14899: However, register allocation cannot be portably influenced by the
14900: programmer, leading to some inefficiencies on register-starved
14901: machines. We use explicit register declarations (@pxref{Explicit Reg
14902: Vars, , Variables in Specified Registers, gcc.info, GNU C Manual}) to
14903: improve the speed on some machines. They are turned on by using the
14904: configuration flag @code{--enable-force-reg} (@code{gcc} switch
14905: @code{-DFORCE_REG}). Unfortunately, this feature not only depends on the
14906: machine, but also on the compiler version: On some machines some
14907: compiler versions produce incorrect code when certain explicit register
14908: declarations are used. So by default @code{-DFORCE_REG} is not used.
14909: 
14910: @node Threading, Primitives, Portability, Engine
14911: @section Threading
14912: @cindex inner interpreter implementation
14913: @cindex threaded code implementation
14914: 
14915: @cindex labels as values
14916: GNU C's labels as values extension (available since @code{gcc-2.0},
14917: @pxref{Labels as Values, , Labels as Values, gcc.info, GNU C Manual})
14918: makes it possible to take the address of @i{label} by writing
14919: @code{&&@i{label}}.  This address can then be used in a statement like
14920: @code{goto *@i{address}}. I.e., @code{goto *&&x} is the same as
14921: @code{goto x}.
14922: 
14923: @cindex @code{NEXT}, indirect threaded
14924: @cindex indirect threaded inner interpreter
14925: @cindex inner interpreter, indirect threaded
14926: With this feature an indirect threaded @code{NEXT} looks like:
14927: @example
14928: cfa = *ip++;
14929: ca = *cfa;
14930: goto *ca;
14931: @end example
14932: @cindex instruction pointer
14933: For those unfamiliar with the names: @code{ip} is the Forth instruction
14934: pointer; the @code{cfa} (code-field address) corresponds to ANS Forths
14935: execution token and points to the code field of the next word to be
14936: executed; The @code{ca} (code address) fetched from there points to some
14937: executable code, e.g., a primitive or the colon definition handler
14938: @code{docol}.
14939: 
14940: @cindex @code{NEXT}, direct threaded
14941: @cindex direct threaded inner interpreter
14942: @cindex inner interpreter, direct threaded
14943: Direct threading is even simpler:
14944: @example
14945: ca = *ip++;
14946: goto *ca;
14947: @end example
14948: 
14949: Of course we have packaged the whole thing neatly in macros called
14950: @code{NEXT} and @code{NEXT1} (the part of @code{NEXT} after fetching the cfa).
14951: 
14952: @menu
14953: * Scheduling::                  
14954: * Direct or Indirect Threaded?::  
14955: * Dynamic Superinstructions::   
14956: * DOES>::                       
14957: @end menu
14958: 
14959: @node Scheduling, Direct or Indirect Threaded?, Threading, Threading
14960: @subsection Scheduling
14961: @cindex inner interpreter optimization
14962: 
14963: There is a little complication: Pipelined and superscalar processors,
14964: i.e., RISC and some modern CISC machines can process independent
14965: instructions while waiting for the results of an instruction. The
14966: compiler usually reorders (schedules) the instructions in a way that
14967: achieves good usage of these delay slots. However, on our first tries
14968: the compiler did not do well on scheduling primitives. E.g., for
14969: @code{+} implemented as
14970: @example
14971: n=sp[0]+sp[1];
14972: sp++;
14973: sp[0]=n;
14974: NEXT;
14975: @end example
14976: the @code{NEXT} comes strictly after the other code, i.e., there is
14977: nearly no scheduling. After a little thought the problem becomes clear:
14978: The compiler cannot know that @code{sp} and @code{ip} point to different
14979: addresses (and the version of @code{gcc} we used would not know it even
14980: if it was possible), so it could not move the load of the cfa above the
14981: store to the TOS. Indeed the pointers could be the same, if code on or
14982: very near the top of stack were executed. In the interest of speed we
14983: chose to forbid this probably unused ``feature'' and helped the compiler
14984: in scheduling: @code{NEXT} is divided into several parts:
14985: @code{NEXT_P0}, @code{NEXT_P1} and @code{NEXT_P2}). @code{+} now looks
14986: like:
14987: @example
14988: NEXT_P0;
14989: n=sp[0]+sp[1];
14990: sp++;
14991: NEXT_P1;
14992: sp[0]=n;
14993: NEXT_P2;
14994: @end example
14995: 
14996: There are various schemes that distribute the different operations of
14997: NEXT between these parts in several ways; in general, different schemes
14998: perform best on different processors.  We use a scheme for most
14999: architectures that performs well for most processors of this
15000: architecture; in the future we may switch to benchmarking and chosing
15001: the scheme on installation time.
15002: 
15003: 
15004: @node Direct or Indirect Threaded?, Dynamic Superinstructions, Scheduling, Threading
15005: @subsection Direct or Indirect Threaded?
15006: @cindex threading, direct or indirect?
15007: 
15008: Threaded forth code consists of references to primitives (simple machine
15009: code routines like @code{+}) and to non-primitives (e.g., colon
15010: definitions, variables, constants); for a specific class of
15011: non-primitives (e.g., variables) there is one code routine (e.g.,
15012: @code{dovar}), but each variable needs a separate reference to its data.
15013: 
15014: Traditionally Forth has been implemented as indirect threaded code,
15015: because this allows to use only one cell to reference a non-primitive
15016: (basically you point to the data, and find the code address there).
15017: 
15018: @cindex primitive-centric threaded code
15019: However, threaded code in Gforth (since 0.6.0) uses two cells for
15020: non-primitives, one for the code address, and one for the data address;
15021: the data pointer is an immediate argument for the virtual machine
15022: instruction represented by the code address.  We call this
15023: @emph{primitive-centric} threaded code, because all code addresses point
15024: to simple primitives.  E.g., for a variable, the code address is for
15025: @code{lit} (also used for integer literals like @code{99}).
15026: 
15027: Primitive-centric threaded code allows us to use (faster) direct
15028: threading as dispatch method, completely portably (direct threaded code
15029: in Gforth before 0.6.0 required architecture-specific code).  It also
15030: eliminates the performance problems related to I-cache consistency that
15031: 386 implementations have with direct threaded code, and allows
15032: additional optimizations.
15033: 
15034: @cindex hybrid direct/indirect threaded code
15035: There is a catch, however: the @var{xt} parameter of @code{execute} can
15036: occupy only one cell, so how do we pass non-primitives with their code
15037: @emph{and} data addresses to them?  Our answer is to use indirect
15038: threaded dispatch for @code{execute} and other words that use a
15039: single-cell xt.  So, normal threaded code in colon definitions uses
15040: direct threading, and @code{execute} and similar words, which dispatch
15041: to xts on the data stack, use indirect threaded code.  We call this
15042: @emph{hybrid direct/indirect} threaded code.
15043: 
15044: @cindex engines, gforth vs. gforth-fast vs. gforth-itc
15045: @cindex gforth engine
15046: @cindex gforth-fast engine
15047: The engines @command{gforth} and @command{gforth-fast} use hybrid
15048: direct/indirect threaded code.  This means that with these engines you
15049: cannot use @code{,} to compile an xt.  Instead, you have to use
15050: @code{compile,}.
15051: 
15052: @cindex gforth-itc engine
15053: If you want to compile xts with @code{,}, use @command{gforth-itc}.
15054: This engine uses plain old indirect threaded code.  It still compiles in
15055: a primitive-centric style, so you cannot use @code{compile,} instead of
15056: @code{,} (e.g., for producing tables of xts with @code{] word1 word2
15057: ... [}).  If you want to do that, you have to use @command{gforth-itc}
15058: and execute @code{' , is compile,}.  Your program can check if it is
15059: running on a hybrid direct/indirect threaded engine or a pure indirect
15060: threaded engine with @code{threading-method} (@pxref{Threading Words}).
15061: 
15062: 
15063: @node Dynamic Superinstructions, DOES>, Direct or Indirect Threaded?, Threading
15064: @subsection Dynamic Superinstructions
15065: @cindex Dynamic superinstructions with replication
15066: @cindex Superinstructions
15067: @cindex Replication
15068: 
15069: The engines @command{gforth} and @command{gforth-fast} use another
15070: optimization: Dynamic superinstructions with replication.  As an
15071: example, consider the following colon definition:
15072: 
15073: @example
15074: : squared ( n1 -- n2 )
15075:   dup * ;
15076: @end example
15077: 
15078: Gforth compiles this into the threaded code sequence
15079: 
15080: @example
15081: dup
15082: *
15083: ;s
15084: @end example
15085: 
15086: In normal direct threaded code there is a code address occupying one
15087: cell for each of these primitives.  Each code address points to a
15088: machine code routine, and the interpreter jumps to this machine code in
15089: order to execute the primitive.  The routines for these three
15090: primitives are (in @command{gforth-fast} on the 386):
15091: 
15092: @example
15093: Code dup  
15094: ( $804B950 )  add     esi , # -4  \ $83 $C6 $FC 
15095: ( $804B953 )  add     ebx , # 4  \ $83 $C3 $4 
15096: ( $804B956 )  mov     dword ptr 4 [esi] , ecx  \ $89 $4E $4 
15097: ( $804B959 )  jmp     dword ptr FC [ebx]  \ $FF $63 $FC 
15098: end-code
15099: Code *  
15100: ( $804ACC4 )  mov     eax , dword ptr 4 [esi]  \ $8B $46 $4 
15101: ( $804ACC7 )  add     esi , # 4  \ $83 $C6 $4 
15102: ( $804ACCA )  add     ebx , # 4  \ $83 $C3 $4 
15103: ( $804ACCD )  imul    ecx , eax  \ $F $AF $C8 
15104: ( $804ACD0 )  jmp     dword ptr FC [ebx]  \ $FF $63 $FC 
15105: end-code
15106: Code ;s  
15107: ( $804A693 )  mov     eax , dword ptr [edi]  \ $8B $7 
15108: ( $804A695 )  add     edi , # 4  \ $83 $C7 $4 
15109: ( $804A698 )  lea     ebx , dword ptr 4 [eax]  \ $8D $58 $4 
15110: ( $804A69B )  jmp     dword ptr FC [ebx]  \ $FF $63 $FC 
15111: end-code
15112: @end example
15113: 
15114: With dynamic superinstructions and replication the compiler does not
15115: just lay down the threaded code, but also copies the machine code
15116: fragments, usually without the jump at the end.
15117: 
15118: @example
15119: ( $4057D27D )  add     esi , # -4  \ $83 $C6 $FC 
15120: ( $4057D280 )  add     ebx , # 4  \ $83 $C3 $4 
15121: ( $4057D283 )  mov     dword ptr 4 [esi] , ecx  \ $89 $4E $4 
15122: ( $4057D286 )  mov     eax , dword ptr 4 [esi]  \ $8B $46 $4 
15123: ( $4057D289 )  add     esi , # 4  \ $83 $C6 $4 
15124: ( $4057D28C )  add     ebx , # 4  \ $83 $C3 $4 
15125: ( $4057D28F )  imul    ecx , eax  \ $F $AF $C8 
15126: ( $4057D292 )  mov     eax , dword ptr [edi]  \ $8B $7 
15127: ( $4057D294 )  add     edi , # 4  \ $83 $C7 $4 
15128: ( $4057D297 )  lea     ebx , dword ptr 4 [eax]  \ $8D $58 $4 
15129: ( $4057D29A )  jmp     dword ptr FC [ebx]  \ $FF $63 $FC 
15130: @end example
15131: 
15132: Only when a threaded-code control-flow change happens (e.g., in
15133: @code{;s}), the jump is appended.  This optimization eliminates many of
15134: these jumps and makes the rest much more predictable.  The speedup
15135: depends on the processor and the application; on the Athlon and Pentium
15136: III this optimization typically produces a speedup by a factor of 2.
15137: 
15138: The code addresses in the direct-threaded code are set to point to the
15139: appropriate points in the copied machine code, in this example like
15140: this:
15141: 
15142: @example
15143: primitive  code address
15144:    dup       $4057D27D
15145:    *         $4057D286
15146:    ;s        $4057D292
15147: @end example
15148: 
15149: Thus there can be threaded-code jumps to any place in this piece of
15150: code.  This also simplifies decompilation quite a bit.
15151: 
15152: @cindex --no-dynamic command-line option
15153: @cindex --no-super command-line option
15154: You can disable this optimization with @option{--no-dynamic}.  You can
15155: use the copying without eliminating the jumps (i.e., dynamic
15156: replication, but without superinstructions) with @option{--no-super};
15157: this gives the branch prediction benefit alone; the effect on
15158: performance depends on the CPU; on the Athlon and Pentium III the
15159: speedup is a little less than for dynamic superinstructions with
15160: replication.
15161: 
15162: @cindex patching threaded code
15163: One use of these options is if you want to patch the threaded code.
15164: With superinstructions, many of the dispatch jumps are eliminated, so
15165: patching often has no effect.  These options preserve all the dispatch
15166: jumps.
15167: 
15168: @cindex --dynamic command-line option
15169: On some machines dynamic superinstructions are disabled by default,
15170: because it is unsafe on these machines.  However, if you feel
15171: adventurous, you can enable it with @option{--dynamic}.
15172: 
15173: @node DOES>,  , Dynamic Superinstructions, Threading
15174: @subsection DOES>
15175: @cindex @code{DOES>} implementation
15176: 
15177: @cindex @code{dodoes} routine
15178: @cindex @code{DOES>}-code
15179: One of the most complex parts of a Forth engine is @code{dodoes}, i.e.,
15180: the chunk of code executed by every word defined by a
15181: @code{CREATE}...@code{DOES>} pair; actually with primitive-centric code,
15182: this is only needed if the xt of the word is @code{execute}d. The main
15183: problem here is: How to find the Forth code to be executed, i.e. the
15184: code after the @code{DOES>} (the @code{DOES>}-code)? There are two
15185: solutions:
15186: 
15187: In fig-Forth the code field points directly to the @code{dodoes} and the
15188: @code{DOES>}-code address is stored in the cell after the code address
15189: (i.e. at @code{@i{CFA} cell+}). It may seem that this solution is
15190: illegal in the Forth-79 and all later standards, because in fig-Forth
15191: this address lies in the body (which is illegal in these
15192: standards). However, by making the code field larger for all words this
15193: solution becomes legal again.  We use this approach.  Leaving a cell
15194: unused in most words is a bit wasteful, but on the machines we are
15195: targeting this is hardly a problem.
15196: 
15197: 
15198: @node Primitives, Performance, Threading, Engine
15199: @section Primitives
15200: @cindex primitives, implementation
15201: @cindex virtual machine instructions, implementation
15202: 
15203: @menu
15204: * Automatic Generation::        
15205: * TOS Optimization::            
15206: * Produced code::               
15207: @end menu
15208: 
15209: @node Automatic Generation, TOS Optimization, Primitives, Primitives
15210: @subsection Automatic Generation
15211: @cindex primitives, automatic generation
15212: 
15213: @cindex @file{prims2x.fs}
15214: 
15215: Since the primitives are implemented in a portable language, there is no
15216: longer any need to minimize the number of primitives. On the contrary,
15217: having many primitives has an advantage: speed. In order to reduce the
15218: number of errors in primitives and to make programming them easier, we
15219: provide a tool, the primitive generator (@file{prims2x.fs} aka Vmgen,
15220: @pxref{Top, Vmgen, Introduction, vmgen, Vmgen}), that automatically
15221: generates most (and sometimes all) of the C code for a primitive from
15222: the stack effect notation.  The source for a primitive has the following
15223: form:
15224: 
15225: @cindex primitive source format
15226: @format
15227: @i{Forth-name}  ( @i{stack-effect} )        @i{category}    [@i{pronounc.}]
15228: [@code{""}@i{glossary entry}@code{""}]
15229: @i{C code}
15230: [@code{:}
15231: @i{Forth code}]
15232: @end format
15233: 
15234: The items in brackets are optional. The category and glossary fields
15235: are there for generating the documentation, the Forth code is there
15236: for manual implementations on machines without GNU C. E.g., the source
15237: for the primitive @code{+} is:
15238: @example
15239: +    ( n1 n2 -- n )   core    plus
15240: n = n1+n2;
15241: @end example
15242: 
15243: This looks like a specification, but in fact @code{n = n1+n2} is C
15244: code. Our primitive generation tool extracts a lot of information from
15245: the stack effect notations@footnote{We use a one-stack notation, even
15246: though we have separate data and floating-point stacks; The separate
15247: notation can be generated easily from the unified notation.}: The number
15248: of items popped from and pushed on the stack, their type, and by what
15249: name they are referred to in the C code. It then generates a C code
15250: prelude and postlude for each primitive. The final C code for @code{+}
15251: looks like this:
15252: 
15253: @example
15254: I_plus: /* + ( n1 n2 -- n ) */  /* label, stack effect */
15255: /*  */                          /* documentation */
15256: NAME("+")                       /* debugging output (with -DDEBUG) */
15257: @{
15258: DEF_CA                          /* definition of variable ca (indirect threading) */
15259: Cell n1;                        /* definitions of variables */
15260: Cell n2;
15261: Cell n;
15262: NEXT_P0;                        /* NEXT part 0 */
15263: n1 = (Cell) sp[1];              /* input */
15264: n2 = (Cell) TOS;
15265: sp += 1;                        /* stack adjustment */
15266: @{
15267: n = n1+n2;                      /* C code taken from the source */
15268: @}
15269: NEXT_P1;                        /* NEXT part 1 */
15270: TOS = (Cell)n;                  /* output */
15271: NEXT_P2;                        /* NEXT part 2 */
15272: @}
15273: @end example
15274: 
15275: This looks long and inefficient, but the GNU C compiler optimizes quite
15276: well and produces optimal code for @code{+} on, e.g., the R3000 and the
15277: HP RISC machines: Defining the @code{n}s does not produce any code, and
15278: using them as intermediate storage also adds no cost.
15279: 
15280: There are also other optimizations that are not illustrated by this
15281: example: assignments between simple variables are usually for free (copy
15282: propagation). If one of the stack items is not used by the primitive
15283: (e.g.  in @code{drop}), the compiler eliminates the load from the stack
15284: (dead code elimination). On the other hand, there are some things that
15285: the compiler does not do, therefore they are performed by
15286: @file{prims2x.fs}: The compiler does not optimize code away that stores
15287: a stack item to the place where it just came from (e.g., @code{over}).
15288: 
15289: While programming a primitive is usually easy, there are a few cases
15290: where the programmer has to take the actions of the generator into
15291: account, most notably @code{?dup}, but also words that do not (always)
15292: fall through to @code{NEXT}.
15293: 
15294: For more information
15295: 
15296: @node TOS Optimization, Produced code, Automatic Generation, Primitives
15297: @subsection TOS Optimization
15298: @cindex TOS optimization for primitives
15299: @cindex primitives, keeping the TOS in a register
15300: 
15301: An important optimization for stack machine emulators, e.g., Forth
15302: engines, is keeping  one or more of the top stack items in
15303: registers.  If a word has the stack effect @i{in1}...@i{inx} @code{--}
15304: @i{out1}...@i{outy}, keeping the top @i{n} items in registers
15305: @itemize @bullet
15306: @item
15307: is better than keeping @i{n-1} items, if @i{x>=n} and @i{y>=n},
15308: due to fewer loads from and stores to the stack.
15309: @item is slower than keeping @i{n-1} items, if @i{x<>y} and @i{x<n} and
15310: @i{y<n}, due to additional moves between registers.
15311: @end itemize
15312: 
15313: @cindex -DUSE_TOS
15314: @cindex -DUSE_NO_TOS
15315: In particular, keeping one item in a register is never a disadvantage,
15316: if there are enough registers. Keeping two items in registers is a
15317: disadvantage for frequent words like @code{?branch}, constants,
15318: variables, literals and @code{i}. Therefore our generator only produces
15319: code that keeps zero or one items in registers. The generated C code
15320: covers both cases; the selection between these alternatives is made at
15321: C-compile time using the switch @code{-DUSE_TOS}. @code{TOS} in the C
15322: code for @code{+} is just a simple variable name in the one-item case,
15323: otherwise it is a macro that expands into @code{sp[0]}. Note that the
15324: GNU C compiler tries to keep simple variables like @code{TOS} in
15325: registers, and it usually succeeds, if there are enough registers.
15326: 
15327: @cindex -DUSE_FTOS
15328: @cindex -DUSE_NO_FTOS
15329: The primitive generator performs the TOS optimization for the
15330: floating-point stack, too (@code{-DUSE_FTOS}). For floating-point
15331: operations the benefit of this optimization is even larger:
15332: floating-point operations take quite long on most processors, but can be
15333: performed in parallel with other operations as long as their results are
15334: not used. If the FP-TOS is kept in a register, this works. If
15335: it is kept on the stack, i.e., in memory, the store into memory has to
15336: wait for the result of the floating-point operation, lengthening the
15337: execution time of the primitive considerably.
15338: 
15339: The TOS optimization makes the automatic generation of primitives a
15340: bit more complicated. Just replacing all occurrences of @code{sp[0]} by
15341: @code{TOS} is not sufficient. There are some special cases to
15342: consider:
15343: @itemize @bullet
15344: @item In the case of @code{dup ( w -- w w )} the generator must not
15345: eliminate the store to the original location of the item on the stack,
15346: if the TOS optimization is turned on.
15347: @item Primitives with stack effects of the form @code{--}
15348: @i{out1}...@i{outy} must store the TOS to the stack at the start.
15349: Likewise, primitives with the stack effect @i{in1}...@i{inx} @code{--}
15350: must load the TOS from the stack at the end. But for the null stack
15351: effect @code{--} no stores or loads should be generated.
15352: @end itemize
15353: 
15354: @node Produced code,  , TOS Optimization, Primitives
15355: @subsection Produced code
15356: @cindex primitives, assembly code listing
15357: 
15358: @cindex @file{engine.s}
15359: To see what assembly code is produced for the primitives on your machine
15360: with your compiler and your flag settings, type @code{make engine.s} and
15361: look at the resulting file @file{engine.s}.  Alternatively, you can also
15362: disassemble the code of primitives with @code{see} on some architectures.
15363: 
15364: @node  Performance,  , Primitives, Engine
15365: @section Performance
15366: @cindex performance of some Forth interpreters
15367: @cindex engine performance
15368: @cindex benchmarking Forth systems
15369: @cindex Gforth performance
15370: 
15371: On RISCs the Gforth engine is very close to optimal; i.e., it is usually
15372: impossible to write a significantly faster threaded-code engine.
15373: 
15374: On register-starved machines like the 386 architecture processors
15375: improvements are possible, because @code{gcc} does not utilize the
15376: registers as well as a human, even with explicit register declarations;
15377: e.g., Bernd Beuster wrote a Forth system fragment in assembly language
15378: and hand-tuned it for the 486; this system is 1.19 times faster on the
15379: Sieve benchmark on a 486DX2/66 than Gforth compiled with
15380: @code{gcc-2.6.3} with @code{-DFORCE_REG}.  The situation has improved
15381: with gcc-2.95 and gforth-0.4.9; now the most important virtual machine
15382: registers fit in real registers (and we can even afford to use the TOS
15383: optimization), resulting in a speedup of 1.14 on the sieve over the
15384: earlier results.  And dynamic superinstructions provide another speedup
15385: (but only around a factor 1.2 on the 486).
15386: 
15387: @cindex Win32Forth performance
15388: @cindex NT Forth performance
15389: @cindex eforth performance
15390: @cindex ThisForth performance
15391: @cindex PFE performance
15392: @cindex TILE performance
15393: The potential advantage of assembly language implementations is not
15394: necessarily realized in complete Forth systems: We compared Gforth-0.5.9
15395: (direct threaded, compiled with @code{gcc-2.95.1} and
15396: @code{-DFORCE_REG}) with Win32Forth 1.2093 (newer versions are
15397: reportedly much faster), LMI's NT Forth (Beta, May 1994) and Eforth
15398: (with and without peephole (aka pinhole) optimization of the threaded
15399: code); all these systems were written in assembly language. We also
15400: compared Gforth with three systems written in C: PFE-0.9.14 (compiled
15401: with @code{gcc-2.6.3} with the default configuration for Linux:
15402: @code{-O2 -fomit-frame-pointer -DUSE_REGS -DUNROLL_NEXT}), ThisForth
15403: Beta (compiled with @code{gcc-2.6.3 -O3 -fomit-frame-pointer}; ThisForth
15404: employs peephole optimization of the threaded code) and TILE (compiled
15405: with @code{make opt}). We benchmarked Gforth, PFE, ThisForth and TILE on
15406: a 486DX2/66 under Linux. Kenneth O'Heskin kindly provided the results
15407: for Win32Forth and NT Forth on a 486DX2/66 with similar memory
15408: performance under Windows NT. Marcel Hendrix ported Eforth to Linux,
15409: then extended it to run the benchmarks, added the peephole optimizer,
15410: ran the benchmarks and reported the results.
15411: 
15412: We used four small benchmarks: the ubiquitous Sieve; bubble-sorting and
15413: matrix multiplication come from the Stanford integer benchmarks and have
15414: been translated into Forth by Martin Fraeman; we used the versions
15415: included in the TILE Forth package, but with bigger data set sizes; and
15416: a recursive Fibonacci number computation for benchmarking calling
15417: performance. The following table shows the time taken for the benchmarks
15418: scaled by the time taken by Gforth (in other words, it shows the speedup
15419: factor that Gforth achieved over the other systems).
15420: 
15421: @example
15422: relative       Win32-    NT       eforth       This-      
15423: time     Gforth Forth Forth eforth  +opt   PFE Forth  TILE
15424: sieve      1.00  2.16  1.78   2.16  1.32  2.46  4.96 13.37
15425: bubble     1.00  1.93  2.07   2.18  1.29  2.21        5.70
15426: matmul     1.00  1.92  1.76   1.90  0.96  2.06        5.32
15427: fib        1.00  2.32  2.03   1.86  1.31  2.64  4.55  6.54
15428: @end example
15429: 
15430: You may be quite surprised by the good performance of Gforth when
15431: compared with systems written in assembly language. One important reason
15432: for the disappointing performance of these other systems is probably
15433: that they are not written optimally for the 486 (e.g., they use the
15434: @code{lods} instruction). In addition, Win32Forth uses a comfortable,
15435: but costly method for relocating the Forth image: like @code{cforth}, it
15436: computes the actual addresses at run time, resulting in two address
15437: computations per @code{NEXT} (@pxref{Image File Background}).
15438: 
15439: The speedup of Gforth over PFE, ThisForth and TILE can be easily
15440: explained with the self-imposed restriction of the latter systems to
15441: standard C, which makes efficient threading impossible (however, the
15442: measured implementation of PFE uses a GNU C extension: @pxref{Global Reg
15443: Vars, , Defining Global Register Variables, gcc.info, GNU C Manual}).
15444: Moreover, current C compilers have a hard time optimizing other aspects
15445: of the ThisForth and the TILE source.
15446: 
15447: The performance of Gforth on 386 architecture processors varies widely
15448: with the version of @code{gcc} used. E.g., @code{gcc-2.5.8} failed to
15449: allocate any of the virtual machine registers into real machine
15450: registers by itself and would not work correctly with explicit register
15451: declarations, giving a significantly slower engine (on a 486DX2/66
15452: running the Sieve) than the one measured above.
15453: 
15454: Note that there have been several releases of Win32Forth since the
15455: release presented here, so the results presented above may have little
15456: predictive value for the performance of Win32Forth today (results for
15457: the current release on an i486DX2/66 are welcome).
15458: 
15459: @cindex @file{Benchres}
15460: In
15461: @cite{@uref{http://www.complang.tuwien.ac.at/papers/ertl&maierhofer95.ps.gz,
15462: Translating Forth to Efficient C}} by M. Anton Ertl and Martin
15463: Maierhofer (presented at EuroForth '95), an indirect threaded version of
15464: Gforth is compared with Win32Forth, NT Forth, PFE, ThisForth, and
15465: several native code systems; that version of Gforth is slower on a 486
15466: than the version used here. You can find a newer version of these
15467: measurements at
15468: @uref{http://www.complang.tuwien.ac.at/forth/performance.html}. You can
15469: find numbers for Gforth on various machines in @file{Benchres}.
15470: 
15471: @c ******************************************************************
15472: @c @node Binding to System Library, Cross Compiler, Engine, Top
15473: @c @chapter Binding to System Library
15474: 
15475: @c ****************************************************************
15476: @node Cross Compiler, Bugs, Engine, Top
15477: @chapter Cross Compiler
15478: @cindex @file{cross.fs}
15479: @cindex cross-compiler
15480: @cindex metacompiler
15481: @cindex target compiler
15482: 
15483: The cross compiler is used to bootstrap a Forth kernel. Since Gforth is
15484: mostly written in Forth, including crucial parts like the outer
15485: interpreter and compiler, it needs compiled Forth code to get
15486: started. The cross compiler allows to create new images for other
15487: architectures, even running under another Forth system.
15488: 
15489: @menu
15490: * Using the Cross Compiler::    
15491: * How the Cross Compiler Works::  
15492: @end menu
15493: 
15494: @node Using the Cross Compiler, How the Cross Compiler Works, Cross Compiler, Cross Compiler
15495: @section Using the Cross Compiler
15496: 
15497: The cross compiler uses a language that resembles Forth, but isn't. The
15498: main difference is that you can execute Forth code after definition,
15499: while you usually can't execute the code compiled by cross, because the
15500: code you are compiling is typically for a different computer than the
15501: one you are compiling on.
15502: 
15503: @c anton: This chapter is somewhat different from waht I would expect: I
15504: @c would expect an explanation of the cross language and how to create an
15505: @c application image with it.  The section explains some aspects of
15506: @c creating a Gforth kernel.
15507: 
15508: The Makefile is already set up to allow you to create kernels for new
15509: architectures with a simple make command. The generic kernels using the
15510: GCC compiled virtual machine are created in the normal build process
15511: with @code{make}. To create a embedded Gforth executable for e.g. the
15512: 8086 processor (running on a DOS machine), type
15513: 
15514: @example
15515: make kernl-8086.fi
15516: @end example
15517: 
15518: This will use the machine description from the @file{arch/8086}
15519: directory to create a new kernel. A machine file may look like that:
15520: 
15521: @example
15522: \ Parameter for target systems                         06oct92py
15523: 
15524:     4 Constant cell             \ cell size in bytes
15525:     2 Constant cell<<           \ cell shift to bytes
15526:     5 Constant cell>bit         \ cell shift to bits
15527:     8 Constant bits/char        \ bits per character
15528:     8 Constant bits/byte        \ bits per byte [default: 8]
15529:     8 Constant float            \ bytes per float
15530:     8 Constant /maxalign        \ maximum alignment in bytes
15531: false Constant bigendian        \ byte order
15532: ( true=big, false=little )
15533: 
15534: include machpc.fs               \ feature list
15535: @end example
15536: 
15537: This part is obligatory for the cross compiler itself, the feature list
15538: is used by the kernel to conditionally compile some features in and out,
15539: depending on whether the target supports these features.
15540: 
15541: There are some optional features, if you define your own primitives,
15542: have an assembler, or need special, nonstandard preparation to make the
15543: boot process work. @code{asm-include} includes an assembler,
15544: @code{prims-include} includes primitives, and @code{>boot} prepares for
15545: booting.
15546: 
15547: @example
15548: : asm-include    ." Include assembler" cr
15549:   s" arch/8086/asm.fs" included ;
15550: 
15551: : prims-include  ." Include primitives" cr
15552:   s" arch/8086/prim.fs" included ;
15553: 
15554: : >boot          ." Prepare booting" cr
15555:   s" ' boot >body into-forth 1+ !" evaluate ;
15556: @end example
15557: 
15558: These words are used as sort of macro during the cross compilation in
15559: the file @file{kernel/main.fs}. Instead of using these macros, it would
15560: be possible --- but more complicated --- to write a new kernel project
15561: file, too.
15562: 
15563: @file{kernel/main.fs} expects the machine description file name on the
15564: stack; the cross compiler itself (@file{cross.fs}) assumes that either
15565: @code{mach-file} leaves a counted string on the stack, or
15566: @code{machine-file} leaves an address, count pair of the filename on the
15567: stack.
15568: 
15569: The feature list is typically controlled using @code{SetValue}, generic
15570: files that are used by several projects can use @code{DefaultValue}
15571: instead. Both functions work like @code{Value}, when the value isn't
15572: defined, but @code{SetValue} works like @code{to} if the value is
15573: defined, and @code{DefaultValue} doesn't set anything, if the value is
15574: defined.
15575: 
15576: @example
15577: \ generic mach file for pc gforth                       03sep97jaw
15578: 
15579: true DefaultValue NIL  \ relocating
15580: 
15581: >ENVIRON
15582: 
15583: true DefaultValue file          \ controls the presence of the
15584:                                 \ file access wordset
15585: true DefaultValue OS            \ flag to indicate a operating system
15586: 
15587: true DefaultValue prims         \ true: primitives are c-code
15588: 
15589: true DefaultValue floating      \ floating point wordset is present
15590: 
15591: true DefaultValue glocals       \ gforth locals are present
15592:                                 \ will be loaded
15593: true DefaultValue dcomps        \ double number comparisons
15594: 
15595: true DefaultValue hash          \ hashing primitives are loaded/present
15596: 
15597: true DefaultValue xconds        \ used together with glocals,
15598:                                 \ special conditionals supporting gforths'
15599:                                 \ local variables
15600: true DefaultValue header        \ save a header information
15601: 
15602: true DefaultValue backtrace     \ enables backtrace code
15603: 
15604: false DefaultValue ec
15605: false DefaultValue crlf
15606: 
15607: cell 2 = [IF] &32 [ELSE] &256 [THEN] KB DefaultValue kernel-size
15608: 
15609: &16 KB          DefaultValue stack-size
15610: &15 KB &512 +   DefaultValue fstack-size
15611: &15 KB          DefaultValue rstack-size
15612: &14 KB &512 +   DefaultValue lstack-size
15613: @end example
15614: 
15615: @node How the Cross Compiler Works,  , Using the Cross Compiler, Cross Compiler
15616: @section How the Cross Compiler Works
15617: 
15618: @node Bugs, Origin, Cross Compiler, Top
15619: @appendix Bugs
15620: @cindex bug reporting
15621: 
15622: Known bugs are described in the file @file{BUGS} in the Gforth distribution.
15623: 
15624: If you find a bug, please submit a bug report through
15625: @uref{https://savannah.gnu.org/bugs/?func=addbug&group=gforth}.
15626: 
15627: @itemize @bullet
15628: @item
15629: A program (or a sequence of keyboard commands) that reproduces the bug.
15630: @item
15631: A description of what you think constitutes the buggy behaviour.
15632: @item
15633: The Gforth version used (it is announced at the start of an
15634: interactive Gforth session).
15635: @item
15636: The machine and operating system (on Unix
15637: systems @code{uname -a} will report this information).
15638: @item
15639: The installation options (you can find the configure options at the
15640: start of @file{config.status}) and configuration (@code{configure}
15641: output or @file{config.cache}).
15642: @item
15643: A complete list of changes (if any) you (or your installer) have made to the
15644: Gforth sources.
15645: @end itemize
15646: 
15647: For a thorough guide on reporting bugs read @ref{Bug Reporting, , How
15648: to Report Bugs, gcc.info, GNU C Manual}.
15649: 
15650: 
15651: @node Origin, Forth-related information, Bugs, Top
15652: @appendix Authors and Ancestors of Gforth
15653: 
15654: @section Authors and Contributors
15655: @cindex authors of Gforth
15656: @cindex contributors to Gforth
15657: 
15658: The Gforth project was started in mid-1992 by Bernd Paysan and Anton
15659: Ertl. The third major author was Jens Wilke.  Neal Crook contributed a
15660: lot to the manual.  Assemblers and disassemblers were contributed by
15661: Andrew McKewan, Christian Pirker, Bernd Thallner, and Michal Revucky.
15662: Lennart Benschop (who was one of Gforth's first users, in mid-1993)
15663: and Stuart Ramsden inspired us with their continuous feedback. Lennart
15664: Benshop contributed @file{glosgen.fs}, while Stuart Ramsden has been
15665: working on automatic support for calling C libraries. Helpful comments
15666: also came from Paul Kleinrubatscher, Christian Pirker, Dirk Zoller,
15667: Marcel Hendrix, John Wavrik, Barrie Stott, Marc de Groot, Jorge
15668: Acerada, Bruce Hoyt, Robert Epprecht, Dennis Ruffer and David
15669: N. Williams. Since the release of Gforth-0.2.1 there were also helpful
15670: comments from many others; thank you all, sorry for not listing you
15671: here (but digging through my mailbox to extract your names is on my
15672: to-do list).
15673: 
15674: Gforth also owes a lot to the authors of the tools we used (GCC, CVS,
15675: and autoconf, among others), and to the creators of the Internet: Gforth
15676: was developed across the Internet, and its authors did not meet
15677: physically for the first 4 years of development.
15678: 
15679: @section Pedigree
15680: @cindex pedigree of Gforth
15681: 
15682: Gforth descends from bigFORTH (1993) and fig-Forth.  Of course, a
15683: significant part of the design of Gforth was prescribed by ANS Forth.
15684: 
15685: Bernd Paysan wrote bigFORTH, a descendent from TurboForth, an unreleased
15686: 32 bit native code version of VolksForth for the Atari ST, written
15687: mostly by Dietrich Weineck.
15688: 
15689: VolksForth was written by Klaus Schleisiek, Bernd Pennemann, Georg
15690: Rehfeld and Dietrich Weineck for the C64 (called UltraForth there) in
15691: the mid-80s and ported to the Atari ST in 1986.  It descends from fig-Forth.
15692: 
15693: @c Henry Laxen and Mike Perry wrote F83 as a model implementation of the
15694: @c Forth-83 standard. !! Pedigree? When?
15695: 
15696: A team led by Bill Ragsdale implemented fig-Forth on many processors in
15697: 1979. Robert Selzer and Bill Ragsdale developed the original
15698: implementation of fig-Forth for the 6502 based on microForth.
15699: 
15700: The principal architect of microForth was Dean Sanderson. microForth was
15701: FORTH, Inc.'s first off-the-shelf product. It was developed in 1976 for
15702: the 1802, and subsequently implemented on the 8080, the 6800 and the
15703: Z80.
15704: 
15705: All earlier Forth systems were custom-made, usually by Charles Moore,
15706: who discovered (as he puts it) Forth during the late 60s. The first full
15707: Forth existed in 1971.
15708: 
15709: A part of the information in this section comes from
15710: @cite{@uref{http://www.forth.com/Content/History/History1.htm,The
15711: Evolution of Forth}} by Elizabeth D. Rather, Donald R. Colburn and
15712: Charles H. Moore, presented at the HOPL-II conference and preprinted
15713: in SIGPLAN Notices 28(3), 1993.  You can find more historical and
15714: genealogical information about Forth there.  For a more general (and
15715: graphical) Forth family tree look see
15716: @cite{@uref{http://www.complang.tuwien.ac.at/forth/family-tree/},
15717: Forth Family Tree and Timeline}.
15718: 
15719: @c ------------------------------------------------------------------
15720: @node Forth-related information, Licenses, Origin, Top
15721: @appendix Other Forth-related information
15722: @cindex Forth-related information
15723: 
15724: @c anton: I threw most of this stuff out, because it can be found through
15725: @c the FAQ and the FAQ is more likely to be up-to-date.
15726: 
15727: @cindex comp.lang.forth
15728: @cindex frequently asked questions
15729: There is an active news group (comp.lang.forth) discussing Forth
15730: (including Gforth) and Forth-related issues. Its
15731: @uref{http://www.complang.tuwien.ac.at/forth/faq/faq-general-2.html,FAQs}
15732: (frequently asked questions and their answers) contains a lot of
15733: information on Forth.  You should read it before posting to
15734: comp.lang.forth.
15735: 
15736: The ANS Forth standard is most usable in its
15737: @uref{http://www.taygeta.com/forth/dpans.html, HTML form}.
15738: 
15739: @c ---------------------------------------------------
15740: @node  Licenses, Word Index, Forth-related information, Top
15741: @appendix Licenses
15742: 
15743: @menu
15744: * GNU Free Documentation License::  License for copying this manual.
15745: * Copying::                         GPL (for copying this software).
15746: @end menu
15747: 
15748: @include fdl.texi
15749: 
15750: @include gpl.texi
15751: 
15752: 
15753: 
15754: @c ------------------------------------------------------------------
15755: @node Word Index, Concept Index, Licenses, Top
15756: @unnumbered Word Index
15757: 
15758: This index is a list of Forth words that have ``glossary'' entries
15759: within this manual. Each word is listed with its stack effect and
15760: wordset.
15761: 
15762: @printindex fn
15763: 
15764: @c anton: the name index seems superfluous given the word and concept indices.
15765: 
15766: @c @node Name Index, Concept Index, Word Index, Top
15767: @c @unnumbered Name Index
15768: 
15769: @c This index is a list of Forth words that have ``glossary'' entries
15770: @c within this manual.
15771: 
15772: @c @printindex ky
15773: 
15774: @c -------------------------------------------------------
15775: @node Concept Index,  , Word Index, Top
15776: @unnumbered Concept and Word Index
15777: 
15778: Not all entries listed in this index are present verbatim in the
15779: text. This index also duplicates, in abbreviated form, all of the words
15780: listed in the Word Index (only the names are listed for the words here).
15781: 
15782: @printindex cp
15783: 
15784: @bye
15785: 
15786: 
15787: 

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