File:  [gforth] / gforth / doc / gforth.ds
Revision 1.115: download - view: text, annotated - select for diffs
Tue Mar 11 21:18:32 2003 UTC (18 years, 8 months ago) by anton
Branches: MAIN
CVS tags: v0-6-1, HEAD
documentation changes
updated version number

    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
   60: (version @value{VERSION}, @value{UPDATED}),
   61: a fast and portable implementation of the ANS Forth language
   62: 
   63: Copyright @copyright{} 1995, 1996, 1997, 1998, 2000, 2003 Free Software Foundation, Inc.
   64: 
   65: @quotation
   66: Permission is granted to copy, distribute and/or modify this document
   67: under the terms of the GNU Free Documentation License, Version 1.1 or
   68: any later version published by the Free Software Foundation; with no
   69: Invariant Sections, with the Front-Cover texts being ``A GNU Manual,''
   70: and with the Back-Cover Texts as in (a) below.  A copy of the
   71: license is included in the section entitled ``GNU Free Documentation
   72: License.''
   73: 
   74: (a) The FSF's Back-Cover Text is: ``You have freedom to copy and modify
   75: this GNU Manual, like GNU software.  Copies published by the Free
   76: Software Foundation raise funds for GNU development.''
   77: @end quotation
   78: @end copying
   79: 
   80: @dircategory Software development
   81: @direntry
   82: * Gforth: (gforth).             A fast interpreter for the Forth language.
   83: @end direntry
   84: @c The Texinfo manual also recommends doing this, but for Gforth it may
   85: @c  not make much sense
   86: @c @dircategory Individual utilities
   87: @c @direntry
   88: @c * Gforth: (gforth)Invoking Gforth.      gforth, gforth-fast, gforthmi
   89: @c @end direntry
   90: 
   91: @titlepage
   92: @title Gforth
   93: @subtitle for version @value{VERSION}, @value{UPDATED}
   94: @author Neal Crook
   95: @author Anton Ertl
   96: @author David Kuehling
   97: @author Bernd Paysan
   98: @author Jens Wilke
   99: @page
  100: @vskip 0pt plus 1filll
  101: @insertcopying
  102: @end titlepage
  103: 
  104: @contents
  105: 
  106: @ifnottex
  107: @node Top, Goals, (dir), (dir)
  108: @top Gforth
  109: 
  110: @insertcopying
  111: @end ifnottex
  112: 
  113: @menu
  114: * Goals::                       About the Gforth Project
  115: * Gforth Environment::          Starting (and exiting) Gforth
  116: * Tutorial::                    Hands-on Forth Tutorial
  117: * Introduction::                An introduction to ANS Forth
  118: * Words::                       Forth words available in Gforth
  119: * Error messages::              How to interpret them
  120: * Tools::                       Programming tools
  121: * ANS conformance::             Implementation-defined options etc.
  122: * Standard vs Extensions::      Should I use extensions?
  123: * Model::                       The abstract machine of Gforth
  124: * Integrating Gforth::          Forth as scripting language for applications
  125: * Emacs and Gforth::            The Gforth Mode
  126: * Image Files::                 @code{.fi} files contain compiled code
  127: * Engine::                      The inner interpreter and the primitives
  128: * Cross Compiler::              The Cross Compiler
  129: * Bugs::                        How to report them
  130: * Origin::                      Authors and ancestors of Gforth
  131: * Forth-related information::   Books and places to look on the WWW
  132: * Licenses::                    
  133: * Word Index::                  An item for each Forth word
  134: * Concept Index::               A menu covering many topics
  135: 
  136: @detailmenu
  137:  --- The Detailed Node Listing ---
  138: 
  139: Gforth Environment
  140: 
  141: * Invoking Gforth::             Getting in
  142: * Leaving Gforth::              Getting out
  143: * Command-line editing::        
  144: * Environment variables::       that affect how Gforth starts up
  145: * Gforth Files::                What gets installed and where
  146: * Gforth in pipes::             
  147: * Startup speed::               When 35ms is not fast enough ...
  148: 
  149: Forth Tutorial
  150: 
  151: * Starting Gforth Tutorial::    
  152: * Syntax Tutorial::             
  153: * Crash Course Tutorial::       
  154: * Stack Tutorial::              
  155: * Arithmetics Tutorial::        
  156: * Stack Manipulation Tutorial::  
  157: * Using files for Forth code Tutorial::  
  158: * Comments Tutorial::           
  159: * Colon Definitions Tutorial::  
  160: * Decompilation Tutorial::      
  161: * Stack-Effect Comments Tutorial::  
  162: * Types Tutorial::              
  163: * Factoring Tutorial::          
  164: * Designing the stack effect Tutorial::  
  165: * Local Variables Tutorial::    
  166: * Conditional execution Tutorial::  
  167: * Flags and Comparisons Tutorial::  
  168: * General Loops Tutorial::      
  169: * Counted loops Tutorial::      
  170: * Recursion Tutorial::          
  171: * Leaving definitions or loops Tutorial::  
  172: * Return Stack Tutorial::       
  173: * Memory Tutorial::             
  174: * Characters and Strings Tutorial::  
  175: * Alignment Tutorial::          
  176: * Files Tutorial::              
  177: * Interpretation and Compilation Semantics and Immediacy Tutorial::  
  178: * Execution Tokens Tutorial::   
  179: * Exceptions Tutorial::         
  180: * Defining Words Tutorial::     
  181: * Arrays and Records Tutorial::  
  182: * POSTPONE Tutorial::           
  183: * Literal Tutorial::            
  184: * Advanced macros Tutorial::    
  185: * Compilation Tokens Tutorial::  
  186: * Wordlists and Search Order Tutorial::  
  187: 
  188: An Introduction to ANS Forth
  189: 
  190: * Introducing the Text Interpreter::  
  191: * Stacks and Postfix notation::  
  192: * Your first definition::       
  193: * How does that work?::         
  194: * Forth is written in Forth::   
  195: * Review - elements of a Forth system::  
  196: * Where to go next::            
  197: * Exercises::                   
  198: 
  199: Forth Words
  200: 
  201: * Notation::                    
  202: * Case insensitivity::          
  203: * Comments::                    
  204: * Boolean Flags::               
  205: * Arithmetic::                  
  206: * Stack Manipulation::          
  207: * Memory::                      
  208: * Control Structures::          
  209: * Defining Words::              
  210: * Interpretation and Compilation Semantics::  
  211: * Tokens for Words::            
  212: * Compiling words::             
  213: * The Text Interpreter::        
  214: * The Input Stream::            
  215: * Word Lists::                  
  216: * Environmental Queries::       
  217: * Files::                       
  218: * Blocks::                      
  219: * Other I/O::                   
  220: * Locals::                      
  221: * Structures::                  
  222: * Object-oriented Forth::       
  223: * Programming Tools::           
  224: * Assembler and Code Words::    
  225: * Threading Words::             
  226: * Passing Commands to the OS::  
  227: * Keeping track of Time::       
  228: * Miscellaneous Words::         
  229: 
  230: Arithmetic
  231: 
  232: * Single precision::            
  233: * Double precision::            Double-cell integer arithmetic
  234: * Bitwise operations::          
  235: * Numeric comparison::          
  236: * Mixed precision::             Operations with single and double-cell integers
  237: * Floating Point::              
  238: 
  239: Stack Manipulation
  240: 
  241: * Data stack::                  
  242: * Floating point stack::        
  243: * Return stack::                
  244: * Locals stack::                
  245: * Stack pointer manipulation::  
  246: 
  247: Memory
  248: 
  249: * Memory model::                
  250: * Dictionary allocation::       
  251: * Heap Allocation::             
  252: * Memory Access::               
  253: * Address arithmetic::          
  254: * Memory Blocks::               
  255: 
  256: Control Structures
  257: 
  258: * Selection::                   IF ... ELSE ... ENDIF
  259: * Simple Loops::                BEGIN ...
  260: * Counted Loops::               DO
  261: * Arbitrary control structures::  
  262: * Calls and returns::           
  263: * Exception Handling::          
  264: 
  265: Defining Words
  266: 
  267: * CREATE::                      
  268: * Variables::                   Variables and user variables
  269: * Constants::                   
  270: * Values::                      Initialised variables
  271: * Colon Definitions::           
  272: * Anonymous Definitions::       Definitions without names
  273: * Supplying names::             Passing definition names as strings
  274: * User-defined Defining Words::  
  275: * Deferred words::              Allow forward references
  276: * Aliases::                     
  277: 
  278: User-defined Defining Words
  279: 
  280: * CREATE..DOES> applications::  
  281: * CREATE..DOES> details::       
  282: * Advanced does> usage example::  
  283: * @code{Const-does>}::          
  284: 
  285: Interpretation and Compilation Semantics
  286: 
  287: * Combined words::              
  288: 
  289: Tokens for Words
  290: 
  291: * Execution token::             represents execution/interpretation semantics
  292: * Compilation token::           represents compilation semantics
  293: * Name token::                  represents named words
  294: 
  295: Compiling words
  296: 
  297: * Literals::                    Compiling data values
  298: * Macros::                      Compiling words
  299: 
  300: The Text Interpreter
  301: 
  302: * Input Sources::               
  303: * Number Conversion::           
  304: * Interpret/Compile states::    
  305: * Interpreter Directives::      
  306: 
  307: Word Lists
  308: 
  309: * Vocabularies::                
  310: * Why use word lists?::         
  311: * Word list example::           
  312: 
  313: Files
  314: 
  315: * Forth source files::          
  316: * General files::               
  317: * Search Paths::                
  318: 
  319: Search Paths
  320: 
  321: * Source Search Paths::         
  322: * General Search Paths::        
  323: 
  324: Other I/O
  325: 
  326: * Simple numeric output::       Predefined formats
  327: * Formatted numeric output::    Formatted (pictured) output
  328: * String Formats::              How Forth stores strings in memory
  329: * Displaying characters and strings::  Other stuff
  330: * Input::                       Input
  331: * Pipes::                       How to create your own pipes
  332: 
  333: Locals
  334: 
  335: * Gforth locals::               
  336: * ANS Forth locals::            
  337: 
  338: Gforth locals
  339: 
  340: * Where are locals visible by name?::  
  341: * How long do locals live?::    
  342: * Locals programming style::    
  343: * Locals implementation::       
  344: 
  345: Structures
  346: 
  347: * Why explicit structure support?::  
  348: * Structure Usage::             
  349: * Structure Naming Convention::  
  350: * Structure Implementation::    
  351: * Structure Glossary::          
  352: 
  353: Object-oriented Forth
  354: 
  355: * Why object-oriented programming?::  
  356: * Object-Oriented Terminology::  
  357: * Objects::                     
  358: * OOF::                         
  359: * Mini-OOF::                    
  360: * Comparison with other object models::  
  361: 
  362: The @file{objects.fs} model
  363: 
  364: * Properties of the Objects model::  
  365: * Basic Objects Usage::         
  366: * The Objects base class::      
  367: * Creating objects::            
  368: * Object-Oriented Programming Style::  
  369: * Class Binding::               
  370: * Method conveniences::         
  371: * Classes and Scoping::         
  372: * Dividing classes::            
  373: * Object Interfaces::           
  374: * Objects Implementation::      
  375: * Objects Glossary::            
  376: 
  377: The @file{oof.fs} model
  378: 
  379: * Properties of the OOF model::  
  380: * Basic OOF Usage::             
  381: * The OOF base class::          
  382: * Class Declaration::           
  383: * Class Implementation::        
  384: 
  385: The @file{mini-oof.fs} model
  386: 
  387: * Basic Mini-OOF Usage::        
  388: * Mini-OOF Example::            
  389: * Mini-OOF Implementation::     
  390: 
  391: Programming Tools
  392: 
  393: * Examining::                   
  394: * Forgetting words::            
  395: * Debugging::                   Simple and quick.
  396: * Assertions::                  Making your programs self-checking.
  397: * Singlestep Debugger::         Executing your program word by word.
  398: 
  399: Assembler and Code Words
  400: 
  401: * Code and ;code::              
  402: * Common Assembler::            Assembler Syntax
  403: * Common Disassembler::         
  404: * 386 Assembler::               Deviations and special cases
  405: * Alpha Assembler::             Deviations and special cases
  406: * MIPS assembler::              Deviations and special cases
  407: * Other assemblers::            How to write them
  408: 
  409: Tools
  410: 
  411: * ANS Report::                  Report the words used, sorted by wordset.
  412: 
  413: ANS conformance
  414: 
  415: * The Core Words::              
  416: * The optional Block word set::  
  417: * The optional Double Number word set::  
  418: * The optional Exception word set::  
  419: * The optional Facility word set::  
  420: * The optional File-Access word set::  
  421: * The optional Floating-Point word set::  
  422: * The optional Locals word set::  
  423: * The optional Memory-Allocation word set::  
  424: * The optional Programming-Tools word set::  
  425: * The optional Search-Order word set::  
  426: 
  427: The Core Words
  428: 
  429: * core-idef::                   Implementation Defined Options                   
  430: * core-ambcond::                Ambiguous Conditions                
  431: * core-other::                  Other System Documentation                  
  432: 
  433: The optional Block word set
  434: 
  435: * block-idef::                  Implementation Defined Options
  436: * block-ambcond::               Ambiguous Conditions               
  437: * block-other::                 Other System Documentation                 
  438: 
  439: The optional Double Number word set
  440: 
  441: * double-ambcond::              Ambiguous Conditions              
  442: 
  443: The optional Exception word set
  444: 
  445: * exception-idef::              Implementation Defined Options              
  446: 
  447: The optional Facility word set
  448: 
  449: * facility-idef::               Implementation Defined Options               
  450: * facility-ambcond::            Ambiguous Conditions            
  451: 
  452: The optional File-Access word set
  453: 
  454: * file-idef::                   Implementation Defined Options
  455: * file-ambcond::                Ambiguous Conditions                
  456: 
  457: The optional Floating-Point word set
  458: 
  459: * floating-idef::               Implementation Defined Options
  460: * floating-ambcond::            Ambiguous Conditions            
  461: 
  462: The optional Locals word set
  463: 
  464: * locals-idef::                 Implementation Defined Options                 
  465: * locals-ambcond::              Ambiguous Conditions              
  466: 
  467: The optional Memory-Allocation word set
  468: 
  469: * memory-idef::                 Implementation Defined Options                 
  470: 
  471: The optional Programming-Tools word set
  472: 
  473: * programming-idef::            Implementation Defined Options            
  474: * programming-ambcond::         Ambiguous Conditions         
  475: 
  476: The optional Search-Order word set
  477: 
  478: * search-idef::                 Implementation Defined Options                 
  479: * search-ambcond::              Ambiguous Conditions              
  480: 
  481: Emacs and Gforth
  482: 
  483: * Installing gforth.el::        Making Emacs aware of Forth.
  484: * Emacs Tags::                  Viewing the source of a word in Emacs.
  485: * Hilighting::                  Making Forth code look prettier.
  486: * Auto-Indentation::            Customizing auto-indentation.
  487: * Blocks Files::                Reading and writing blocks files.
  488: 
  489: Image Files
  490: 
  491: * Image Licensing Issues::      Distribution terms for images.
  492: * Image File Background::       Why have image files?
  493: * Non-Relocatable Image Files::  don't always work.
  494: * Data-Relocatable Image Files::  are better.
  495: * Fully Relocatable Image Files::  better yet.
  496: * Stack and Dictionary Sizes::  Setting the default sizes for an image.
  497: * Running Image Files::         @code{gforth -i @i{file}} or @i{file}.
  498: * Modifying the Startup Sequence::  and turnkey applications.
  499: 
  500: Fully Relocatable Image Files
  501: 
  502: * gforthmi::                    The normal way
  503: * cross.fs::                    The hard way
  504: 
  505: Engine
  506: 
  507: * Portability::                 
  508: * Threading::                   
  509: * Primitives::                  
  510: * Performance::                 
  511: 
  512: Threading
  513: 
  514: * Scheduling::                  
  515: * Direct or Indirect Threaded?::  
  516: * Dynamic Superinstructions::   
  517: * DOES>::                       
  518: 
  519: Primitives
  520: 
  521: * Automatic Generation::        
  522: * TOS Optimization::            
  523: * Produced code::               
  524: 
  525: Cross Compiler
  526: 
  527: * Using the Cross Compiler::    
  528: * How the Cross Compiler Works::  
  529: 
  530: Licenses
  531: 
  532: * GNU Free Documentation License::  License for copying this manual.
  533: * Copying::                         GPL (for copying this software).
  534: 
  535: @end detailmenu
  536: @end menu
  537: 
  538: @c ----------------------------------------------------------
  539: @iftex
  540: @unnumbered Preface
  541: @cindex Preface
  542: This manual documents Gforth. Some introductory material is provided for
  543: readers who are unfamiliar with Forth or who are migrating to Gforth
  544: from other Forth compilers. However, this manual is primarily a
  545: reference manual.
  546: @end iftex
  547: 
  548: @comment TODO much more blurb here.
  549: 
  550: @c ******************************************************************
  551: @node Goals, Gforth Environment, Top, Top
  552: @comment node-name,     next,           previous, up
  553: @chapter Goals of Gforth
  554: @cindex goals of the Gforth project
  555: The goal of the Gforth Project is to develop a standard model for
  556: ANS Forth. This can be split into several subgoals:
  557: 
  558: @itemize @bullet
  559: @item
  560: Gforth should conform to the ANS Forth Standard.
  561: @item
  562: It should be a model, i.e. it should define all the
  563: implementation-dependent things.
  564: @item
  565: It should become standard, i.e. widely accepted and used. This goal
  566: is the most difficult one.
  567: @end itemize
  568: 
  569: To achieve these goals Gforth should be
  570: @itemize @bullet
  571: @item
  572: Similar to previous models (fig-Forth, F83)
  573: @item
  574: Powerful. It should provide for all the things that are considered
  575: necessary today and even some that are not yet considered necessary.
  576: @item
  577: Efficient. It should not get the reputation of being exceptionally
  578: slow.
  579: @item
  580: Free.
  581: @item
  582: Available on many machines/easy to port.
  583: @end itemize
  584: 
  585: Have we achieved these goals? Gforth conforms to the ANS Forth
  586: standard. It may be considered a model, but we have not yet documented
  587: which parts of the model are stable and which parts we are likely to
  588: change. It certainly has not yet become a de facto standard, but it
  589: appears to be quite popular. It has some similarities to and some
  590: differences from previous models. It has some powerful features, but not
  591: yet everything that we envisioned. We certainly have achieved our
  592: execution speed goals (@pxref{Performance})@footnote{However, in 1998
  593: the bar was raised when the major commercial Forth vendors switched to
  594: native code compilers.}.  It is free and available on many machines.
  595: 
  596: @c ******************************************************************
  597: @node Gforth Environment, Tutorial, Goals, Top
  598: @chapter Gforth Environment
  599: @cindex Gforth environment
  600: 
  601: Note: ultimately, the Gforth man page will be auto-generated from the
  602: material in this chapter.
  603: 
  604: @menu
  605: * Invoking Gforth::             Getting in
  606: * Leaving Gforth::              Getting out
  607: * Command-line editing::        
  608: * Environment variables::       that affect how Gforth starts up
  609: * Gforth Files::                What gets installed and where
  610: * Gforth in pipes::             
  611: * Startup speed::               When 35ms is not fast enough ...
  612: @end menu
  613: 
  614: For related information about the creation of images see @ref{Image Files}.
  615: 
  616: @comment ----------------------------------------------
  617: @node Invoking Gforth, Leaving Gforth, Gforth Environment, Gforth Environment
  618: @section Invoking Gforth
  619: @cindex invoking Gforth
  620: @cindex running Gforth
  621: @cindex command-line options
  622: @cindex options on the command line
  623: @cindex flags on the command line
  624: 
  625: Gforth is made up of two parts; an executable ``engine'' (named
  626: @command{gforth} or @command{gforth-fast}) and an image file. To start it, you
  627: will usually just say @code{gforth} -- this automatically loads the
  628: default image file @file{gforth.fi}. In many other cases the default
  629: Gforth image will be invoked like this:
  630: @example
  631: gforth [file | -e forth-code] ...
  632: @end example
  633: @noindent
  634: This interprets the contents of the files and the Forth code in the order they
  635: are given.
  636: 
  637: In addition to the @command{gforth} engine, there is also an engine
  638: called @command{gforth-fast}, which is faster, but gives less
  639: informative error messages (@pxref{Error messages}) and may catch some
  640: stack underflows later or not at all.  You should use it for debugged,
  641: performance-critical programs.
  642: 
  643: Moreover, there is an engine called @command{gforth-itc}, which is
  644: useful in some backwards-compatibility situations (@pxref{Direct or
  645: Indirect Threaded?}).
  646: 
  647: In general, the command line looks like this:
  648: 
  649: @example
  650: gforth[-fast] [engine options] [image options]
  651: @end example
  652: 
  653: The engine options must come before the rest of the command
  654: line. They are:
  655: 
  656: @table @code
  657: @cindex -i, command-line option
  658: @cindex --image-file, command-line option
  659: @item --image-file @i{file}
  660: @itemx -i @i{file}
  661: Loads the Forth image @i{file} instead of the default
  662: @file{gforth.fi} (@pxref{Image Files}).
  663: 
  664: @cindex --appl-image, command-line option
  665: @item --appl-image @i{file}
  666: Loads the image @i{file} and leaves all further command-line arguments
  667: to the image (instead of processing them as engine options).  This is
  668: useful for building executable application images on Unix, built with
  669: @code{gforthmi --application ...}.
  670: 
  671: @cindex --path, command-line option
  672: @cindex -p, command-line option
  673: @item --path @i{path}
  674: @itemx -p @i{path}
  675: Uses @i{path} for searching the image file and Forth source code files
  676: instead of the default in the environment variable @code{GFORTHPATH} or
  677: the path specified at installation time (e.g.,
  678: @file{/usr/local/share/gforth/0.2.0:.}). A path is given as a list of
  679: directories, separated by @samp{:} (on Unix) or @samp{;} (on other OSs).
  680: 
  681: @cindex --dictionary-size, command-line option
  682: @cindex -m, command-line option
  683: @cindex @i{size} parameters for command-line options
  684: @cindex size of the dictionary and the stacks
  685: @item --dictionary-size @i{size}
  686: @itemx -m @i{size}
  687: Allocate @i{size} space for the Forth dictionary space instead of
  688: using the default specified in the image (typically 256K). The
  689: @i{size} specification for this and subsequent options consists of
  690: an integer and a unit (e.g.,
  691: @code{4M}). The unit can be one of @code{b} (bytes), @code{e} (element
  692: size, in this case Cells), @code{k} (kilobytes), @code{M} (Megabytes),
  693: @code{G} (Gigabytes), and @code{T} (Terabytes). If no unit is specified,
  694: @code{e} is used.
  695: 
  696: @cindex --data-stack-size, command-line option
  697: @cindex -d, command-line option
  698: @item --data-stack-size @i{size}
  699: @itemx -d @i{size}
  700: Allocate @i{size} space for the data stack instead of using the
  701: default specified in the image (typically 16K).
  702: 
  703: @cindex --return-stack-size, command-line option
  704: @cindex -r, command-line option
  705: @item --return-stack-size @i{size}
  706: @itemx -r @i{size}
  707: Allocate @i{size} space for the return stack instead of using the
  708: default specified in the image (typically 15K).
  709: 
  710: @cindex --fp-stack-size, command-line option
  711: @cindex -f, command-line option
  712: @item --fp-stack-size @i{size}
  713: @itemx -f @i{size}
  714: Allocate @i{size} space for the floating point stack instead of
  715: using the default specified in the image (typically 15.5K). In this case
  716: the unit specifier @code{e} refers to floating point numbers.
  717: 
  718: @cindex --locals-stack-size, command-line option
  719: @cindex -l, command-line option
  720: @item --locals-stack-size @i{size}
  721: @itemx -l @i{size}
  722: Allocate @i{size} space for the locals stack instead of using the
  723: default specified in the image (typically 14.5K).
  724: 
  725: @cindex -h, command-line option
  726: @cindex --help, command-line option
  727: @item --help
  728: @itemx -h
  729: Print a message about the command-line options
  730: 
  731: @cindex -v, command-line option
  732: @cindex --version, command-line option
  733: @item --version
  734: @itemx -v
  735: Print version and exit
  736: 
  737: @cindex --debug, command-line option
  738: @item --debug
  739: Print some information useful for debugging on startup.
  740: 
  741: @cindex --offset-image, command-line option
  742: @item --offset-image
  743: Start the dictionary at a slightly different position than would be used
  744: otherwise (useful for creating data-relocatable images,
  745: @pxref{Data-Relocatable Image Files}).
  746: 
  747: @cindex --no-offset-im, command-line option
  748: @item --no-offset-im
  749: Start the dictionary at the normal position.
  750: 
  751: @cindex --clear-dictionary, command-line option
  752: @item --clear-dictionary
  753: Initialize all bytes in the dictionary to 0 before loading the image
  754: (@pxref{Data-Relocatable Image Files}).
  755: 
  756: @cindex --die-on-signal, command-line-option
  757: @item --die-on-signal
  758: Normally Gforth handles most signals (e.g., the user interrupt SIGINT,
  759: or the segmentation violation SIGSEGV) by translating it into a Forth
  760: @code{THROW}. With this option, Gforth exits if it receives such a
  761: signal. This option is useful when the engine and/or the image might be
  762: severely broken (such that it causes another signal before recovering
  763: from the first); this option avoids endless loops in such cases.
  764: 
  765: @item --no-dynamic
  766: @item --dynamic
  767: Disable or enable dynamic superinstructions with replication
  768: (@pxref{Dynamic Superinstructions}).
  769: 
  770: @item --no-super
  771: Disable dynamic superinstructions, use just dynamic replication; this is
  772: useful if you want to patch threaded code (@pxref{Dynamic
  773: Superinstructions}).
  774: 
  775: @end table
  776: 
  777: @cindex loading files at startup
  778: @cindex executing code on startup
  779: @cindex batch processing with Gforth
  780: As explained above, the image-specific command-line arguments for the
  781: default image @file{gforth.fi} consist of a sequence of filenames and
  782: @code{-e @var{forth-code}} options that are interpreted in the sequence
  783: in which they are given. The @code{-e @var{forth-code}} or
  784: @code{--evaluate @var{forth-code}} option evaluates the Forth
  785: code. This option takes only one argument; if you want to evaluate more
  786: Forth words, you have to quote them or use @code{-e} several times. To exit
  787: after processing the command line (instead of entering interactive mode)
  788: append @code{-e bye} to the command line.
  789: 
  790: @cindex versions, invoking other versions of Gforth
  791: If you have several versions of Gforth installed, @code{gforth} will
  792: invoke the version that was installed last. @code{gforth-@i{version}}
  793: invokes a specific version. If your environment contains the variable
  794: @code{GFORTHPATH}, you may want to override it by using the
  795: @code{--path} option.
  796: 
  797: Not yet implemented:
  798: On startup the system first executes the system initialization file
  799: (unless the option @code{--no-init-file} is given; note that the system
  800: resulting from using this option may not be ANS Forth conformant). Then
  801: the user initialization file @file{.gforth.fs} is executed, unless the
  802: option @code{--no-rc} is given; this file is searched for in @file{.},
  803: then in @file{~}, then in the normal path (see above).
  804: 
  805: 
  806: 
  807: @comment ----------------------------------------------
  808: @node Leaving Gforth, Command-line editing, Invoking Gforth, Gforth Environment
  809: @section Leaving Gforth
  810: @cindex Gforth - leaving
  811: @cindex leaving Gforth
  812: 
  813: You can leave Gforth by typing @code{bye} or @kbd{Ctrl-d} (at the start
  814: of a line) or (if you invoked Gforth with the @code{--die-on-signal}
  815: option) @kbd{Ctrl-c}. When you leave Gforth, all of your definitions and
  816: data are discarded.  For ways of saving the state of the system before
  817: leaving Gforth see @ref{Image Files}.
  818: 
  819: doc-bye
  820: 
  821: 
  822: @comment ----------------------------------------------
  823: @node Command-line editing, Environment variables, Leaving Gforth, Gforth Environment
  824: @section Command-line editing
  825: @cindex command-line editing
  826: 
  827: Gforth maintains a history file that records every line that you type to
  828: the text interpreter. This file is preserved between sessions, and is
  829: used to provide a command-line recall facility; if you type @kbd{Ctrl-P}
  830: repeatedly you can recall successively older commands from this (or
  831: previous) session(s). The full list of command-line editing facilities is:
  832: 
  833: @itemize @bullet
  834: @item
  835: @kbd{Ctrl-p} (``previous'') (or up-arrow) to recall successively older
  836: commands from the history buffer.
  837: @item
  838: @kbd{Ctrl-n} (``next'') (or down-arrow) to recall successively newer commands
  839: from the history buffer.
  840: @item
  841: @kbd{Ctrl-f} (or right-arrow) to move the cursor right, non-destructively.
  842: @item
  843: @kbd{Ctrl-b} (or left-arrow) to move the cursor left, non-destructively.
  844: @item
  845: @kbd{Ctrl-h} (backspace) to delete the character to the left of the cursor,
  846: closing up the line.
  847: @item
  848: @kbd{Ctrl-k} to delete (``kill'') from the cursor to the end of the line.
  849: @item
  850: @kbd{Ctrl-a} to move the cursor to the start of the line.
  851: @item
  852: @kbd{Ctrl-e} to move the cursor to the end of the line.
  853: @item
  854: @key{RET} (@kbd{Ctrl-m}) or @key{LFD} (@kbd{Ctrl-j}) to submit the current
  855: line.
  856: @item
  857: @key{TAB} to step through all possible full-word completions of the word
  858: currently being typed.
  859: @item
  860: @kbd{Ctrl-d} on an empty line line to terminate Gforth (gracefully,
  861: using @code{bye}). 
  862: @item
  863: @kbd{Ctrl-x} (or @code{Ctrl-d} on a non-empty line) to delete the
  864: character under the cursor.
  865: @end itemize
  866: 
  867: When editing, displayable characters are inserted to the left of the
  868: cursor position; the line is always in ``insert'' (as opposed to
  869: ``overstrike'') mode.
  870: 
  871: @cindex history file
  872: @cindex @file{.gforth-history}
  873: On Unix systems, the history file is @file{~/.gforth-history} by
  874: default@footnote{i.e. it is stored in the user's home directory.}. You
  875: can find out the name and location of your history file using:
  876: 
  877: @example 
  878: history-file type \ Unix-class systems
  879: 
  880: history-file type \ Other systems
  881: history-dir  type
  882: @end example
  883: 
  884: If you enter long definitions by hand, you can use a text editor to
  885: paste them out of the history file into a Forth source file for reuse at
  886: a later time.
  887: 
  888: Gforth never trims the size of the history file, so you should do this
  889: periodically, if necessary.
  890: 
  891: @comment this is all defined in history.fs
  892: @comment NAC TODO the ctrl-D behaviour can either do a bye or a beep.. how is that option
  893: @comment chosen?
  894: 
  895: 
  896: @comment ----------------------------------------------
  897: @node Environment variables, Gforth Files, Command-line editing, Gforth Environment
  898: @section Environment variables
  899: @cindex environment variables
  900: 
  901: Gforth uses these environment variables:
  902: 
  903: @itemize @bullet
  904: @item
  905: @cindex @code{GFORTHHIST} -- environment variable
  906: @code{GFORTHHIST} -- (Unix systems only) specifies the directory in which to
  907: open/create the history file, @file{.gforth-history}. Default:
  908: @code{$HOME}.
  909: 
  910: @item
  911: @cindex @code{GFORTHPATH} -- environment variable
  912: @code{GFORTHPATH} -- specifies the path used when searching for the gforth image file and
  913: for Forth source-code files.
  914: 
  915: @item
  916: @cindex @code{GFORTH} -- environment variable
  917: @code{GFORTH} -- used by @file{gforthmi}, @xref{gforthmi}.
  918: 
  919: @item
  920: @cindex @code{GFORTHD} -- environment variable
  921: @code{GFORTHD} -- used by @file{gforthmi}, @xref{gforthmi}.
  922: 
  923: @item
  924: @cindex @code{TMP}, @code{TEMP} - environment variable
  925: @code{TMP}, @code{TEMP} - (non-Unix systems only) used as a potential
  926: location for the history file.
  927: @end itemize
  928: 
  929: @comment also POSIXELY_CORRECT LINES COLUMNS HOME but no interest in
  930: @comment mentioning these.
  931: 
  932: All the Gforth environment variables default to sensible values if they
  933: are not set.
  934: 
  935: 
  936: @comment ----------------------------------------------
  937: @node Gforth Files, Gforth in pipes, Environment variables, Gforth Environment
  938: @section Gforth files
  939: @cindex Gforth files
  940: 
  941: When you install Gforth on a Unix system, it installs files in these
  942: locations by default:
  943: 
  944: @itemize @bullet
  945: @item
  946: @file{/usr/local/bin/gforth}
  947: @item
  948: @file{/usr/local/bin/gforthmi}
  949: @item
  950: @file{/usr/local/man/man1/gforth.1} - man page.
  951: @item
  952: @file{/usr/local/info} - the Info version of this manual.
  953: @item
  954: @file{/usr/local/lib/gforth/<version>/...} - Gforth @file{.fi} files.
  955: @item
  956: @file{/usr/local/share/gforth/<version>/TAGS} - Emacs TAGS file.
  957: @item
  958: @file{/usr/local/share/gforth/<version>/...} - Gforth source files.
  959: @item
  960: @file{.../emacs/site-lisp/gforth.el} - Emacs gforth mode.
  961: @end itemize
  962: 
  963: You can select different places for installation by using
  964: @code{configure} options (listed with @code{configure --help}).
  965: 
  966: @comment ----------------------------------------------
  967: @node Gforth in pipes, Startup speed, Gforth Files, Gforth Environment
  968: @section Gforth in pipes
  969: @cindex pipes, Gforth as part of
  970: 
  971: Gforth can be used in pipes created elsewhere (described here).  It can
  972: also create pipes on its own (@pxref{Pipes}).
  973: 
  974: @cindex input from pipes
  975: If you pipe into Gforth, your program should read with @code{read-file}
  976: or @code{read-line} from @code{stdin} (@pxref{General files}).
  977: @code{Key} does not recognize the end of input.  Words like
  978: @code{accept} echo the input and are therefore usually not useful for
  979: reading from a pipe.  You have to invoke the Forth program with an OS
  980: command-line option, as you have no chance to use the Forth command line
  981: (the text interpreter would try to interpret the pipe input).
  982: 
  983: @cindex output in pipes
  984: You can output to a pipe with @code{type}, @code{emit}, @code{cr} etc.
  985: 
  986: @cindex silent exiting from Gforth
  987: When you write to a pipe that has been closed at the other end, Gforth
  988: receives a SIGPIPE signal (``pipe broken'').  Gforth translates this
  989: into the exception @code{broken-pipe-error}.  If your application does
  990: not catch that exception, the system catches it and exits, usually
  991: silently (unless you were working on the Forth command line; then it
  992: prints an error message and exits).  This is usually the desired
  993: behaviour.
  994: 
  995: If you do not like this behaviour, you have to catch the exception
  996: yourself, and react to it.
  997: 
  998: Here's an example of an invocation of Gforth that is usable in a pipe:
  999: 
 1000: @example
 1001: gforth -e ": foo begin pad dup 10 stdin read-file throw dup while \
 1002:  type repeat ; foo bye"
 1003: @end example
 1004: 
 1005: This example just copies the input verbatim to the output.  A very
 1006: simple pipe containing this example looks like this:
 1007: 
 1008: @example
 1009: cat startup.fs |
 1010: gforth -e ": foo begin pad dup 80 stdin read-file throw dup while \
 1011:  type repeat ; foo bye"|
 1012: head
 1013: @end example
 1014: 
 1015: @cindex stderr and pipes
 1016: Pipes involving Gforth's @code{stderr} output do not work.
 1017: 
 1018: @comment ----------------------------------------------
 1019: @node Startup speed,  , Gforth in pipes, Gforth Environment
 1020: @section Startup speed
 1021: @cindex Startup speed
 1022: @cindex speed, startup
 1023: 
 1024: If Gforth is used for CGI scripts or in shell scripts, its startup
 1025: speed may become a problem.  On a 300MHz 21064a under Linux-2.2.13 with
 1026: glibc-2.0.7, @code{gforth -e bye} takes about 24.6ms user and 11.3ms
 1027: system time.
 1028: 
 1029: If startup speed is a problem, you may consider the following ways to
 1030: improve it; or you may consider ways to reduce the number of startups
 1031: (for example, by using Fast-CGI).
 1032: 
 1033: An easy step that influences Gforth startup speed is the use of the
 1034: @option{--no-dynamic} option; this decreases image loading speed, but
 1035: increases compile-time and run-time.
 1036: 
 1037: Another step to improve startup speed is to statically link Gforth, by
 1038: building it with @code{XLDFLAGS=-static}.  This requires more memory for
 1039: the code and will therefore slow down the first invocation, but
 1040: subsequent invocations avoid the dynamic linking overhead.  Another
 1041: disadvantage is that Gforth won't profit from library upgrades.  As a
 1042: result, @code{gforth-static -e bye} takes about 17.1ms user and
 1043: 8.2ms system time.
 1044: 
 1045: The next step to improve startup speed is to use a non-relocatable image
 1046: (@pxref{Non-Relocatable Image Files}).  You can create this image with
 1047: @code{gforth -e "savesystem gforthnr.fi bye"} and later use it with
 1048: @code{gforth -i gforthnr.fi ...}.  This avoids the relocation overhead
 1049: and a part of the copy-on-write overhead.  The disadvantage is that the
 1050: non-relocatable image does not work if the OS gives Gforth a different
 1051: address for the dictionary, for whatever reason; so you better provide a
 1052: fallback on a relocatable image.  @code{gforth-static -i gforthnr.fi -e
 1053: bye} takes about 15.3ms user and 7.5ms system time.
 1054: 
 1055: The final step is to disable dictionary hashing in Gforth.  Gforth
 1056: builds the hash table on startup, which takes much of the startup
 1057: overhead. You can do this by commenting out the @code{include hash.fs}
 1058: in @file{startup.fs} and everything that requires @file{hash.fs} (at the
 1059: moment @file{table.fs} and @file{ekey.fs}) and then doing @code{make}.
 1060: The disadvantages are that functionality like @code{table} and
 1061: @code{ekey} is missing and that text interpretation (e.g., compiling)
 1062: now takes much longer. So, you should only use this method if there is
 1063: no significant text interpretation to perform (the script should be
 1064: compiled into the image, amongst other things).  @code{gforth-static -i
 1065: gforthnrnh.fi -e bye} takes about 2.1ms user and 6.1ms system time.
 1066: 
 1067: @c ******************************************************************
 1068: @node Tutorial, Introduction, Gforth Environment, Top
 1069: @chapter Forth Tutorial
 1070: @cindex Tutorial
 1071: @cindex Forth Tutorial
 1072: 
 1073: @c Topics from nac's Introduction that could be mentioned:
 1074: @c press <ret> after each line
 1075: @c Prompt
 1076: @c numbers vs. words in dictionary on text interpretation
 1077: @c what happens on redefinition
 1078: @c parsing words (in particular, defining words)
 1079: 
 1080: The difference of this chapter from the Introduction
 1081: (@pxref{Introduction}) is that this tutorial is more fast-paced, should
 1082: be used while sitting in front of a computer, and covers much more
 1083: material, but does not explain how the Forth system works.
 1084: 
 1085: This tutorial can be used with any ANS-compliant Forth; any
 1086: Gforth-specific features are marked as such and you can skip them if you
 1087: work with another Forth.  This tutorial does not explain all features of
 1088: Forth, just enough to get you started and give you some ideas about the
 1089: facilities available in Forth.  Read the rest of the manual and the
 1090: standard when you are through this.
 1091: 
 1092: The intended way to use this tutorial is that you work through it while
 1093: sitting in front of the console, take a look at the examples and predict
 1094: what they will do, then try them out; if the outcome is not as expected,
 1095: find out why (e.g., by trying out variations of the example), so you
 1096: understand what's going on.  There are also some assignments that you
 1097: should solve.
 1098: 
 1099: This tutorial assumes that you have programmed before and know what,
 1100: e.g., a loop is.
 1101: 
 1102: @c !! explain compat library
 1103: 
 1104: @menu
 1105: * Starting Gforth Tutorial::    
 1106: * Syntax Tutorial::             
 1107: * Crash Course Tutorial::       
 1108: * Stack Tutorial::              
 1109: * Arithmetics Tutorial::        
 1110: * Stack Manipulation Tutorial::  
 1111: * Using files for Forth code Tutorial::  
 1112: * Comments Tutorial::           
 1113: * Colon Definitions Tutorial::  
 1114: * Decompilation Tutorial::      
 1115: * Stack-Effect Comments Tutorial::  
 1116: * Types Tutorial::              
 1117: * Factoring Tutorial::          
 1118: * Designing the stack effect Tutorial::  
 1119: * Local Variables Tutorial::    
 1120: * Conditional execution Tutorial::  
 1121: * Flags and Comparisons Tutorial::  
 1122: * General Loops Tutorial::      
 1123: * Counted loops Tutorial::      
 1124: * Recursion Tutorial::          
 1125: * Leaving definitions or loops Tutorial::  
 1126: * Return Stack Tutorial::       
 1127: * Memory Tutorial::             
 1128: * Characters and Strings Tutorial::  
 1129: * Alignment Tutorial::          
 1130: * Files Tutorial::              
 1131: * Interpretation and Compilation Semantics and Immediacy Tutorial::  
 1132: * Execution Tokens Tutorial::   
 1133: * Exceptions Tutorial::         
 1134: * Defining Words Tutorial::     
 1135: * Arrays and Records Tutorial::  
 1136: * POSTPONE Tutorial::           
 1137: * Literal Tutorial::            
 1138: * Advanced macros Tutorial::    
 1139: * Compilation Tokens Tutorial::  
 1140: * Wordlists and Search Order Tutorial::  
 1141: @end menu
 1142: 
 1143: @node Starting Gforth Tutorial, Syntax Tutorial, Tutorial, Tutorial
 1144: @section Starting Gforth
 1145: @cindex starting Gforth tutorial
 1146: You can start Gforth by typing its name:
 1147: 
 1148: @example
 1149: gforth
 1150: @end example
 1151: 
 1152: That puts you into interactive mode; you can leave Gforth by typing
 1153: @code{bye}.  While in Gforth, you can edit the command line and access
 1154: the command line history with cursor keys, similar to bash.
 1155: 
 1156: 
 1157: @node Syntax Tutorial, Crash Course Tutorial, Starting Gforth Tutorial, Tutorial
 1158: @section Syntax
 1159: @cindex syntax tutorial
 1160: 
 1161: A @dfn{word} is a sequence of arbitrary characters (expcept white
 1162: space).  Words are separated by white space.  E.g., each of the
 1163: following lines contains exactly one word:
 1164: 
 1165: @example
 1166: word
 1167: !@@#$%^&*()
 1168: 1234567890
 1169: 5!a
 1170: @end example
 1171: 
 1172: A frequent beginner's error is to leave away necessary white space,
 1173: resulting in an error like @samp{Undefined word}; so if you see such an
 1174: error, check if you have put spaces wherever necessary.
 1175: 
 1176: @example
 1177: ." hello, world" \ correct
 1178: ."hello, world"  \ gives an "Undefined word" error
 1179: @end example
 1180: 
 1181: Gforth and most other Forth systems ignore differences in case (they are
 1182: case-insensitive), i.e., @samp{word} is the same as @samp{Word}.  If
 1183: your system is case-sensitive, you may have to type all the examples
 1184: given here in upper case.
 1185: 
 1186: 
 1187: @node Crash Course Tutorial, Stack Tutorial, Syntax Tutorial, Tutorial
 1188: @section Crash Course
 1189: 
 1190: Type
 1191: 
 1192: @example
 1193: 0 0 !
 1194: here execute
 1195: ' catch >body 20 erase abort
 1196: ' (quit) >body 20 erase
 1197: @end example
 1198: 
 1199: The last two examples are guaranteed to destroy parts of Gforth (and
 1200: most other systems), so you better leave Gforth afterwards (if it has
 1201: not finished by itself).  On some systems you may have to kill gforth
 1202: from outside (e.g., in Unix with @code{kill}).
 1203: 
 1204: Now that you know how to produce crashes (and that there's not much to
 1205: them), let's learn how to produce meaningful programs.
 1206: 
 1207: 
 1208: @node Stack Tutorial, Arithmetics Tutorial, Crash Course Tutorial, Tutorial
 1209: @section Stack
 1210: @cindex stack tutorial
 1211: 
 1212: The most obvious feature of Forth is the stack.  When you type in a
 1213: number, it is pushed on the stack.  You can display the content of the
 1214: stack with @code{.s}.
 1215: 
 1216: @example
 1217: 1 2 .s
 1218: 3 .s
 1219: @end example
 1220: 
 1221: @code{.s} displays the top-of-stack to the right, i.e., the numbers
 1222: appear in @code{.s} output as they appeared in the input.
 1223: 
 1224: You can print the top of stack element with @code{.}.
 1225: 
 1226: @example
 1227: 1 2 3 . . .
 1228: @end example
 1229: 
 1230: In general, words consume their stack arguments (@code{.s} is an
 1231: exception).
 1232: 
 1233: @assignment
 1234: What does the stack contain after @code{5 6 7 .}?
 1235: @endassignment
 1236: 
 1237: 
 1238: @node Arithmetics Tutorial, Stack Manipulation Tutorial, Stack Tutorial, Tutorial
 1239: @section Arithmetics
 1240: @cindex arithmetics tutorial
 1241: 
 1242: The words @code{+}, @code{-}, @code{*}, @code{/}, and @code{mod} always
 1243: operate on the top two stack items:
 1244: 
 1245: @example
 1246: 2 2 .s
 1247: + .s
 1248: .
 1249: 2 1 - .
 1250: 7 3 mod .
 1251: @end example
 1252: 
 1253: The operands of @code{-}, @code{/}, and @code{mod} are in the same order
 1254: as in the corresponding infix expression (this is generally the case in
 1255: Forth).
 1256: 
 1257: Parentheses are superfluous (and not available), because the order of
 1258: the words unambiguously determines the order of evaluation and the
 1259: operands:
 1260: 
 1261: @example
 1262: 3 4 + 5 * .
 1263: 3 4 5 * + .
 1264: @end example
 1265: 
 1266: @assignment
 1267: What are the infix expressions corresponding to the Forth code above?
 1268: Write @code{6-7*8+9} in Forth notation@footnote{This notation is also
 1269: known as Postfix or RPN (Reverse Polish Notation).}.
 1270: @endassignment
 1271: 
 1272: To change the sign, use @code{negate}:
 1273: 
 1274: @example
 1275: 2 negate .
 1276: @end example
 1277: 
 1278: @assignment
 1279: Convert -(-3)*4-5 to Forth.
 1280: @endassignment
 1281: 
 1282: @code{/mod} performs both @code{/} and @code{mod}.
 1283: 
 1284: @example
 1285: 7 3 /mod . .
 1286: @end example
 1287: 
 1288: Reference: @ref{Arithmetic}.
 1289: 
 1290: 
 1291: @node Stack Manipulation Tutorial, Using files for Forth code Tutorial, Arithmetics Tutorial, Tutorial
 1292: @section Stack Manipulation
 1293: @cindex stack manipulation tutorial
 1294: 
 1295: Stack manipulation words rearrange the data on the stack.
 1296: 
 1297: @example
 1298: 1 .s drop .s
 1299: 1 .s dup .s drop drop .s
 1300: 1 2 .s over .s drop drop drop
 1301: 1 2 .s swap .s drop drop
 1302: 1 2 3 .s rot .s drop drop drop
 1303: @end example
 1304: 
 1305: These are the most important stack manipulation words.  There are also
 1306: variants that manipulate twice as many stack items:
 1307: 
 1308: @example
 1309: 1 2 3 4 .s 2swap .s 2drop 2drop
 1310: @end example
 1311: 
 1312: Two more stack manipulation words are:
 1313: 
 1314: @example
 1315: 1 2 .s nip .s drop
 1316: 1 2 .s tuck .s 2drop drop
 1317: @end example
 1318: 
 1319: @assignment
 1320: Replace @code{nip} and @code{tuck} with combinations of other stack
 1321: manipulation words.
 1322: 
 1323: @example
 1324: Given:          How do you get:
 1325: 1 2 3           3 2 1           
 1326: 1 2 3           1 2 3 2                 
 1327: 1 2 3           1 2 3 3                 
 1328: 1 2 3           1 3 3           
 1329: 1 2 3           2 1 3           
 1330: 1 2 3 4         4 3 2 1         
 1331: 1 2 3           1 2 3 1 2 3             
 1332: 1 2 3 4         1 2 3 4 1 2             
 1333: 1 2 3
 1334: 1 2 3           1 2 3 4                 
 1335: 1 2 3           1 3             
 1336: @end example
 1337: @endassignment
 1338: 
 1339: @example
 1340: 5 dup * .
 1341: @end example
 1342: 
 1343: @assignment
 1344: Write 17^3 and 17^4 in Forth, without writing @code{17} more than once.
 1345: Write a piece of Forth code that expects two numbers on the stack
 1346: (@var{a} and @var{b}, with @var{b} on top) and computes
 1347: @code{(a-b)(a+1)}.
 1348: @endassignment
 1349: 
 1350: Reference: @ref{Stack Manipulation}.
 1351: 
 1352: 
 1353: @node Using files for Forth code Tutorial, Comments Tutorial, Stack Manipulation Tutorial, Tutorial
 1354: @section Using files for Forth code
 1355: @cindex loading Forth code, tutorial
 1356: @cindex files containing Forth code, tutorial
 1357: 
 1358: While working at the Forth command line is convenient for one-line
 1359: examples and short one-off code, you probably want to store your source
 1360: code in files for convenient editing and persistence.  You can use your
 1361: favourite editor (Gforth includes Emacs support, @pxref{Emacs and
 1362: Gforth}) to create @var{file.fs} and use
 1363: 
 1364: @example
 1365: s" @var{file.fs}" included
 1366: @end example
 1367: 
 1368: to load it into your Forth system.  The file name extension I use for
 1369: Forth files is @samp{.fs}.
 1370: 
 1371: You can easily start Gforth with some files loaded like this:
 1372: 
 1373: @example
 1374: gforth @var{file1.fs} @var{file2.fs}
 1375: @end example
 1376: 
 1377: If an error occurs during loading these files, Gforth terminates,
 1378: whereas an error during @code{INCLUDED} within Gforth usually gives you
 1379: a Gforth command line.  Starting the Forth system every time gives you a
 1380: clean start every time, without interference from the results of earlier
 1381: tries.
 1382: 
 1383: I often put all the tests in a file, then load the code and run the
 1384: tests with
 1385: 
 1386: @example
 1387: gforth @var{code.fs} @var{tests.fs} -e bye
 1388: @end example
 1389: 
 1390: (often by performing this command with @kbd{C-x C-e} in Emacs).  The
 1391: @code{-e bye} ensures that Gforth terminates afterwards so that I can
 1392: restart this command without ado.
 1393: 
 1394: The advantage of this approach is that the tests can be repeated easily
 1395: every time the program ist changed, making it easy to catch bugs
 1396: introduced by the change.
 1397: 
 1398: Reference: @ref{Forth source files}.
 1399: 
 1400: 
 1401: @node Comments Tutorial, Colon Definitions Tutorial, Using files for Forth code Tutorial, Tutorial
 1402: @section Comments
 1403: @cindex comments tutorial
 1404: 
 1405: @example
 1406: \ That's a comment; it ends at the end of the line
 1407: ( Another comment; it ends here: )  .s
 1408: @end example
 1409: 
 1410: @code{\} and @code{(} are ordinary Forth words and therefore have to be
 1411: separated with white space from the following text.
 1412: 
 1413: @example
 1414: \This gives an "Undefined word" error
 1415: @end example
 1416: 
 1417: The first @code{)} ends a comment started with @code{(}, so you cannot
 1418: nest @code{(}-comments; and you cannot comment out text containing a
 1419: @code{)} with @code{( ... )}@footnote{therefore it's a good idea to
 1420: avoid @code{)} in word names.}.
 1421: 
 1422: I use @code{\}-comments for descriptive text and for commenting out code
 1423: of one or more line; I use @code{(}-comments for describing the stack
 1424: effect, the stack contents, or for commenting out sub-line pieces of
 1425: code.
 1426: 
 1427: The Emacs mode @file{gforth.el} (@pxref{Emacs and Gforth}) supports
 1428: these uses by commenting out a region with @kbd{C-x \}, uncommenting a
 1429: region with @kbd{C-u C-x \}, and filling a @code{\}-commented region
 1430: with @kbd{M-q}.
 1431: 
 1432: Reference: @ref{Comments}.
 1433: 
 1434: 
 1435: @node Colon Definitions Tutorial, Decompilation Tutorial, Comments Tutorial, Tutorial
 1436: @section Colon Definitions
 1437: @cindex colon definitions, tutorial
 1438: @cindex definitions, tutorial
 1439: @cindex procedures, tutorial
 1440: @cindex functions, tutorial
 1441: 
 1442: are similar to procedures and functions in other programming languages.
 1443: 
 1444: @example
 1445: : squared ( n -- n^2 )
 1446:    dup * ;
 1447: 5 squared .
 1448: 7 squared .
 1449: @end example
 1450: 
 1451: @code{:} starts the colon definition; its name is @code{squared}.  The
 1452: following comment describes its stack effect.  The words @code{dup *}
 1453: are not executed, but compiled into the definition.  @code{;} ends the
 1454: colon definition.
 1455: 
 1456: The newly-defined word can be used like any other word, including using
 1457: it in other definitions:
 1458: 
 1459: @example
 1460: : cubed ( n -- n^3 )
 1461:    dup squared * ;
 1462: -5 cubed .
 1463: : fourth-power ( n -- n^4 )
 1464:    squared squared ;
 1465: 3 fourth-power .
 1466: @end example
 1467: 
 1468: @assignment
 1469: Write colon definitions for @code{nip}, @code{tuck}, @code{negate}, and
 1470: @code{/mod} in terms of other Forth words, and check if they work (hint:
 1471: test your tests on the originals first).  Don't let the
 1472: @samp{redefined}-Messages spook you, they are just warnings.
 1473: @endassignment
 1474: 
 1475: Reference: @ref{Colon Definitions}.
 1476: 
 1477: 
 1478: @node Decompilation Tutorial, Stack-Effect Comments Tutorial, Colon Definitions Tutorial, Tutorial
 1479: @section Decompilation
 1480: @cindex decompilation tutorial
 1481: @cindex see tutorial
 1482: 
 1483: You can decompile colon definitions with @code{see}:
 1484: 
 1485: @example
 1486: see squared
 1487: see cubed
 1488: @end example
 1489: 
 1490: In Gforth @code{see} shows you a reconstruction of the source code from
 1491: the executable code.  Informations that were present in the source, but
 1492: not in the executable code, are lost (e.g., comments).
 1493: 
 1494: You can also decompile the predefined words:
 1495: 
 1496: @example
 1497: see .
 1498: see +
 1499: @end example
 1500: 
 1501: 
 1502: @node Stack-Effect Comments Tutorial, Types Tutorial, Decompilation Tutorial, Tutorial
 1503: @section Stack-Effect Comments
 1504: @cindex stack-effect comments, tutorial
 1505: @cindex --, tutorial
 1506: By convention the comment after the name of a definition describes the
 1507: stack effect: The part in from of the @samp{--} describes the state of
 1508: the stack before the execution of the definition, i.e., the parameters
 1509: that are passed into the colon definition; the part behind the @samp{--}
 1510: is the state of the stack after the execution of the definition, i.e.,
 1511: the results of the definition.  The stack comment only shows the top
 1512: stack items that the definition accesses and/or changes.
 1513: 
 1514: You should put a correct stack effect on every definition, even if it is
 1515: just @code{( -- )}.  You should also add some descriptive comment to
 1516: more complicated words (I usually do this in the lines following
 1517: @code{:}).  If you don't do this, your code becomes unreadable (because
 1518: you have to work through every definition before you can undertsand
 1519: any).
 1520: 
 1521: @assignment
 1522: The stack effect of @code{swap} can be written like this: @code{x1 x2 --
 1523: x2 x1}.  Describe the stack effect of @code{-}, @code{drop}, @code{dup},
 1524: @code{over}, @code{rot}, @code{nip}, and @code{tuck}.  Hint: When you
 1525: are done, you can compare your stack effects to those in this manual
 1526: (@pxref{Word Index}).
 1527: @endassignment
 1528: 
 1529: Sometimes programmers put comments at various places in colon
 1530: definitions that describe the contents of the stack at that place (stack
 1531: comments); i.e., they are like the first part of a stack-effect
 1532: comment. E.g.,
 1533: 
 1534: @example
 1535: : cubed ( n -- n^3 )
 1536:    dup squared  ( n n^2 ) * ;
 1537: @end example
 1538: 
 1539: In this case the stack comment is pretty superfluous, because the word
 1540: is simple enough.  If you think it would be a good idea to add such a
 1541: comment to increase readability, you should also consider factoring the
 1542: word into several simpler words (@pxref{Factoring Tutorial,,
 1543: Factoring}), which typically eliminates the need for the stack comment;
 1544: however, if you decide not to refactor it, then having such a comment is
 1545: better than not having it.
 1546: 
 1547: The names of the stack items in stack-effect and stack comments in the
 1548: standard, in this manual, and in many programs specify the type through
 1549: a type prefix, similar to Fortran and Hungarian notation.  The most
 1550: frequent prefixes are:
 1551: 
 1552: @table @code
 1553: @item n
 1554: signed integer
 1555: @item u
 1556: unsigned integer
 1557: @item c
 1558: character
 1559: @item f
 1560: Boolean flags, i.e. @code{false} or @code{true}.
 1561: @item a-addr,a-
 1562: Cell-aligned address
 1563: @item c-addr,c-
 1564: Char-aligned address (note that a Char may have two bytes in Windows NT)
 1565: @item xt
 1566: Execution token, same size as Cell
 1567: @item w,x
 1568: Cell, can contain an integer or an address.  It usually takes 32, 64 or
 1569: 16 bits (depending on your platform and Forth system). A cell is more
 1570: commonly known as machine word, but the term @emph{word} already means
 1571: something different in Forth.
 1572: @item d
 1573: signed double-cell integer
 1574: @item ud
 1575: unsigned double-cell integer
 1576: @item r
 1577: Float (on the FP stack)
 1578: @end table
 1579: 
 1580: You can find a more complete list in @ref{Notation}.
 1581: 
 1582: @assignment
 1583: Write stack-effect comments for all definitions you have written up to
 1584: now.
 1585: @endassignment
 1586: 
 1587: 
 1588: @node Types Tutorial, Factoring Tutorial, Stack-Effect Comments Tutorial, Tutorial
 1589: @section Types
 1590: @cindex types tutorial
 1591: 
 1592: In Forth the names of the operations are not overloaded; so similar
 1593: operations on different types need different names; e.g., @code{+} adds
 1594: integers, and you have to use @code{f+} to add floating-point numbers.
 1595: The following prefixes are often used for related operations on
 1596: different types:
 1597: 
 1598: @table @code
 1599: @item (none)
 1600: signed integer
 1601: @item u
 1602: unsigned integer
 1603: @item c
 1604: character
 1605: @item d
 1606: signed double-cell integer
 1607: @item ud, du
 1608: unsigned double-cell integer
 1609: @item 2
 1610: two cells (not-necessarily double-cell numbers)
 1611: @item m, um
 1612: mixed single-cell and double-cell operations
 1613: @item f
 1614: floating-point (note that in stack comments @samp{f} represents flags,
 1615: and @samp{r} represents FP numbers).
 1616: @end table
 1617: 
 1618: If there are no differences between the signed and the unsigned variant
 1619: (e.g., for @code{+}), there is only the prefix-less variant.
 1620: 
 1621: Forth does not perform type checking, neither at compile time, nor at
 1622: run time.  If you use the wrong oeration, the data are interpreted
 1623: incorrectly:
 1624: 
 1625: @example
 1626: -1 u.
 1627: @end example
 1628: 
 1629: If you have only experience with type-checked languages until now, and
 1630: have heard how important type-checking is, don't panic!  In my
 1631: experience (and that of other Forthers), type errors in Forth code are
 1632: usually easy to find (once you get used to it), the increased vigilance
 1633: of the programmer tends to catch some harder errors in addition to most
 1634: type errors, and you never have to work around the type system, so in
 1635: most situations the lack of type-checking seems to be a win (projects to
 1636: add type checking to Forth have not caught on).
 1637: 
 1638: 
 1639: @node Factoring Tutorial, Designing the stack effect Tutorial, Types Tutorial, Tutorial
 1640: @section Factoring
 1641: @cindex factoring tutorial
 1642: 
 1643: If you try to write longer definitions, you will soon find it hard to
 1644: keep track of the stack contents.  Therefore, good Forth programmers
 1645: tend to write only short definitions (e.g., three lines).  The art of
 1646: finding meaningful short definitions is known as factoring (as in
 1647: factoring polynomials).
 1648: 
 1649: Well-factored programs offer additional advantages: smaller, more
 1650: general words, are easier to test and debug and can be reused more and
 1651: better than larger, specialized words.
 1652: 
 1653: So, if you run into difficulties with stack management, when writing
 1654: code, try to define meaningful factors for the word, and define the word
 1655: in terms of those.  Even if a factor contains only two words, it is
 1656: often helpful.
 1657: 
 1658: Good factoring is not easy, and it takes some practice to get the knack
 1659: for it; but even experienced Forth programmers often don't find the
 1660: right solution right away, but only when rewriting the program.  So, if
 1661: you don't come up with a good solution immediately, keep trying, don't
 1662: despair.
 1663: 
 1664: @c example !!
 1665: 
 1666: 
 1667: @node Designing the stack effect Tutorial, Local Variables Tutorial, Factoring Tutorial, Tutorial
 1668: @section Designing the stack effect
 1669: @cindex Stack effect design, tutorial
 1670: @cindex design of stack effects, tutorial
 1671: 
 1672: In other languages you can use an arbitrary order of parameters for a
 1673: function; and since there is only one result, you don't have to deal with
 1674: the order of results, either.
 1675: 
 1676: In Forth (and other stack-based languages, e.g., Postscript) the
 1677: parameter and result order of a definition is important and should be
 1678: designed well.  The general guideline is to design the stack effect such
 1679: that the word is simple to use in most cases, even if that complicates
 1680: the implementation of the word.  Some concrete rules are:
 1681: 
 1682: @itemize @bullet
 1683: 
 1684: @item
 1685: Words consume all of their parameters (e.g., @code{.}).
 1686: 
 1687: @item
 1688: If there is a convention on the order of parameters (e.g., from
 1689: mathematics or another programming language), stick with it (e.g.,
 1690: @code{-}).
 1691: 
 1692: @item
 1693: If one parameter usually requires only a short computation (e.g., it is
 1694: a constant), pass it on the top of the stack.  Conversely, parameters
 1695: that usually require a long sequence of code to compute should be passed
 1696: as the bottom (i.e., first) parameter.  This makes the code easier to
 1697: read, because reader does not need to keep track of the bottom item
 1698: through a long sequence of code (or, alternatively, through stack
 1699: manipulations). E.g., @code{!} (store, @pxref{Memory}) expects the
 1700: address on top of the stack because it is usually simpler to compute
 1701: than the stored value (often the address is just a variable).
 1702: 
 1703: @item
 1704: Similarly, results that are usually consumed quickly should be returned
 1705: on the top of stack, whereas a result that is often used in long
 1706: computations should be passed as bottom result.  E.g., the file words
 1707: like @code{open-file} return the error code on the top of stack, because
 1708: it is usually consumed quickly by @code{throw}; moreover, the error code
 1709: has to be checked before doing anything with the other results.
 1710: 
 1711: @end itemize
 1712: 
 1713: These rules are just general guidelines, don't lose sight of the overall
 1714: goal to make the words easy to use.  E.g., if the convention rule
 1715: conflicts with the computation-length rule, you might decide in favour
 1716: of the convention if the word will be used rarely, and in favour of the
 1717: computation-length rule if the word will be used frequently (because
 1718: with frequent use the cost of breaking the computation-length rule would
 1719: be quite high, and frequent use makes it easier to remember an
 1720: unconventional order).
 1721: 
 1722: @c example !! structure package
 1723: 
 1724: 
 1725: @node Local Variables Tutorial, Conditional execution Tutorial, Designing the stack effect Tutorial, Tutorial
 1726: @section Local Variables
 1727: @cindex local variables, tutorial
 1728: 
 1729: You can define local variables (@emph{locals}) in a colon definition:
 1730: 
 1731: @example
 1732: : swap @{ a b -- b a @}
 1733:   b a ;
 1734: 1 2 swap .s 2drop
 1735: @end example
 1736: 
 1737: (If your Forth system does not support this syntax, include
 1738: @file{compat/anslocals.fs} first).
 1739: 
 1740: In this example @code{@{ a b -- b a @}} is the locals definition; it
 1741: takes two cells from the stack, puts the top of stack in @code{b} and
 1742: the next stack element in @code{a}.  @code{--} starts a comment ending
 1743: with @code{@}}.  After the locals definition, using the name of the
 1744: local will push its value on the stack.  You can leave the comment
 1745: part (@code{-- b a}) away:
 1746: 
 1747: @example
 1748: : swap ( x1 x2 -- x2 x1 )
 1749:   @{ a b @} b a ;
 1750: @end example
 1751: 
 1752: In Gforth you can have several locals definitions, anywhere in a colon
 1753: definition; in contrast, in a standard program you can have only one
 1754: locals definition per colon definition, and that locals definition must
 1755: be outside any controll structure.
 1756: 
 1757: With locals you can write slightly longer definitions without running
 1758: into stack trouble.  However, I recommend trying to write colon
 1759: definitions without locals for exercise purposes to help you gain the
 1760: essential factoring skills.
 1761: 
 1762: @assignment
 1763: Rewrite your definitions until now with locals
 1764: @endassignment
 1765: 
 1766: Reference: @ref{Locals}.
 1767: 
 1768: 
 1769: @node Conditional execution Tutorial, Flags and Comparisons Tutorial, Local Variables Tutorial, Tutorial
 1770: @section Conditional execution
 1771: @cindex conditionals, tutorial
 1772: @cindex if, tutorial
 1773: 
 1774: In Forth you can use control structures only inside colon definitions.
 1775: An @code{if}-structure looks like this:
 1776: 
 1777: @example
 1778: : abs ( n1 -- +n2 )
 1779:     dup 0 < if
 1780:         negate
 1781:     endif ;
 1782: 5 abs .
 1783: -5 abs .
 1784: @end example
 1785: 
 1786: @code{if} takes a flag from the stack.  If the flag is non-zero (true),
 1787: the following code is performed, otherwise execution continues after the
 1788: @code{endif} (or @code{else}).  @code{<} compares the top two stack
 1789: elements and prioduces a flag:
 1790: 
 1791: @example
 1792: 1 2 < .
 1793: 2 1 < .
 1794: 1 1 < .
 1795: @end example
 1796: 
 1797: Actually the standard name for @code{endif} is @code{then}.  This
 1798: tutorial presents the examples using @code{endif}, because this is often
 1799: less confusing for people familiar with other programming languages
 1800: where @code{then} has a different meaning.  If your system does not have
 1801: @code{endif}, define it with
 1802: 
 1803: @example
 1804: : endif postpone then ; immediate
 1805: @end example
 1806: 
 1807: You can optionally use an @code{else}-part:
 1808: 
 1809: @example
 1810: : min ( n1 n2 -- n )
 1811:   2dup < if
 1812:     drop
 1813:   else
 1814:     nip
 1815:   endif ;
 1816: 2 3 min .
 1817: 3 2 min .
 1818: @end example
 1819: 
 1820: @assignment
 1821: Write @code{min} without @code{else}-part (hint: what's the definition
 1822: of @code{nip}?).
 1823: @endassignment
 1824: 
 1825: Reference: @ref{Selection}.
 1826: 
 1827: 
 1828: @node Flags and Comparisons Tutorial, General Loops Tutorial, Conditional execution Tutorial, Tutorial
 1829: @section Flags and Comparisons
 1830: @cindex flags tutorial
 1831: @cindex comparison tutorial
 1832: 
 1833: In a false-flag all bits are clear (0 when interpreted as integer).  In
 1834: a canonical true-flag all bits are set (-1 as a twos-complement signed
 1835: integer); in many contexts (e.g., @code{if}) any non-zero value is
 1836: treated as true flag.
 1837: 
 1838: @example
 1839: false .
 1840: true .
 1841: true hex u. decimal
 1842: @end example
 1843: 
 1844: Comparison words produce canonical flags:
 1845: 
 1846: @example
 1847: 1 1 = .
 1848: 1 0= .
 1849: 0 1 < .
 1850: 0 0 < .
 1851: -1 1 u< . \ type error, u< interprets -1 as large unsigned number
 1852: -1 1 < .
 1853: @end example
 1854: 
 1855: Gforth supports all combinations of the prefixes @code{0 u d d0 du f f0}
 1856: (or none) and the comparisons @code{= <> < > <= >=}.  Only a part of
 1857: these combinations are standard (for details see the standard,
 1858: @ref{Numeric comparison}, @ref{Floating Point} or @ref{Word Index}).
 1859: 
 1860: You can use @code{and or xor invert} can be used as operations on
 1861: canonical flags.  Actually they are bitwise operations:
 1862: 
 1863: @example
 1864: 1 2 and .
 1865: 1 2 or .
 1866: 1 3 xor .
 1867: 1 invert .
 1868: @end example
 1869: 
 1870: You can convert a zero/non-zero flag into a canonical flag with
 1871: @code{0<>} (and complement it on the way with @code{0=}).
 1872: 
 1873: @example
 1874: 1 0= .
 1875: 1 0<> .
 1876: @end example
 1877: 
 1878: You can use the all-bits-set feature of canonical flags and the bitwise
 1879: operation of the Boolean operations to avoid @code{if}s:
 1880: 
 1881: @example
 1882: : foo ( n1 -- n2 )
 1883:   0= if
 1884:     14
 1885:   else
 1886:     0
 1887:   endif ;
 1888: 0 foo .
 1889: 1 foo .
 1890: 
 1891: : foo ( n1 -- n2 )
 1892:   0= 14 and ;
 1893: 0 foo .
 1894: 1 foo .
 1895: @end example
 1896: 
 1897: @assignment
 1898: Write @code{min} without @code{if}.
 1899: @endassignment
 1900: 
 1901: For reference, see @ref{Boolean Flags}, @ref{Numeric comparison}, and
 1902: @ref{Bitwise operations}.
 1903: 
 1904: 
 1905: @node General Loops Tutorial, Counted loops Tutorial, Flags and Comparisons Tutorial, Tutorial
 1906: @section General Loops
 1907: @cindex loops, indefinite, tutorial
 1908: 
 1909: The endless loop is the most simple one:
 1910: 
 1911: @example
 1912: : endless ( -- )
 1913:   0 begin
 1914:     dup . 1+
 1915:   again ;
 1916: endless
 1917: @end example
 1918: 
 1919: Terminate this loop by pressing @kbd{Ctrl-C} (in Gforth).  @code{begin}
 1920: does nothing at run-time, @code{again} jumps back to @code{begin}.
 1921: 
 1922: A loop with one exit at any place looks like this:
 1923: 
 1924: @example
 1925: : log2 ( +n1 -- n2 )
 1926: \ logarithmus dualis of n1>0, rounded down to the next integer
 1927:   assert( dup 0> )
 1928:   2/ 0 begin
 1929:     over 0> while
 1930:       1+ swap 2/ swap
 1931:   repeat
 1932:   nip ;
 1933: 7 log2 .
 1934: 8 log2 .
 1935: @end example
 1936: 
 1937: At run-time @code{while} consumes a flag; if it is 0, execution
 1938: continues behind the @code{repeat}; if the flag is non-zero, execution
 1939: continues behind the @code{while}.  @code{Repeat} jumps back to
 1940: @code{begin}, just like @code{again}.
 1941: 
 1942: In Forth there are many combinations/abbreviations, like @code{1+}.
 1943: However, @code{2/} is not one of them; it shifts its argument right by
 1944: one bit (arithmetic shift right):
 1945: 
 1946: @example
 1947: -5 2 / .
 1948: -5 2/ .
 1949: @end example
 1950: 
 1951: @code{assert(} is no standard word, but you can get it on systems other
 1952: then Gforth by including @file{compat/assert.fs}.  You can see what it
 1953: does by trying
 1954: 
 1955: @example
 1956: 0 log2 .
 1957: @end example
 1958: 
 1959: Here's a loop with an exit at the end:
 1960: 
 1961: @example
 1962: : log2 ( +n1 -- n2 )
 1963: \ logarithmus dualis of n1>0, rounded down to the next integer
 1964:   assert( dup 0 > )
 1965:   -1 begin
 1966:     1+ swap 2/ swap
 1967:     over 0 <=
 1968:   until
 1969:   nip ;
 1970: @end example
 1971: 
 1972: @code{Until} consumes a flag; if it is non-zero, execution continues at
 1973: the @code{begin}, otherwise after the @code{until}.
 1974: 
 1975: @assignment
 1976: Write a definition for computing the greatest common divisor.
 1977: @endassignment
 1978: 
 1979: Reference: @ref{Simple Loops}.
 1980: 
 1981: 
 1982: @node Counted loops Tutorial, Recursion Tutorial, General Loops Tutorial, Tutorial
 1983: @section Counted loops
 1984: @cindex loops, counted, tutorial
 1985: 
 1986: @example
 1987: : ^ ( n1 u -- n )
 1988: \ n = the uth power of u1
 1989:   1 swap 0 u+do
 1990:     over *
 1991:   loop
 1992:   nip ;
 1993: 3 2 ^ .
 1994: 4 3 ^ .
 1995: @end example
 1996: 
 1997: @code{U+do} (from @file{compat/loops.fs}, if your Forth system doesn't
 1998: have it) takes two numbers of the stack @code{( u3 u4 -- )}, and then
 1999: performs the code between @code{u+do} and @code{loop} for @code{u3-u4}
 2000: times (or not at all, if @code{u3-u4<0}).
 2001: 
 2002: You can see the stack effect design rules at work in the stack effect of
 2003: the loop start words: Since the start value of the loop is more
 2004: frequently constant than the end value, the start value is passed on
 2005: the top-of-stack.
 2006: 
 2007: You can access the counter of a counted loop with @code{i}:
 2008: 
 2009: @example
 2010: : fac ( u -- u! )
 2011:   1 swap 1+ 1 u+do
 2012:     i *
 2013:   loop ;
 2014: 5 fac .
 2015: 7 fac .
 2016: @end example
 2017: 
 2018: There is also @code{+do}, which expects signed numbers (important for
 2019: deciding whether to enter the loop).
 2020: 
 2021: @assignment
 2022: Write a definition for computing the nth Fibonacci number.
 2023: @endassignment
 2024: 
 2025: You can also use increments other than 1:
 2026: 
 2027: @example
 2028: : up2 ( n1 n2 -- )
 2029:   +do
 2030:     i .
 2031:   2 +loop ;
 2032: 10 0 up2
 2033: 
 2034: : down2 ( n1 n2 -- )
 2035:   -do
 2036:     i .
 2037:   2 -loop ;
 2038: 0 10 down2
 2039: @end example
 2040: 
 2041: Reference: @ref{Counted Loops}.
 2042: 
 2043: 
 2044: @node Recursion Tutorial, Leaving definitions or loops Tutorial, Counted loops Tutorial, Tutorial
 2045: @section Recursion
 2046: @cindex recursion tutorial
 2047: 
 2048: Usually the name of a definition is not visible in the definition; but
 2049: earlier definitions are usually visible:
 2050: 
 2051: @example
 2052: 1 0 / . \ "Floating-point unidentified fault" in Gforth on most platforms
 2053: : / ( n1 n2 -- n )
 2054:   dup 0= if
 2055:     -10 throw \ report division by zero
 2056:   endif
 2057:   /           \ old version
 2058: ;
 2059: 1 0 /
 2060: @end example
 2061: 
 2062: For recursive definitions you can use @code{recursive} (non-standard) or
 2063: @code{recurse}:
 2064: 
 2065: @example
 2066: : fac1 ( n -- n! ) recursive
 2067:  dup 0> if
 2068:    dup 1- fac1 *
 2069:  else
 2070:    drop 1
 2071:  endif ;
 2072: 7 fac1 .
 2073: 
 2074: : fac2 ( n -- n! )
 2075:  dup 0> if
 2076:    dup 1- recurse *
 2077:  else
 2078:    drop 1
 2079:  endif ;
 2080: 8 fac2 .
 2081: @end example
 2082: 
 2083: @assignment
 2084: Write a recursive definition for computing the nth Fibonacci number.
 2085: @endassignment
 2086: 
 2087: Reference (including indirect recursion): @xref{Calls and returns}.
 2088: 
 2089: 
 2090: @node Leaving definitions or loops Tutorial, Return Stack Tutorial, Recursion Tutorial, Tutorial
 2091: @section Leaving definitions or loops
 2092: @cindex leaving definitions, tutorial
 2093: @cindex leaving loops, tutorial
 2094: 
 2095: @code{EXIT} exits the current definition right away.  For every counted
 2096: loop that is left in this way, an @code{UNLOOP} has to be performed
 2097: before the @code{EXIT}:
 2098: 
 2099: @c !! real examples
 2100: @example
 2101: : ...
 2102:  ... u+do
 2103:    ... if
 2104:      ... unloop exit
 2105:    endif
 2106:    ...
 2107:  loop
 2108:  ... ;
 2109: @end example
 2110: 
 2111: @code{LEAVE} leaves the innermost counted loop right away:
 2112: 
 2113: @example
 2114: : ...
 2115:  ... u+do
 2116:    ... if
 2117:      ... leave
 2118:    endif
 2119:    ...
 2120:  loop
 2121:  ... ;
 2122: @end example
 2123: 
 2124: @c !! example
 2125: 
 2126: Reference: @ref{Calls and returns}, @ref{Counted Loops}.
 2127: 
 2128: 
 2129: @node Return Stack Tutorial, Memory Tutorial, Leaving definitions or loops Tutorial, Tutorial
 2130: @section Return Stack
 2131: @cindex return stack tutorial
 2132: 
 2133: In addition to the data stack Forth also has a second stack, the return
 2134: stack; most Forth systems store the return addresses of procedure calls
 2135: there (thus its name).  Programmers can also use this stack:
 2136: 
 2137: @example
 2138: : foo ( n1 n2 -- )
 2139:  .s
 2140:  >r .s
 2141:  r@@ .
 2142:  >r .s
 2143:  r@@ .
 2144:  r> .
 2145:  r@@ .
 2146:  r> . ;
 2147: 1 2 foo
 2148: @end example
 2149: 
 2150: @code{>r} takes an element from the data stack and pushes it onto the
 2151: return stack; conversely, @code{r>} moves an elementm from the return to
 2152: the data stack; @code{r@@} pushes a copy of the top of the return stack
 2153: on the return stack.
 2154: 
 2155: Forth programmers usually use the return stack for storing data
 2156: temporarily, if using the data stack alone would be too complex, and
 2157: factoring and locals are not an option:
 2158: 
 2159: @example
 2160: : 2swap ( x1 x2 x3 x4 -- x3 x4 x1 x2 )
 2161:  rot >r rot r> ;
 2162: @end example
 2163: 
 2164: The return address of the definition and the loop control parameters of
 2165: counted loops usually reside on the return stack, so you have to take
 2166: all items, that you have pushed on the return stack in a colon
 2167: definition or counted loop, from the return stack before the definition
 2168: or loop ends.  You cannot access items that you pushed on the return
 2169: stack outside some definition or loop within the definition of loop.
 2170: 
 2171: If you miscount the return stack items, this usually ends in a crash:
 2172: 
 2173: @example
 2174: : crash ( n -- )
 2175:   >r ;
 2176: 5 crash
 2177: @end example
 2178: 
 2179: You cannot mix using locals and using the return stack (according to the
 2180: standard; Gforth has no problem).  However, they solve the same
 2181: problems, so this shouldn't be an issue.
 2182: 
 2183: @assignment
 2184: Can you rewrite any of the definitions you wrote until now in a better
 2185: way using the return stack?
 2186: @endassignment
 2187: 
 2188: Reference: @ref{Return stack}.
 2189: 
 2190: 
 2191: @node Memory Tutorial, Characters and Strings Tutorial, Return Stack Tutorial, Tutorial
 2192: @section Memory
 2193: @cindex memory access/allocation tutorial
 2194: 
 2195: You can create a global variable @code{v} with
 2196: 
 2197: @example
 2198: variable v ( -- addr )
 2199: @end example
 2200: 
 2201: @code{v} pushes the address of a cell in memory on the stack.  This cell
 2202: was reserved by @code{variable}.  You can use @code{!} (store) to store
 2203: values into this cell and @code{@@} (fetch) to load the value from the
 2204: stack into memory:
 2205: 
 2206: @example
 2207: v .
 2208: 5 v ! .s
 2209: v @@ .
 2210: @end example
 2211: 
 2212: You can see a raw dump of memory with @code{dump}:
 2213: 
 2214: @example
 2215: v 1 cells .s dump
 2216: @end example
 2217: 
 2218: @code{Cells ( n1 -- n2 )} gives you the number of bytes (or, more
 2219: generally, address units (aus)) that @code{n1 cells} occupy.  You can
 2220: also reserve more memory:
 2221: 
 2222: @example
 2223: create v2 20 cells allot
 2224: v2 20 cells dump
 2225: @end example
 2226: 
 2227: creates a word @code{v2} and reserves 20 uninitialized cells; the
 2228: address pushed by @code{v2} points to the start of these 20 cells.  You
 2229: can use address arithmetic to access these cells:
 2230: 
 2231: @example
 2232: 3 v2 5 cells + !
 2233: v2 20 cells dump
 2234: @end example
 2235: 
 2236: You can reserve and initialize memory with @code{,}:
 2237: 
 2238: @example
 2239: create v3
 2240:   5 , 4 , 3 , 2 , 1 ,
 2241: v3 @@ .
 2242: v3 cell+ @@ .
 2243: v3 2 cells + @@ .
 2244: v3 5 cells dump
 2245: @end example
 2246: 
 2247: @assignment
 2248: Write a definition @code{vsum ( addr u -- n )} that computes the sum of
 2249: @code{u} cells, with the first of these cells at @code{addr}, the next
 2250: one at @code{addr cell+} etc.
 2251: @endassignment
 2252: 
 2253: You can also reserve memory without creating a new word:
 2254: 
 2255: @example
 2256: here 10 cells allot .
 2257: here .
 2258: @end example
 2259: 
 2260: @code{Here} pushes the start address of the memory area.  You should
 2261: store it somewhere, or you will have a hard time finding the memory area
 2262: again.
 2263: 
 2264: @code{Allot} manages dictionary memory.  The dictionary memory contains
 2265: the system's data structures for words etc. on Gforth and most other
 2266: Forth systems.  It is managed like a stack: You can free the memory that
 2267: you have just @code{allot}ed with
 2268: 
 2269: @example
 2270: -10 cells allot
 2271: here .
 2272: @end example
 2273: 
 2274: Note that you cannot do this if you have created a new word in the
 2275: meantime (because then your @code{allot}ed memory is no longer on the
 2276: top of the dictionary ``stack'').
 2277: 
 2278: Alternatively, you can use @code{allocate} and @code{free} which allow
 2279: freeing memory in any order:
 2280: 
 2281: @example
 2282: 10 cells allocate throw .s
 2283: 20 cells allocate throw .s
 2284: swap
 2285: free throw
 2286: free throw
 2287: @end example
 2288: 
 2289: The @code{throw}s deal with errors (e.g., out of memory).
 2290: 
 2291: And there is also a
 2292: @uref{http://www.complang.tuwien.ac.at/forth/garbage-collection.zip,
 2293: garbage collector}, which eliminates the need to @code{free} memory
 2294: explicitly.
 2295: 
 2296: Reference: @ref{Memory}.
 2297: 
 2298: 
 2299: @node Characters and Strings Tutorial, Alignment Tutorial, Memory Tutorial, Tutorial
 2300: @section Characters and Strings
 2301: @cindex strings tutorial
 2302: @cindex characters tutorial
 2303: 
 2304: On the stack characters take up a cell, like numbers.  In memory they
 2305: have their own size (one 8-bit byte on most systems), and therefore
 2306: require their own words for memory access:
 2307: 
 2308: @example
 2309: create v4 
 2310:   104 c, 97 c, 108 c, 108 c, 111 c,
 2311: v4 4 chars + c@@ .
 2312: v4 5 chars dump
 2313: @end example
 2314: 
 2315: The preferred representation of strings on the stack is @code{addr
 2316: u-count}, where @code{addr} is the address of the first character and
 2317: @code{u-count} is the number of characters in the string.
 2318: 
 2319: @example
 2320: v4 5 type
 2321: @end example
 2322: 
 2323: You get a string constant with
 2324: 
 2325: @example
 2326: s" hello, world" .s
 2327: type
 2328: @end example
 2329: 
 2330: Make sure you have a space between @code{s"} and the string; @code{s"}
 2331: is a normal Forth word and must be delimited with white space (try what
 2332: happens when you remove the space).
 2333: 
 2334: However, this interpretive use of @code{s"} is quite restricted: the
 2335: string exists only until the next call of @code{s"} (some Forth systems
 2336: keep more than one of these strings, but usually they still have a
 2337: limited lifetime).
 2338: 
 2339: @example
 2340: s" hello," s" world" .s
 2341: type
 2342: type
 2343: @end example
 2344: 
 2345: You can also use @code{s"} in a definition, and the resulting
 2346: strings then live forever (well, for as long as the definition):
 2347: 
 2348: @example
 2349: : foo s" hello," s" world" ;
 2350: foo .s
 2351: type
 2352: type
 2353: @end example
 2354: 
 2355: @assignment
 2356: @code{Emit ( c -- )} types @code{c} as character (not a number).
 2357: Implement @code{type ( addr u -- )}.
 2358: @endassignment
 2359: 
 2360: Reference: @ref{Memory Blocks}.
 2361: 
 2362: 
 2363: @node Alignment Tutorial, Files Tutorial, Characters and Strings Tutorial, Tutorial
 2364: @section Alignment
 2365: @cindex alignment tutorial
 2366: @cindex memory alignment tutorial
 2367: 
 2368: On many processors cells have to be aligned in memory, if you want to
 2369: access them with @code{@@} and @code{!} (and even if the processor does
 2370: not require alignment, access to aligned cells is faster).
 2371: 
 2372: @code{Create} aligns @code{here} (i.e., the place where the next
 2373: allocation will occur, and that the @code{create}d word points to).
 2374: Likewise, the memory produced by @code{allocate} starts at an aligned
 2375: address.  Adding a number of @code{cells} to an aligned address produces
 2376: another aligned address.
 2377: 
 2378: However, address arithmetic involving @code{char+} and @code{chars} can
 2379: create an address that is not cell-aligned.  @code{Aligned ( addr --
 2380: a-addr )} produces the next aligned address:
 2381: 
 2382: @example
 2383: v3 char+ aligned .s @@ .
 2384: v3 char+ .s @@ .
 2385: @end example
 2386: 
 2387: Similarly, @code{align} advances @code{here} to the next aligned
 2388: address:
 2389: 
 2390: @example
 2391: create v5 97 c,
 2392: here .
 2393: align here .
 2394: 1000 ,
 2395: @end example
 2396: 
 2397: Note that you should use aligned addresses even if your processor does
 2398: not require them, if you want your program to be portable.
 2399: 
 2400: Reference: @ref{Address arithmetic}.
 2401: 
 2402: 
 2403: @node Files Tutorial, Interpretation and Compilation Semantics and Immediacy Tutorial, Alignment Tutorial, Tutorial
 2404: @section Files
 2405: @cindex files tutorial
 2406: 
 2407: This section gives a short introduction into how to use files inside
 2408: Forth. It's broken up into five easy steps:
 2409: 
 2410: @enumerate 1
 2411: @item Opened an ASCII text file for input
 2412: @item Opened a file for output
 2413: @item Read input file until string matched (or some other condition matched)
 2414: @item Wrote some lines from input ( modified or not) to output
 2415: @item Closed the files.
 2416: @end enumerate
 2417: 
 2418: @subsection Open file for input
 2419: 
 2420: @example
 2421: s" foo.in"  r/o open-file throw Value fd-in
 2422: @end example
 2423: 
 2424: @subsection Create file for output
 2425: 
 2426: @example
 2427: s" foo.out" w/o create-file throw Value fd-out
 2428: @end example
 2429: 
 2430: The available file modes are r/o for read-only access, r/w for
 2431: read-write access, and w/o for write-only access. You could open both
 2432: files with r/w, too, if you like. All file words return error codes; for
 2433: most applications, it's best to pass there error codes with @code{throw}
 2434: to the outer error handler.
 2435: 
 2436: If you want words for opening and assigning, define them as follows:
 2437: 
 2438: @example
 2439: 0 Value fd-in
 2440: 0 Value fd-out
 2441: : open-input ( addr u -- )  r/o open-file throw to fd-in ;
 2442: : open-output ( addr u -- )  w/o create-file throw to fd-out ;
 2443: @end example
 2444: 
 2445: Usage example:
 2446: 
 2447: @example
 2448: s" foo.in" open-input
 2449: s" foo.out" open-output
 2450: @end example
 2451: 
 2452: @subsection Scan file for a particular line
 2453: 
 2454: @example
 2455: 256 Constant max-line
 2456: Create line-buffer  max-line 2 + allot
 2457: 
 2458: : scan-file ( addr u -- )
 2459:   begin
 2460:       line-buffer max-line fd-in read-line throw
 2461:   while
 2462:          >r 2dup line-buffer r> compare 0=
 2463:      until
 2464:   else
 2465:      drop
 2466:   then
 2467:   2drop ;
 2468: @end example
 2469: 
 2470: @code{read-line ( addr u1 fd -- u2 flag ior )} reads up to u1 bytes into
 2471: the buffer at addr, and returns the number of bytes read, a flag that is
 2472: false when the end of file is reached, and an error code.
 2473: 
 2474: @code{compare ( addr1 u1 addr2 u2 -- n )} compares two strings and
 2475: returns zero if both strings are equal. It returns a positive number if
 2476: the first string is lexically greater, a negative if the second string
 2477: is lexically greater.
 2478: 
 2479: We haven't seen this loop here; it has two exits. Since the @code{while}
 2480: exits with the number of bytes read on the stack, we have to clean up
 2481: that separately; that's after the @code{else}.
 2482: 
 2483: Usage example:
 2484: 
 2485: @example
 2486: s" The text I search is here" scan-file
 2487: @end example
 2488: 
 2489: @subsection Copy input to output
 2490: 
 2491: @example
 2492: : copy-file ( -- )
 2493:   begin
 2494:       line-buffer max-line fd-in read-line throw
 2495:   while
 2496:       line-buffer swap fd-out write-file throw
 2497:   repeat ;
 2498: @end example
 2499: 
 2500: @subsection Close files
 2501: 
 2502: @example
 2503: fd-in close-file throw
 2504: fd-out close-file throw
 2505: @end example
 2506: 
 2507: Likewise, you can put that into definitions, too:
 2508: 
 2509: @example
 2510: : close-input ( -- )  fd-in close-file throw ;
 2511: : close-output ( -- )  fd-out close-file throw ;
 2512: @end example
 2513: 
 2514: @assignment
 2515: How could you modify @code{copy-file} so that it copies until a second line is
 2516: matched? Can you write a program that extracts a section of a text file,
 2517: given the line that starts and the line that terminates that section?
 2518: @endassignment
 2519: 
 2520: @node Interpretation and Compilation Semantics and Immediacy Tutorial, Execution Tokens Tutorial, Files Tutorial, Tutorial
 2521: @section Interpretation and Compilation Semantics and Immediacy
 2522: @cindex semantics tutorial
 2523: @cindex interpretation semantics tutorial
 2524: @cindex compilation semantics tutorial
 2525: @cindex immediate, tutorial
 2526: 
 2527: When a word is compiled, it behaves differently from being interpreted.
 2528: E.g., consider @code{+}:
 2529: 
 2530: @example
 2531: 1 2 + .
 2532: : foo + ;
 2533: @end example
 2534: 
 2535: These two behaviours are known as compilation and interpretation
 2536: semantics.  For normal words (e.g., @code{+}), the compilation semantics
 2537: is to append the interpretation semantics to the currently defined word
 2538: (@code{foo} in the example above).  I.e., when @code{foo} is executed
 2539: later, the interpretation semantics of @code{+} (i.e., adding two
 2540: numbers) will be performed.
 2541: 
 2542: However, there are words with non-default compilation semantics, e.g.,
 2543: the control-flow words like @code{if}.  You can use @code{immediate} to
 2544: change the compilation semantics of the last defined word to be equal to
 2545: the interpretation semantics:
 2546: 
 2547: @example
 2548: : [FOO] ( -- )
 2549:  5 . ; immediate
 2550: 
 2551: [FOO]
 2552: : bar ( -- )
 2553:   [FOO] ;
 2554: bar
 2555: see bar
 2556: @end example
 2557: 
 2558: Two conventions to mark words with non-default compilation semnatics are
 2559: names with brackets (more frequently used) and to write them all in
 2560: upper case (less frequently used).
 2561: 
 2562: In Gforth (and many other systems) you can also remove the
 2563: interpretation semantics with @code{compile-only} (the compilation
 2564: semantics is derived from the original interpretation semantics):
 2565: 
 2566: @example
 2567: : flip ( -- )
 2568:  6 . ; compile-only \ but not immediate
 2569: flip
 2570: 
 2571: : flop ( -- )
 2572:  flip ;
 2573: flop
 2574: @end example
 2575: 
 2576: In this example the interpretation semantics of @code{flop} is equal to
 2577: the original interpretation semantics of @code{flip}.
 2578: 
 2579: The text interpreter has two states: in interpret state, it performs the
 2580: interpretation semantics of words it encounters; in compile state, it
 2581: performs the compilation semantics of these words.
 2582: 
 2583: Among other things, @code{:} switches into compile state, and @code{;}
 2584: switches back to interpret state.  They contain the factors @code{]}
 2585: (switch to compile state) and @code{[} (switch to interpret state), that
 2586: do nothing but switch the state.
 2587: 
 2588: @example
 2589: : xxx ( -- )
 2590:   [ 5 . ]
 2591: ;
 2592: 
 2593: xxx
 2594: see xxx
 2595: @end example
 2596: 
 2597: These brackets are also the source of the naming convention mentioned
 2598: above.
 2599: 
 2600: Reference: @ref{Interpretation and Compilation Semantics}.
 2601: 
 2602: 
 2603: @node Execution Tokens Tutorial, Exceptions Tutorial, Interpretation and Compilation Semantics and Immediacy Tutorial, Tutorial
 2604: @section Execution Tokens
 2605: @cindex execution tokens tutorial
 2606: @cindex XT tutorial
 2607: 
 2608: @code{' word} gives you the execution token (XT) of a word.  The XT is a
 2609: cell representing the interpretation semantics of a word.  You can
 2610: execute this semantics with @code{execute}:
 2611: 
 2612: @example
 2613: ' + .s
 2614: 1 2 rot execute .
 2615: @end example
 2616: 
 2617: The XT is similar to a function pointer in C.  However, parameter
 2618: passing through the stack makes it a little more flexible:
 2619: 
 2620: @example
 2621: : map-array ( ... addr u xt -- ... )
 2622: \ executes xt ( ... x -- ... ) for every element of the array starting
 2623: \ at addr and containing u elements
 2624:   @{ xt @}
 2625:   cells over + swap ?do
 2626:     i @@ xt execute
 2627:   1 cells +loop ;
 2628: 
 2629: create a 3 , 4 , 2 , -1 , 4 ,
 2630: a 5 ' . map-array .s
 2631: 0 a 5 ' + map-array .
 2632: s" max-n" environment? drop .s
 2633: a 5 ' min map-array .
 2634: @end example
 2635: 
 2636: You can use map-array with the XTs of words that consume one element
 2637: more than they produce.  In theory you can also use it with other XTs,
 2638: but the stack effect then depends on the size of the array, which is
 2639: hard to understand.
 2640: 
 2641: Since XTs are cell-sized, you can store them in memory and manipulate
 2642: them on the stack like other cells.  You can also compile the XT into a
 2643: word with @code{compile,}:
 2644: 
 2645: @example
 2646: : foo1 ( n1 n2 -- n )
 2647:    [ ' + compile, ] ;
 2648: see foo
 2649: @end example
 2650: 
 2651: This is non-standard, because @code{compile,} has no compilation
 2652: semantics in the standard, but it works in good Forth systems.  For the
 2653: broken ones, use
 2654: 
 2655: @example
 2656: : [compile,] compile, ; immediate
 2657: 
 2658: : foo1 ( n1 n2 -- n )
 2659:    [ ' + ] [compile,] ;
 2660: see foo
 2661: @end example
 2662: 
 2663: @code{'} is a word with default compilation semantics; it parses the
 2664: next word when its interpretation semantics are executed, not during
 2665: compilation:
 2666: 
 2667: @example
 2668: : foo ( -- xt )
 2669:   ' ;
 2670: see foo
 2671: : bar ( ... "word" -- ... )
 2672:   ' execute ;
 2673: see bar
 2674: 1 2 bar + .
 2675: @end example
 2676: 
 2677: You often want to parse a word during compilation and compile its XT so
 2678: it will be pushed on the stack at run-time.  @code{[']} does this:
 2679: 
 2680: @example
 2681: : xt-+ ( -- xt )
 2682:   ['] + ;
 2683: see xt-+
 2684: 1 2 xt-+ execute .
 2685: @end example
 2686: 
 2687: Many programmers tend to see @code{'} and the word it parses as one
 2688: unit, and expect it to behave like @code{[']} when compiled, and are
 2689: confused by the actual behaviour.  If you are, just remember that the
 2690: Forth system just takes @code{'} as one unit and has no idea that it is
 2691: a parsing word (attempts to convenience programmers in this issue have
 2692: usually resulted in even worse pitfalls, see
 2693: @uref{http://www.complang.tuwien.ac.at/papers/ertl98.ps.gz,
 2694: @code{State}-smartness---Why it is evil and How to Exorcise it}).
 2695: 
 2696: Note that the state of the interpreter does not come into play when
 2697: creating and executing XTs.  I.e., even when you execute @code{'} in
 2698: compile state, it still gives you the interpretation semantics.  And
 2699: whatever that state is, @code{execute} performs the semantics
 2700: represented by the XT (i.e., for XTs produced with @code{'} the
 2701: interpretation semantics).
 2702: 
 2703: Reference: @ref{Tokens for Words}.
 2704: 
 2705: 
 2706: @node Exceptions Tutorial, Defining Words Tutorial, Execution Tokens Tutorial, Tutorial
 2707: @section Exceptions
 2708: @cindex exceptions tutorial
 2709: 
 2710: @code{throw ( n -- )} causes an exception unless n is zero.
 2711: 
 2712: @example
 2713: 100 throw .s
 2714: 0 throw .s
 2715: @end example
 2716: 
 2717: @code{catch ( ... xt -- ... n )} behaves similar to @code{execute}, but
 2718: it catches exceptions and pushes the number of the exception on the
 2719: stack (or 0, if the xt executed without exception).  If there was an
 2720: exception, the stacks have the same depth as when entering @code{catch}:
 2721: 
 2722: @example
 2723: .s
 2724: 3 0 ' / catch .s
 2725: 3 2 ' / catch .s
 2726: @end example
 2727: 
 2728: @assignment
 2729: Try the same with @code{execute} instead of @code{catch}.
 2730: @endassignment
 2731: 
 2732: @code{Throw} always jumps to the dynamically next enclosing
 2733: @code{catch}, even if it has to leave several call levels to achieve
 2734: this:
 2735: 
 2736: @example
 2737: : foo 100 throw ;
 2738: : foo1 foo ." after foo" ;
 2739: : bar ['] foo1 catch ;
 2740: bar .
 2741: @end example
 2742: 
 2743: It is often important to restore a value upon leaving a definition, even
 2744: if the definition is left through an exception.  You can ensure this
 2745: like this:
 2746: 
 2747: @example
 2748: : ...
 2749:    save-x
 2750:    ['] word-changing-x catch ( ... n )
 2751:    restore-x
 2752:    ( ... n ) throw ;
 2753: @end example
 2754: 
 2755: Gforth provides an alternative syntax in addition to @code{catch}:
 2756: @code{try ... recover ... endtry}.  If the code between @code{try} and
 2757: @code{recover} has an exception, the stack depths are restored, the
 2758: exception number is pushed on the stack, and the code between
 2759: @code{recover} and @code{endtry} is performed.  E.g., the definition for
 2760: @code{catch} is
 2761: 
 2762: @example
 2763: : catch ( x1 .. xn xt -- y1 .. ym 0 / z1 .. zn error ) \ exception
 2764:   try
 2765:     execute 0
 2766:   recover
 2767:     nip
 2768:   endtry ;
 2769: @end example
 2770: 
 2771: The equivalent to the restoration code above is
 2772: 
 2773: @example
 2774: : ...
 2775:   save-x
 2776:   try
 2777:     word-changing-x 0
 2778:   recover endtry
 2779:   restore-x
 2780:   throw ;
 2781: @end example
 2782: 
 2783: This works if @code{word-changing-x} does not change the stack depth,
 2784: otherwise you should add some code between @code{recover} and
 2785: @code{endtry} to balance the stack.
 2786: 
 2787: Reference: @ref{Exception Handling}.
 2788: 
 2789: 
 2790: @node Defining Words Tutorial, Arrays and Records Tutorial, Exceptions Tutorial, Tutorial
 2791: @section Defining Words
 2792: @cindex defining words tutorial
 2793: @cindex does> tutorial
 2794: @cindex create...does> tutorial
 2795: 
 2796: @c before semantics?
 2797: 
 2798: @code{:}, @code{create}, and @code{variable} are definition words: They
 2799: define other words.  @code{Constant} is another definition word:
 2800: 
 2801: @example
 2802: 5 constant foo
 2803: foo .
 2804: @end example
 2805: 
 2806: You can also use the prefixes @code{2} (double-cell) and @code{f}
 2807: (floating point) with @code{variable} and @code{constant}.
 2808: 
 2809: You can also define your own defining words.  E.g.:
 2810: 
 2811: @example
 2812: : variable ( "name" -- )
 2813:   create 0 , ;
 2814: @end example
 2815: 
 2816: You can also define defining words that create words that do something
 2817: other than just producing their address:
 2818: 
 2819: @example
 2820: : constant ( n "name" -- )
 2821:   create ,
 2822: does> ( -- n )
 2823:   ( addr ) @@ ;
 2824: 
 2825: 5 constant foo
 2826: foo .
 2827: @end example
 2828: 
 2829: The definition of @code{constant} above ends at the @code{does>}; i.e.,
 2830: @code{does>} replaces @code{;}, but it also does something else: It
 2831: changes the last defined word such that it pushes the address of the
 2832: body of the word and then performs the code after the @code{does>}
 2833: whenever it is called.
 2834: 
 2835: In the example above, @code{constant} uses @code{,} to store 5 into the
 2836: body of @code{foo}.  When @code{foo} executes, it pushes the address of
 2837: the body onto the stack, then (in the code after the @code{does>})
 2838: fetches the 5 from there.
 2839: 
 2840: The stack comment near the @code{does>} reflects the stack effect of the
 2841: defined word, not the stack effect of the code after the @code{does>}
 2842: (the difference is that the code expects the address of the body that
 2843: the stack comment does not show).
 2844: 
 2845: You can use these definition words to do factoring in cases that involve
 2846: (other) definition words.  E.g., a field offset is always added to an
 2847: address.  Instead of defining
 2848: 
 2849: @example
 2850: 2 cells constant offset-field1
 2851: @end example
 2852: 
 2853: and using this like
 2854: 
 2855: @example
 2856: ( addr ) offset-field1 +
 2857: @end example
 2858: 
 2859: you can define a definition word
 2860: 
 2861: @example
 2862: : simple-field ( n "name" -- )
 2863:   create ,
 2864: does> ( n1 -- n1+n )
 2865:   ( addr ) @@ + ;
 2866: @end example
 2867: 
 2868: Definition and use of field offsets now look like this:
 2869: 
 2870: @example
 2871: 2 cells simple-field field1
 2872: create mystruct 4 cells allot
 2873: mystruct .s field1 .s drop
 2874: @end example
 2875: 
 2876: If you want to do something with the word without performing the code
 2877: after the @code{does>}, you can access the body of a @code{create}d word
 2878: with @code{>body ( xt -- addr )}:
 2879: 
 2880: @example
 2881: : value ( n "name" -- )
 2882:   create ,
 2883: does> ( -- n1 )
 2884:   @@ ;
 2885: : to ( n "name" -- )
 2886:   ' >body ! ;
 2887: 
 2888: 5 value foo
 2889: foo .
 2890: 7 to foo
 2891: foo .
 2892: @end example
 2893: 
 2894: @assignment
 2895: Define @code{defer ( "name" -- )}, which creates a word that stores an
 2896: XT (at the start the XT of @code{abort}), and upon execution
 2897: @code{execute}s the XT.  Define @code{is ( xt "name" -- )} that stores
 2898: @code{xt} into @code{name}, a word defined with @code{defer}.  Indirect
 2899: recursion is one application of @code{defer}.
 2900: @endassignment
 2901: 
 2902: Reference: @ref{User-defined Defining Words}.
 2903: 
 2904: 
 2905: @node Arrays and Records Tutorial, POSTPONE Tutorial, Defining Words Tutorial, Tutorial
 2906: @section Arrays and Records
 2907: @cindex arrays tutorial
 2908: @cindex records tutorial
 2909: @cindex structs tutorial
 2910: 
 2911: Forth has no standard words for defining data structures such as arrays
 2912: and records (structs in C terminology), but you can build them yourself
 2913: based on address arithmetic.  You can also define words for defining
 2914: arrays and records (@pxref{Defining Words Tutorial,, Defining Words}).
 2915: 
 2916: One of the first projects a Forth newcomer sets out upon when learning
 2917: about defining words is an array defining word (possibly for
 2918: n-dimensional arrays).  Go ahead and do it, I did it, too; you will
 2919: learn something from it.  However, don't be disappointed when you later
 2920: learn that you have little use for these words (inappropriate use would
 2921: be even worse).  I have not yet found a set of useful array words yet;
 2922: the needs are just too diverse, and named, global arrays (the result of
 2923: naive use of defining words) are often not flexible enough (e.g.,
 2924: consider how to pass them as parameters).  Another such project is a set
 2925: of words to help dealing with strings.
 2926: 
 2927: On the other hand, there is a useful set of record words, and it has
 2928: been defined in @file{compat/struct.fs}; these words are predefined in
 2929: Gforth.  They are explained in depth elsewhere in this manual (see
 2930: @pxref{Structures}).  The @code{simple-field} example above is
 2931: simplified variant of fields in this package.
 2932: 
 2933: 
 2934: @node POSTPONE Tutorial, Literal Tutorial, Arrays and Records Tutorial, Tutorial
 2935: @section @code{POSTPONE}
 2936: @cindex postpone tutorial
 2937: 
 2938: You can compile the compilation semantics (instead of compiling the
 2939: interpretation semantics) of a word with @code{POSTPONE}:
 2940: 
 2941: @example
 2942: : MY-+ ( Compilation: -- ; Run-time of compiled code: n1 n2 -- n )
 2943:  POSTPONE + ; immediate
 2944: : foo ( n1 n2 -- n )
 2945:  MY-+ ;
 2946: 1 2 foo .
 2947: see foo
 2948: @end example
 2949: 
 2950: During the definition of @code{foo} the text interpreter performs the
 2951: compilation semantics of @code{MY-+}, which performs the compilation
 2952: semantics of @code{+}, i.e., it compiles @code{+} into @code{foo}.
 2953: 
 2954: This example also displays separate stack comments for the compilation
 2955: semantics and for the stack effect of the compiled code.  For words with
 2956: default compilation semantics these stack effects are usually not
 2957: displayed; the stack effect of the compilation semantics is always
 2958: @code{( -- )} for these words, the stack effect for the compiled code is
 2959: the stack effect of the interpretation semantics.
 2960: 
 2961: Note that the state of the interpreter does not come into play when
 2962: performing the compilation semantics in this way.  You can also perform
 2963: it interpretively, e.g.:
 2964: 
 2965: @example
 2966: : foo2 ( n1 n2 -- n )
 2967:  [ MY-+ ] ;
 2968: 1 2 foo .
 2969: see foo
 2970: @end example
 2971: 
 2972: However, there are some broken Forth systems where this does not always
 2973: work, and therefore this practice was been declared non-standard in
 2974: 1999.
 2975: @c !! repair.fs
 2976: 
 2977: Here is another example for using @code{POSTPONE}:
 2978: 
 2979: @example
 2980: : MY-- ( Compilation: -- ; Run-time of compiled code: n1 n2 -- n )
 2981:  POSTPONE negate POSTPONE + ; immediate compile-only
 2982: : bar ( n1 n2 -- n )
 2983:   MY-- ;
 2984: 2 1 bar .
 2985: see bar
 2986: @end example
 2987: 
 2988: You can define @code{ENDIF} in this way:
 2989: 
 2990: @example
 2991: : ENDIF ( Compilation: orig -- )
 2992:   POSTPONE then ; immediate
 2993: @end example
 2994: 
 2995: @assignment
 2996: Write @code{MY-2DUP} that has compilation semantics equivalent to
 2997: @code{2dup}, but compiles @code{over over}.
 2998: @endassignment
 2999: 
 3000: @c !! @xref{Macros} for reference
 3001: 
 3002: 
 3003: @node Literal Tutorial, Advanced macros Tutorial, POSTPONE Tutorial, Tutorial
 3004: @section @code{Literal}
 3005: @cindex literal tutorial
 3006: 
 3007: You cannot @code{POSTPONE} numbers:
 3008: 
 3009: @example
 3010: : [FOO] POSTPONE 500 ; immediate
 3011: @end example
 3012: 
 3013: Instead, you can use @code{LITERAL (compilation: n --; run-time: -- n )}:
 3014: 
 3015: @example
 3016: : [FOO] ( compilation: --; run-time: -- n )
 3017:   500 POSTPONE literal ; immediate
 3018: 
 3019: : flip [FOO] ;
 3020: flip .
 3021: see flip
 3022: @end example
 3023: 
 3024: @code{LITERAL} consumes a number at compile-time (when it's compilation
 3025: semantics are executed) and pushes it at run-time (when the code it
 3026: compiled is executed).  A frequent use of @code{LITERAL} is to compile a
 3027: number computed at compile time into the current word:
 3028: 
 3029: @example
 3030: : bar ( -- n )
 3031:   [ 2 2 + ] literal ;
 3032: see bar
 3033: @end example
 3034: 
 3035: @assignment
 3036: Write @code{]L} which allows writing the example above as @code{: bar (
 3037: -- n ) [ 2 2 + ]L ;}
 3038: @endassignment
 3039: 
 3040: @c !! @xref{Macros} for reference
 3041: 
 3042: 
 3043: @node Advanced macros Tutorial, Compilation Tokens Tutorial, Literal Tutorial, Tutorial
 3044: @section Advanced macros
 3045: @cindex macros, advanced tutorial
 3046: @cindex run-time code generation, tutorial
 3047: 
 3048: Reconsider @code{map-array} from @ref{Execution Tokens Tutorial,,
 3049: Execution Tokens}.  It frequently performs @code{execute}, a relatively
 3050: expensive operation in some Forth implementations.  You can use
 3051: @code{compile,} and @code{POSTPONE} to eliminate these @code{execute}s
 3052: and produce a word that contains the word to be performed directly:
 3053: 
 3054: @c use ]] ... [[
 3055: @example
 3056: : compile-map-array ( compilation: xt -- ; run-time: ... addr u -- ... )
 3057: \ at run-time, execute xt ( ... x -- ... ) for each element of the
 3058: \ array beginning at addr and containing u elements
 3059:   @{ xt @}
 3060:   POSTPONE cells POSTPONE over POSTPONE + POSTPONE swap POSTPONE ?do
 3061:     POSTPONE i POSTPONE @@ xt compile,
 3062:   1 cells POSTPONE literal POSTPONE +loop ;
 3063: 
 3064: : sum-array ( addr u -- n )
 3065:  0 rot rot [ ' + compile-map-array ] ;
 3066: see sum-array
 3067: a 5 sum-array .
 3068: @end example
 3069: 
 3070: You can use the full power of Forth for generating the code; here's an
 3071: example where the code is generated in a loop:
 3072: 
 3073: @example
 3074: : compile-vmul-step ( compilation: n --; run-time: n1 addr1 -- n2 addr2 )
 3075: \ n2=n1+(addr1)*n, addr2=addr1+cell
 3076:   POSTPONE tuck POSTPONE @@
 3077:   POSTPONE literal POSTPONE * POSTPONE +
 3078:   POSTPONE swap POSTPONE cell+ ;
 3079: 
 3080: : compile-vmul ( compilation: addr1 u -- ; run-time: addr2 -- n )
 3081: \ n=v1*v2 (inner product), where the v_i are represented as addr_i u
 3082:   0 postpone literal postpone swap
 3083:   [ ' compile-vmul-step compile-map-array ]
 3084:   postpone drop ;
 3085: see compile-vmul
 3086: 
 3087: : a-vmul ( addr -- n )
 3088: \ n=a*v, where v is a vector that's as long as a and starts at addr
 3089:  [ a 5 compile-vmul ] ;
 3090: see a-vmul
 3091: a a-vmul .
 3092: @end example
 3093: 
 3094: This example uses @code{compile-map-array} to show off, but you could
 3095: also use @code{map-array} instead (try it now!).
 3096: 
 3097: You can use this technique for efficient multiplication of large
 3098: matrices.  In matrix multiplication, you multiply every line of one
 3099: matrix with every column of the other matrix.  You can generate the code
 3100: for one line once, and use it for every column.  The only downside of
 3101: this technique is that it is cumbersome to recover the memory consumed
 3102: by the generated code when you are done (and in more complicated cases
 3103: it is not possible portably).
 3104: 
 3105: @c !! @xref{Macros} for reference
 3106: 
 3107: 
 3108: @node Compilation Tokens Tutorial, Wordlists and Search Order Tutorial, Advanced macros Tutorial, Tutorial
 3109: @section Compilation Tokens
 3110: @cindex compilation tokens, tutorial
 3111: @cindex CT, tutorial
 3112: 
 3113: This section is Gforth-specific.  You can skip it.
 3114: 
 3115: @code{' word compile,} compiles the interpretation semantics.  For words
 3116: with default compilation semantics this is the same as performing the
 3117: compilation semantics.  To represent the compilation semantics of other
 3118: words (e.g., words like @code{if} that have no interpretation
 3119: semantics), Gforth has the concept of a compilation token (CT,
 3120: consisting of two cells), and words @code{comp'} and @code{[comp']}.
 3121: You can perform the compilation semantics represented by a CT with
 3122: @code{execute}:
 3123: 
 3124: @example
 3125: : foo2 ( n1 n2 -- n )
 3126:    [ comp' + execute ] ;
 3127: see foo
 3128: @end example
 3129: 
 3130: You can compile the compilation semantics represented by a CT with
 3131: @code{postpone,}:
 3132: 
 3133: @example
 3134: : foo3 ( -- )
 3135:   [ comp' + postpone, ] ;
 3136: see foo3
 3137: @end example
 3138: 
 3139: @code{[ comp' word postpone, ]} is equivalent to @code{POSTPONE word}.
 3140: @code{comp'} is particularly useful for words that have no
 3141: interpretation semantics:
 3142: 
 3143: @example
 3144: ' if
 3145: comp' if .s 2drop
 3146: @end example
 3147: 
 3148: Reference: @ref{Tokens for Words}.
 3149: 
 3150: 
 3151: @node Wordlists and Search Order Tutorial,  , Compilation Tokens Tutorial, Tutorial
 3152: @section Wordlists and Search Order
 3153: @cindex wordlists tutorial
 3154: @cindex search order, tutorial
 3155: 
 3156: The dictionary is not just a memory area that allows you to allocate
 3157: memory with @code{allot}, it also contains the Forth words, arranged in
 3158: several wordlists.  When searching for a word in a wordlist,
 3159: conceptually you start searching at the youngest and proceed towards
 3160: older words (in reality most systems nowadays use hash-tables); i.e., if
 3161: you define a word with the same name as an older word, the new word
 3162: shadows the older word.
 3163: 
 3164: Which wordlists are searched in which order is determined by the search
 3165: order.  You can display the search order with @code{order}.  It displays
 3166: first the search order, starting with the wordlist searched first, then
 3167: it displays the wordlist that will contain newly defined words.
 3168: 
 3169: You can create a new, empty wordlist with @code{wordlist ( -- wid )}:
 3170: 
 3171: @example
 3172: wordlist constant mywords
 3173: @end example
 3174: 
 3175: @code{Set-current ( wid -- )} sets the wordlist that will contain newly
 3176: defined words (the @emph{current} wordlist):
 3177: 
 3178: @example
 3179: mywords set-current
 3180: order
 3181: @end example
 3182: 
 3183: Gforth does not display a name for the wordlist in @code{mywords}
 3184: because this wordlist was created anonymously with @code{wordlist}.
 3185: 
 3186: You can get the current wordlist with @code{get-current ( -- wid)}.  If
 3187: you want to put something into a specific wordlist without overall
 3188: effect on the current wordlist, this typically looks like this:
 3189: 
 3190: @example
 3191: get-current mywords set-current ( wid )
 3192: create someword
 3193: ( wid ) set-current
 3194: @end example
 3195: 
 3196: You can write the search order with @code{set-order ( wid1 .. widn n --
 3197: )} and read it with @code{get-order ( -- wid1 .. widn n )}.  The first
 3198: searched wordlist is topmost.
 3199: 
 3200: @example
 3201: get-order mywords swap 1+ set-order
 3202: order
 3203: @end example
 3204: 
 3205: Yes, the order of wordlists in the output of @code{order} is reversed
 3206: from stack comments and the output of @code{.s} and thus unintuitive.
 3207: 
 3208: @assignment
 3209: Define @code{>order ( wid -- )} with adds @code{wid} as first searched
 3210: wordlist to the search order.  Define @code{previous ( -- )}, which
 3211: removes the first searched wordlist from the search order.  Experiment
 3212: with boundary conditions (you will see some crashes or situations that
 3213: are hard or impossible to leave).
 3214: @endassignment
 3215: 
 3216: The search order is a powerful foundation for providing features similar
 3217: to Modula-2 modules and C++ namespaces.  However, trying to modularize
 3218: programs in this way has disadvantages for debugging and reuse/factoring
 3219: that overcome the advantages in my experience (I don't do huge projects,
 3220: though).  These disadvantages are not so clear in other
 3221: languages/programming environments, because these languages are not so
 3222: strong in debugging and reuse.
 3223: 
 3224: @c !! example
 3225: 
 3226: Reference: @ref{Word Lists}.
 3227: 
 3228: @c ******************************************************************
 3229: @node Introduction, Words, Tutorial, Top
 3230: @comment node-name,     next,           previous, up
 3231: @chapter An Introduction to ANS Forth
 3232: @cindex Forth - an introduction
 3233: 
 3234: The difference of this chapter from the Tutorial (@pxref{Tutorial}) is
 3235: that it is slower-paced in its examples, but uses them to dive deep into
 3236: explaining Forth internals (not covered by the Tutorial).  Apart from
 3237: that, this chapter covers far less material.  It is suitable for reading
 3238: without using a computer.
 3239: 
 3240: The primary purpose of this manual is to document Gforth. However, since
 3241: Forth is not a widely-known language and there is a lack of up-to-date
 3242: teaching material, it seems worthwhile to provide some introductory
 3243: material.  For other sources of Forth-related
 3244: information, see @ref{Forth-related information}.
 3245: 
 3246: The examples in this section should work on any ANS Forth; the
 3247: output shown was produced using Gforth. Each example attempts to
 3248: reproduce the exact output that Gforth produces. If you try out the
 3249: examples (and you should), what you should type is shown @kbd{like this}
 3250: and Gforth's response is shown @code{like this}. The single exception is
 3251: that, where the example shows @key{RET} it means that you should
 3252: press the ``carriage return'' key. Unfortunately, some output formats for
 3253: this manual cannot show the difference between @kbd{this} and
 3254: @code{this} which will make trying out the examples harder (but not
 3255: impossible).
 3256: 
 3257: Forth is an unusual language. It provides an interactive development
 3258: environment which includes both an interpreter and compiler. Forth
 3259: programming style encourages you to break a problem down into many
 3260: @cindex factoring
 3261: small fragments (@dfn{factoring}), and then to develop and test each
 3262: fragment interactively. Forth advocates assert that breaking the
 3263: edit-compile-test cycle used by conventional programming languages can
 3264: lead to great productivity improvements.
 3265: 
 3266: @menu
 3267: * Introducing the Text Interpreter::  
 3268: * Stacks and Postfix notation::  
 3269: * Your first definition::       
 3270: * How does that work?::         
 3271: * Forth is written in Forth::   
 3272: * Review - elements of a Forth system::  
 3273: * Where to go next::            
 3274: * Exercises::                   
 3275: @end menu
 3276: 
 3277: @comment ----------------------------------------------
 3278: @node Introducing the Text Interpreter, Stacks and Postfix notation, Introduction, Introduction
 3279: @section Introducing the Text Interpreter
 3280: @cindex text interpreter
 3281: @cindex outer interpreter
 3282: 
 3283: @c IMO this is too detailed and the pace is too slow for
 3284: @c an introduction.  If you know German, take a look at
 3285: @c http://www.complang.tuwien.ac.at/anton/lvas/skriptum-stack.html 
 3286: @c to see how I do it - anton 
 3287: 
 3288: @c nac-> Where I have accepted your comments 100% and modified the text
 3289: @c accordingly, I have deleted your comments. Elsewhere I have added a
 3290: @c response like this to attempt to rationalise what I have done. Of
 3291: @c course, this is a very clumsy mechanism for something that would be
 3292: @c done far more efficiently over a beer. Please delete any dialogue
 3293: @c you consider closed.
 3294: 
 3295: When you invoke the Forth image, you will see a startup banner printed
 3296: and nothing else (if you have Gforth installed on your system, try
 3297: invoking it now, by typing @kbd{gforth@key{RET}}). Forth is now running
 3298: its command line interpreter, which is called the @dfn{Text Interpreter}
 3299: (also known as the @dfn{Outer Interpreter}).  (You will learn a lot
 3300: about the text interpreter as you read through this chapter, for more
 3301: detail @pxref{The Text Interpreter}).
 3302: 
 3303: Although it's not obvious, Forth is actually waiting for your
 3304: input. Type a number and press the @key{RET} key:
 3305: 
 3306: @example
 3307: @kbd{45@key{RET}}  ok
 3308: @end example
 3309: 
 3310: Rather than give you a prompt to invite you to input something, the text
 3311: interpreter prints a status message @i{after} it has processed a line
 3312: of input. The status message in this case (``@code{ ok}'' followed by
 3313: carriage-return) indicates that the text interpreter was able to process
 3314: all of your input successfully. Now type something illegal:
 3315: 
 3316: @example
 3317: @kbd{qwer341@key{RET}}
 3318: :1: Undefined word
 3319: qwer341
 3320: ^^^^^^^
 3321: $400D2BA8 Bounce
 3322: $400DBDA8 no.extensions
 3323: @end example
 3324: 
 3325: The exact text, other than the ``Undefined word'' may differ slightly on
 3326: your system, but the effect is the same; when the text interpreter
 3327: detects an error, it discards any remaining text on a line, resets
 3328: certain internal state and prints an error message. For a detailed description of error messages see @ref{Error
 3329: messages}.
 3330: 
 3331: The text interpreter waits for you to press carriage-return, and then
 3332: processes your input line. Starting at the beginning of the line, it
 3333: breaks the line into groups of characters separated by spaces. For each
 3334: group of characters in turn, it makes two attempts to do something:
 3335: 
 3336: @itemize @bullet
 3337: @item
 3338: @cindex name dictionary
 3339: It tries to treat it as a command. It does this by searching a @dfn{name
 3340: dictionary}. If the group of characters matches an entry in the name
 3341: dictionary, the name dictionary provides the text interpreter with
 3342: information that allows the text interpreter perform some actions. In
 3343: Forth jargon, we say that the group
 3344: @cindex word
 3345: @cindex definition
 3346: @cindex execution token
 3347: @cindex xt
 3348: of characters names a @dfn{word}, that the dictionary search returns an
 3349: @dfn{execution token (xt)} corresponding to the @dfn{definition} of the
 3350: word, and that the text interpreter executes the xt. Often, the terms
 3351: @dfn{word} and @dfn{definition} are used interchangeably.
 3352: @item
 3353: If the text interpreter fails to find a match in the name dictionary, it
 3354: tries to treat the group of characters as a number in the current number
 3355: base (when you start up Forth, the current number base is base 10). If
 3356: the group of characters legitimately represents a number, the text
 3357: interpreter pushes the number onto a stack (we'll learn more about that
 3358: in the next section).
 3359: @end itemize
 3360: 
 3361: If the text interpreter is unable to do either of these things with any
 3362: group of characters, it discards the group of characters and the rest of
 3363: the line, then prints an error message. If the text interpreter reaches
 3364: the end of the line without error, it prints the status message ``@code{ ok}''
 3365: followed by carriage-return.
 3366: 
 3367: This is the simplest command we can give to the text interpreter:
 3368: 
 3369: @example
 3370: @key{RET}  ok
 3371: @end example
 3372: 
 3373: The text interpreter did everything we asked it to do (nothing) without
 3374: an error, so it said that everything is ``@code{ ok}''. Try a slightly longer
 3375: command:
 3376: 
 3377: @example
 3378: @kbd{12 dup fred dup@key{RET}}
 3379: :1: Undefined word
 3380: 12 dup fred dup
 3381:        ^^^^
 3382: $400D2BA8 Bounce
 3383: $400DBDA8 no.extensions
 3384: @end example
 3385: 
 3386: When you press the carriage-return key, the text interpreter starts to
 3387: work its way along the line:
 3388: 
 3389: @itemize @bullet
 3390: @item
 3391: When it gets to the space after the @code{2}, it takes the group of
 3392: characters @code{12} and looks them up in the name
 3393: dictionary@footnote{We can't tell if it found them or not, but assume
 3394: for now that it did not}. There is no match for this group of characters
 3395: in the name dictionary, so it tries to treat them as a number. It is
 3396: able to do this successfully, so it puts the number, 12, ``on the stack''
 3397: (whatever that means).
 3398: @item
 3399: The text interpreter resumes scanning the line and gets the next group
 3400: of characters, @code{dup}. It looks it up in the name dictionary and
 3401: (you'll have to take my word for this) finds it, and executes the word
 3402: @code{dup} (whatever that means).
 3403: @item
 3404: Once again, the text interpreter resumes scanning the line and gets the
 3405: group of characters @code{fred}. It looks them up in the name
 3406: dictionary, but can't find them. It tries to treat them as a number, but
 3407: they don't represent any legal number.
 3408: @end itemize
 3409: 
 3410: At this point, the text interpreter gives up and prints an error
 3411: message. The error message shows exactly how far the text interpreter
 3412: got in processing the line. In particular, it shows that the text
 3413: interpreter made no attempt to do anything with the final character
 3414: group, @code{dup}, even though we have good reason to believe that the
 3415: text interpreter would have no problem looking that word up and
 3416: executing it a second time.
 3417: 
 3418: 
 3419: @comment ----------------------------------------------
 3420: @node Stacks and Postfix notation, Your first definition, Introducing the Text Interpreter, Introduction
 3421: @section Stacks, postfix notation and parameter passing
 3422: @cindex text interpreter
 3423: @cindex outer interpreter
 3424: 
 3425: In procedural programming languages (like C and Pascal), the
 3426: building-block of programs is the @dfn{function} or @dfn{procedure}. These
 3427: functions or procedures are called with @dfn{explicit parameters}. For
 3428: example, in C we might write:
 3429: 
 3430: @example
 3431: total = total + new_volume(length,height,depth);
 3432: @end example
 3433: 
 3434: @noindent
 3435: where new_volume is a function-call to another piece of code, and total,
 3436: length, height and depth are all variables. length, height and depth are
 3437: parameters to the function-call.
 3438: 
 3439: In Forth, the equivalent of the function or procedure is the
 3440: @dfn{definition} and parameters are implicitly passed between
 3441: definitions using a shared stack that is visible to the
 3442: programmer. Although Forth does support variables, the existence of the
 3443: stack means that they are used far less often than in most other
 3444: programming languages. When the text interpreter encounters a number, it
 3445: will place (@dfn{push}) it on the stack. There are several stacks (the
 3446: actual number is implementation-dependent ...) and the particular stack
 3447: used for any operation is implied unambiguously by the operation being
 3448: performed. The stack used for all integer operations is called the @dfn{data
 3449: stack} and, since this is the stack used most commonly, references to
 3450: ``the data stack'' are often abbreviated to ``the stack''.
 3451: 
 3452: The stacks have a last-in, first-out (LIFO) organisation. If you type:
 3453: 
 3454: @example
 3455: @kbd{1 2 3@key{RET}}  ok
 3456: @end example
 3457: 
 3458: Then this instructs the text interpreter to placed three numbers on the
 3459: (data) stack. An analogy for the behaviour of the stack is to take a
 3460: pack of playing cards and deal out the ace (1), 2 and 3 into a pile on
 3461: the table. The 3 was the last card onto the pile (``last-in'') and if
 3462: you take a card off the pile then, unless you're prepared to fiddle a
 3463: bit, the card that you take off will be the 3 (``first-out''). The
 3464: number that will be first-out of the stack is called the @dfn{top of
 3465: stack}, which
 3466: @cindex TOS definition
 3467: is often abbreviated to @dfn{TOS}.
 3468: 
 3469: To understand how parameters are passed in Forth, consider the
 3470: behaviour of the definition @code{+} (pronounced ``plus''). You will not
 3471: be surprised to learn that this definition performs addition. More
 3472: precisely, it adds two number together and produces a result. Where does
 3473: it get the two numbers from? It takes the top two numbers off the
 3474: stack. Where does it place the result? On the stack. You can act-out the
 3475: behaviour of @code{+} with your playing cards like this:
 3476: 
 3477: @itemize @bullet
 3478: @item
 3479: Pick up two cards from the stack on the table
 3480: @item
 3481: Stare at them intently and ask yourself ``what @i{is} the sum of these two
 3482: numbers''
 3483: @item
 3484: Decide that the answer is 5
 3485: @item
 3486: Shuffle the two cards back into the pack and find a 5
 3487: @item
 3488: Put a 5 on the remaining ace that's on the table.
 3489: @end itemize
 3490: 
 3491: If you don't have a pack of cards handy but you do have Forth running,
 3492: you can use the definition @code{.s} to show the current state of the stack,
 3493: without affecting the stack. Type:
 3494: 
 3495: @example
 3496: @kbd{clearstack 1 2 3@key{RET}} ok
 3497: @kbd{.s@key{RET}} <3> 1 2 3  ok
 3498: @end example
 3499: 
 3500: The text interpreter looks up the word @code{clearstack} and executes
 3501: it; it tidies up the stack and removes any entries that may have been
 3502: left on it by earlier examples. The text interpreter pushes each of the
 3503: three numbers in turn onto the stack. Finally, the text interpreter
 3504: looks up the word @code{.s} and executes it. The effect of executing
 3505: @code{.s} is to print the ``<3>'' (the total number of items on the stack)
 3506: followed by a list of all the items on the stack; the item on the far
 3507: right-hand side is the TOS.
 3508: 
 3509: You can now type:
 3510: 
 3511: @example
 3512: @kbd{+ .s@key{RET}} <2> 1 5  ok
 3513: @end example
 3514: 
 3515: @noindent
 3516: which is correct; there are now 2 items on the stack and the result of
 3517: the addition is 5.
 3518: 
 3519: If you're playing with cards, try doing a second addition: pick up the
 3520: two cards, work out that their sum is 6, shuffle them into the pack,
 3521: look for a 6 and place that on the table. You now have just one item on
 3522: the stack. What happens if you try to do a third addition? Pick up the
 3523: first card, pick up the second card -- ah! There is no second card. This
 3524: is called a @dfn{stack underflow} and consitutes an error. If you try to
 3525: do the same thing with Forth it often reports an error (probably a Stack
 3526: Underflow or an Invalid Memory Address error).
 3527: 
 3528: The opposite situation to a stack underflow is a @dfn{stack overflow},
 3529: which simply accepts that there is a finite amount of storage space
 3530: reserved for the stack. To stretch the playing card analogy, if you had
 3531: enough packs of cards and you piled the cards up on the table, you would
 3532: eventually be unable to add another card; you'd hit the ceiling. Gforth
 3533: allows you to set the maximum size of the stacks. In general, the only
 3534: time that you will get a stack overflow is because a definition has a
 3535: bug in it and is generating data on the stack uncontrollably.
 3536: 
 3537: There's one final use for the playing card analogy. If you model your
 3538: stack using a pack of playing cards, the maximum number of items on
 3539: your stack will be 52 (I assume you didn't use the Joker). The maximum
 3540: @i{value} of any item on the stack is 13 (the King). In fact, the only
 3541: possible numbers are positive integer numbers 1 through 13; you can't
 3542: have (for example) 0 or 27 or 3.52 or -2. If you change the way you
 3543: think about some of the cards, you can accommodate different
 3544: numbers. For example, you could think of the Jack as representing 0,
 3545: the Queen as representing -1 and the King as representing -2. Your
 3546: @i{range} remains unchanged (you can still only represent a total of 13
 3547: numbers) but the numbers that you can represent are -2 through 10.
 3548: 
 3549: In that analogy, the limit was the amount of information that a single
 3550: stack entry could hold, and Forth has a similar limit. In Forth, the
 3551: size of a stack entry is called a @dfn{cell}. The actual size of a cell is
 3552: implementation dependent and affects the maximum value that a stack
 3553: entry can hold. A Standard Forth provides a cell size of at least
 3554: 16-bits, and most desktop systems use a cell size of 32-bits.
 3555: 
 3556: Forth does not do any type checking for you, so you are free to
 3557: manipulate and combine stack items in any way you wish. A convenient way
 3558: of treating stack items is as 2's complement signed integers, and that
 3559: is what Standard words like @code{+} do. Therefore you can type:
 3560: 
 3561: @example
 3562: @kbd{-5 12 + .s@key{RET}} <1> 7  ok
 3563: @end example
 3564: 
 3565: If you use numbers and definitions like @code{+} in order to turn Forth
 3566: into a great big pocket calculator, you will realise that it's rather
 3567: different from a normal calculator. Rather than typing 2 + 3 = you had
 3568: to type 2 3 + (ignore the fact that you had to use @code{.s} to see the
 3569: result). The terminology used to describe this difference is to say that
 3570: your calculator uses @dfn{Infix Notation} (parameters and operators are
 3571: mixed) whilst Forth uses @dfn{Postfix Notation} (parameters and
 3572: operators are separate), also called @dfn{Reverse Polish Notation}.
 3573: 
 3574: Whilst postfix notation might look confusing to begin with, it has
 3575: several important advantages:
 3576: 
 3577: @itemize @bullet
 3578: @item
 3579: it is unambiguous
 3580: @item
 3581: it is more concise
 3582: @item
 3583: it fits naturally with a stack-based system
 3584: @end itemize
 3585: 
 3586: To examine these claims in more detail, consider these sums:
 3587: 
 3588: @example
 3589: 6 + 5 * 4 =
 3590: 4 * 5 + 6 =
 3591: @end example
 3592: 
 3593: If you're just learning maths or your maths is very rusty, you will
 3594: probably come up with the answer 44 for the first and 26 for the
 3595: second. If you are a bit of a whizz at maths you will remember the
 3596: @i{convention} that multiplication takes precendence over addition, and
 3597: you'd come up with the answer 26 both times. To explain the answer 26
 3598: to someone who got the answer 44, you'd probably rewrite the first sum
 3599: like this:
 3600: 
 3601: @example
 3602: 6 + (5 * 4) =
 3603: @end example
 3604: 
 3605: If what you really wanted was to perform the addition before the
 3606: multiplication, you would have to use parentheses to force it.
 3607: 
 3608: If you did the first two sums on a pocket calculator you would probably
 3609: get the right answers, unless you were very cautious and entered them using
 3610: these keystroke sequences:
 3611: 
 3612: 6 + 5 = * 4 =
 3613: 4 * 5 = + 6 =
 3614: 
 3615: Postfix notation is unambiguous because the order that the operators
 3616: are applied is always explicit; that also means that parentheses are
 3617: never required. The operators are @i{active} (the act of quoting the
 3618: operator makes the operation occur) which removes the need for ``=''.
 3619: 
 3620: The sum 6 + 5 * 4 can be written (in postfix notation) in two
 3621: equivalent ways:
 3622: 
 3623: @example
 3624: 6 5 4 * +      or:
 3625: 5 4 * 6 +
 3626: @end example
 3627: 
 3628: An important thing that you should notice about this notation is that
 3629: the @i{order} of the numbers does not change; if you want to subtract
 3630: 2 from 10 you type @code{10 2 -}.
 3631: 
 3632: The reason that Forth uses postfix notation is very simple to explain: it
 3633: makes the implementation extremely simple, and it follows naturally from
 3634: using the stack as a mechanism for passing parameters. Another way of
 3635: thinking about this is to realise that all Forth definitions are
 3636: @i{active}; they execute as they are encountered by the text
 3637: interpreter. The result of this is that the syntax of Forth is trivially
 3638: simple.
 3639: 
 3640: 
 3641: 
 3642: @comment ----------------------------------------------
 3643: @node Your first definition, How does that work?, Stacks and Postfix notation, Introduction
 3644: @section Your first Forth definition
 3645: @cindex first definition
 3646: 
 3647: Until now, the examples we've seen have been trivial; we've just been
 3648: using Forth as a bigger-than-pocket calculator. Also, each calculation
 3649: we've shown has been a ``one-off'' -- to repeat it we'd need to type it in
 3650: again@footnote{That's not quite true. If you press the up-arrow key on
 3651: your keyboard you should be able to scroll back to any earlier command,
 3652: edit it and re-enter it.} In this section we'll see how to add new
 3653: words to Forth's vocabulary.
 3654: 
 3655: The easiest way to create a new word is to use a @dfn{colon
 3656: definition}. We'll define a few and try them out before worrying too
 3657: much about how they work. Try typing in these examples; be careful to
 3658: copy the spaces accurately:
 3659: 
 3660: @example
 3661: : add-two 2 + . ;
 3662: : greet ." Hello and welcome" ;
 3663: : demo 5 add-two ;
 3664: @end example
 3665: 
 3666: @noindent
 3667: Now try them out:
 3668: 
 3669: @example
 3670: @kbd{greet@key{RET}} Hello and welcome  ok
 3671: @kbd{greet greet@key{RET}} Hello and welcomeHello and welcome  ok
 3672: @kbd{4 add-two@key{RET}} 6  ok
 3673: @kbd{demo@key{RET}} 7  ok
 3674: @kbd{9 greet demo add-two@key{RET}} Hello and welcome7 11  ok
 3675: @end example
 3676: 
 3677: The first new thing that we've introduced here is the pair of words
 3678: @code{:} and @code{;}. These are used to start and terminate a new
 3679: definition, respectively. The first word after the @code{:} is the name
 3680: for the new definition.
 3681: 
 3682: As you can see from the examples, a definition is built up of words that
 3683: have already been defined; Forth makes no distinction between
 3684: definitions that existed when you started the system up, and those that
 3685: you define yourself.
 3686: 
 3687: The examples also introduce the words @code{.} (dot), @code{."}
 3688: (dot-quote) and @code{dup} (dewp). Dot takes the value from the top of
 3689: the stack and displays it. It's like @code{.s} except that it only
 3690: displays the top item of the stack and it is destructive; after it has
 3691: executed, the number is no longer on the stack. There is always one
 3692: space printed after the number, and no spaces before it. Dot-quote
 3693: defines a string (a sequence of characters) that will be printed when
 3694: the word is executed. The string can contain any printable characters
 3695: except @code{"}. A @code{"} has a special function; it is not a Forth
 3696: word but it acts as a delimiter (the way that delimiters work is
 3697: described in the next section). Finally, @code{dup} duplicates the value
 3698: at the top of the stack. Try typing @code{5 dup .s} to see what it does.
 3699: 
 3700: We already know that the text interpreter searches through the
 3701: dictionary to locate names. If you've followed the examples earlier, you
 3702: will already have a definition called @code{add-two}. Lets try modifying
 3703: it by typing in a new definition:
 3704: 
 3705: @example
 3706: @kbd{: add-two dup . ." + 2 =" 2 + . ;@key{RET}} redefined add-two  ok
 3707: @end example
 3708: 
 3709: Forth recognised that we were defining a word that already exists, and
 3710: printed a message to warn us of that fact. Let's try out the new
 3711: definition:
 3712: 
 3713: @example
 3714: @kbd{9 add-two@key{RET}} 9 + 2 =11  ok
 3715: @end example
 3716: 
 3717: @noindent
 3718: All that we've actually done here, though, is to create a new
 3719: definition, with a particular name. The fact that there was already a
 3720: definition with the same name did not make any difference to the way
 3721: that the new definition was created (except that Forth printed a warning
 3722: message). The old definition of add-two still exists (try @code{demo}
 3723: again to see that this is true). Any new definition will use the new
 3724: definition of @code{add-two}, but old definitions continue to use the
 3725: version that already existed at the time that they were @code{compiled}.
 3726: 
 3727: Before you go on to the next section, try defining and redefining some
 3728: words of your own.
 3729: 
 3730: @comment ----------------------------------------------
 3731: @node How does that work?, Forth is written in Forth, Your first definition, Introduction
 3732: @section How does that work?
 3733: @cindex parsing words
 3734: 
 3735: @c That's pretty deep (IMO way too deep) for an introduction. - anton
 3736: 
 3737: @c Is it a good idea to talk about the interpretation semantics of a
 3738: @c number? We don't have an xt to go along with it. - anton
 3739: 
 3740: @c Now that I have eliminated execution semantics, I wonder if it would not
 3741: @c be better to keep them (or add run-time semantics), to make it easier to
 3742: @c explain what compilation semantics usually does. - anton
 3743: 
 3744: @c nac-> I removed the term ``default compilation sematics'' from the
 3745: @c introductory chapter. Removing ``execution semantics'' was making
 3746: @c everything simpler to explain, then I think the use of this term made
 3747: @c everything more complex again. I replaced it with ``default
 3748: @c semantics'' (which is used elsewhere in the manual) by which I mean
 3749: @c ``a definition that has neither the immediate nor the compile-only
 3750: @c flag set''.
 3751: 
 3752: @c anton: I have eliminated default semantics (except in one place where it
 3753: @c means "default interpretation and compilation semantics"), because it
 3754: @c makes no sense in the presence of combined words.  I reverted to
 3755: @c "execution semantics" where necessary.
 3756: 
 3757: @c nac-> I reworded big chunks of the ``how does that work''
 3758: @c section (and, unusually for me, I think I even made it shorter!).  See
 3759: @c what you think -- I know I have not addressed your primary concern
 3760: @c that it is too heavy-going for an introduction. From what I understood
 3761: @c of your course notes it looks as though they might be a good framework. 
 3762: @c Things that I've tried to capture here are some things that came as a
 3763: @c great revelation here when I first understood them. Also, I like the
 3764: @c fact that a very simple code example shows up almost all of the issues
 3765: @c that you need to understand to see how Forth works. That's unique and
 3766: @c worthwhile to emphasise.
 3767: 
 3768: @c anton: I think it's a good idea to present the details, especially those
 3769: @c that you found to be a revelation, and probably the tutorial tries to be
 3770: @c too superficial and does not get some of the things across that make
 3771: @c Forth special.  I do believe that most of the time these things should
 3772: @c be discussed at the end of a section or in separate sections instead of
 3773: @c in the middle of a section (e.g., the stuff you added in "User-defined
 3774: @c defining words" leads in a completely different direction from the rest
 3775: @c of the section).
 3776: 
 3777: Now we're going to take another look at the definition of @code{add-two}
 3778: from the previous section. From our knowledge of the way that the text
 3779: interpreter works, we would have expected this result when we tried to
 3780: define @code{add-two}:
 3781: 
 3782: @example
 3783: @kbd{: add-two 2 + . ;@key{RET}}
 3784:   ^^^^^^^
 3785: Error: Undefined word
 3786: @end example
 3787: 
 3788: The reason that this didn't happen is bound up in the way that @code{:}
 3789: works. The word @code{:} does two special things. The first special
 3790: thing that it does prevents the text interpreter from ever seeing the
 3791: characters @code{add-two}. The text interpreter uses a variable called
 3792: @cindex modifying >IN
 3793: @code{>IN} (pronounced ``to-in'') to keep track of where it is in the
 3794: input line. When it encounters the word @code{:} it behaves in exactly
 3795: the same way as it does for any other word; it looks it up in the name
 3796: dictionary, finds its xt and executes it. When @code{:} executes, it
 3797: looks at the input buffer, finds the word @code{add-two} and advances the
 3798: value of @code{>IN} to point past it. It then does some other stuff
 3799: associated with creating the new definition (including creating an entry
 3800: for @code{add-two} in the name dictionary). When the execution of @code{:}
 3801: completes, control returns to the text interpreter, which is oblivious
 3802: to the fact that it has been tricked into ignoring part of the input
 3803: line.
 3804: 
 3805: @cindex parsing words
 3806: Words like @code{:} -- words that advance the value of @code{>IN} and so
 3807: prevent the text interpreter from acting on the whole of the input line
 3808: -- are called @dfn{parsing words}.
 3809: 
 3810: @cindex @code{state} - effect on the text interpreter
 3811: @cindex text interpreter - effect of state
 3812: The second special thing that @code{:} does is change the value of a
 3813: variable called @code{state}, which affects the way that the text
 3814: interpreter behaves. When Gforth starts up, @code{state} has the value
 3815: 0, and the text interpreter is said to be @dfn{interpreting}. During a
 3816: colon definition (started with @code{:}), @code{state} is set to -1 and
 3817: the text interpreter is said to be @dfn{compiling}.
 3818: 
 3819: In this example, the text interpreter is compiling when it processes the
 3820: string ``@code{2 + . ;}''. It still breaks the string down into
 3821: character sequences in the same way. However, instead of pushing the
 3822: number @code{2} onto the stack, it lays down (@dfn{compiles}) some magic
 3823: into the definition of @code{add-two} that will make the number @code{2} get
 3824: pushed onto the stack when @code{add-two} is @dfn{executed}. Similarly,
 3825: the behaviours of @code{+} and @code{.} are also compiled into the
 3826: definition.
 3827: 
 3828: One category of words don't get compiled. These so-called @dfn{immediate
 3829: words} get executed (performed @i{now}) regardless of whether the text
 3830: interpreter is interpreting or compiling. The word @code{;} is an
 3831: immediate word. Rather than being compiled into the definition, it
 3832: executes. Its effect is to terminate the current definition, which
 3833: includes changing the value of @code{state} back to 0.
 3834: 
 3835: When you execute @code{add-two}, it has a @dfn{run-time effect} that is
 3836: exactly the same as if you had typed @code{2 + . @key{RET}} outside of a
 3837: definition.
 3838: 
 3839: In Forth, every word or number can be described in terms of two
 3840: properties:
 3841: 
 3842: @itemize @bullet
 3843: @item
 3844: @cindex interpretation semantics
 3845: Its @dfn{interpretation semantics} describe how it will behave when the
 3846: text interpreter encounters it in @dfn{interpret} state. The
 3847: interpretation semantics of a word are represented by an @dfn{execution
 3848: token}.
 3849: @item
 3850: @cindex compilation semantics
 3851: Its @dfn{compilation semantics} describe how it will behave when the
 3852: text interpreter encounters it in @dfn{compile} state. The compilation
 3853: semantics of a word are represented in an implementation-dependent way;
 3854: Gforth uses a @dfn{compilation token}.
 3855: @end itemize
 3856: 
 3857: @noindent
 3858: Numbers are always treated in a fixed way:
 3859: 
 3860: @itemize @bullet
 3861: @item
 3862: When the number is @dfn{interpreted}, its behaviour is to push the
 3863: number onto the stack.
 3864: @item
 3865: When the number is @dfn{compiled}, a piece of code is appended to the
 3866: current definition that pushes the number when it runs. (In other words,
 3867: the compilation semantics of a number are to postpone its interpretation
 3868: semantics until the run-time of the definition that it is being compiled
 3869: into.)
 3870: @end itemize
 3871: 
 3872: Words don't behave in such a regular way, but most have @i{default
 3873: semantics} which means that they behave like this:
 3874: 
 3875: @itemize @bullet
 3876: @item
 3877: The @dfn{interpretation semantics} of the word are to do something useful.
 3878: @item
 3879: The @dfn{compilation semantics} of the word are to append its
 3880: @dfn{interpretation semantics} to the current definition (so that its
 3881: run-time behaviour is to do something useful).
 3882: @end itemize
 3883: 
 3884: @cindex immediate words
 3885: The actual behaviour of any particular word can be controlled by using
 3886: the words @code{immediate} and @code{compile-only} when the word is
 3887: defined. These words set flags in the name dictionary entry of the most
 3888: recently defined word, and these flags are retrieved by the text
 3889: interpreter when it finds the word in the name dictionary.
 3890: 
 3891: A word that is marked as @dfn{immediate} has compilation semantics that
 3892: are identical to its interpretation semantics. In other words, it
 3893: behaves like this:
 3894: 
 3895: @itemize @bullet
 3896: @item
 3897: The @dfn{interpretation semantics} of the word are to do something useful.
 3898: @item
 3899: The @dfn{compilation semantics} of the word are to do something useful
 3900: (and actually the same thing); i.e., it is executed during compilation.
 3901: @end itemize
 3902: 
 3903: Marking a word as @dfn{compile-only} prohibits the text interpreter from
 3904: performing the interpretation semantics of the word directly; an attempt
 3905: to do so will generate an error. It is never necessary to use
 3906: @code{compile-only} (and it is not even part of ANS Forth, though it is
 3907: provided by many implementations) but it is good etiquette to apply it
 3908: to a word that will not behave correctly (and might have unexpected
 3909: side-effects) in interpret state. For example, it is only legal to use
 3910: the conditional word @code{IF} within a definition. If you forget this
 3911: and try to use it elsewhere, the fact that (in Gforth) it is marked as
 3912: @code{compile-only} allows the text interpreter to generate a helpful
 3913: error message rather than subjecting you to the consequences of your
 3914: folly.
 3915: 
 3916: This example shows the difference between an immediate and a
 3917: non-immediate word:
 3918: 
 3919: @example
 3920: : show-state state @@ . ;
 3921: : show-state-now show-state ; immediate
 3922: : word1 show-state ;
 3923: : word2 show-state-now ;
 3924: @end example
 3925: 
 3926: The word @code{immediate} after the definition of @code{show-state-now}
 3927: makes that word an immediate word. These definitions introduce a new
 3928: word: @code{@@} (pronounced ``fetch''). This word fetches the value of a
 3929: variable, and leaves it on the stack. Therefore, the behaviour of
 3930: @code{show-state} is to print a number that represents the current value
 3931: of @code{state}.
 3932: 
 3933: When you execute @code{word1}, it prints the number 0, indicating that
 3934: the system is interpreting. When the text interpreter compiled the
 3935: definition of @code{word1}, it encountered @code{show-state} whose
 3936: compilation semantics are to append its interpretation semantics to the
 3937: current definition. When you execute @code{word1}, it performs the
 3938: interpretation semantics of @code{show-state}.  At the time that @code{word1}
 3939: (and therefore @code{show-state}) are executed, the system is
 3940: interpreting.
 3941: 
 3942: When you pressed @key{RET} after entering the definition of @code{word2},
 3943: you should have seen the number -1 printed, followed by ``@code{
 3944: ok}''. When the text interpreter compiled the definition of
 3945: @code{word2}, it encountered @code{show-state-now}, an immediate word,
 3946: whose compilation semantics are therefore to perform its interpretation
 3947: semantics. It is executed straight away (even before the text
 3948: interpreter has moved on to process another group of characters; the
 3949: @code{;} in this example). The effect of executing it are to display the
 3950: value of @code{state} @i{at the time that the definition of}
 3951: @code{word2} @i{is being defined}. Printing -1 demonstrates that the
 3952: system is compiling at this time. If you execute @code{word2} it does
 3953: nothing at all.
 3954: 
 3955: @cindex @code{."}, how it works
 3956: Before leaving the subject of immediate words, consider the behaviour of
 3957: @code{."} in the definition of @code{greet}, in the previous
 3958: section. This word is both a parsing word and an immediate word. Notice
 3959: that there is a space between @code{."} and the start of the text
 3960: @code{Hello and welcome}, but that there is no space between the last
 3961: letter of @code{welcome} and the @code{"} character. The reason for this
 3962: is that @code{."} is a Forth word; it must have a space after it so that
 3963: the text interpreter can identify it. The @code{"} is not a Forth word;
 3964: it is a @dfn{delimiter}. The examples earlier show that, when the string
 3965: is displayed, there is neither a space before the @code{H} nor after the
 3966: @code{e}. Since @code{."} is an immediate word, it executes at the time
 3967: that @code{greet} is defined. When it executes, its behaviour is to
 3968: search forward in the input line looking for the delimiter. When it
 3969: finds the delimiter, it updates @code{>IN} to point past the
 3970: delimiter. It also compiles some magic code into the definition of
 3971: @code{greet}; the xt of a run-time routine that prints a text string. It
 3972: compiles the string @code{Hello and welcome} into memory so that it is
 3973: available to be printed later. When the text interpreter gains control,
 3974: the next word it finds in the input stream is @code{;} and so it
 3975: terminates the definition of @code{greet}.
 3976: 
 3977: 
 3978: @comment ----------------------------------------------
 3979: @node Forth is written in Forth, Review - elements of a Forth system, How does that work?, Introduction
 3980: @section Forth is written in Forth
 3981: @cindex structure of Forth programs
 3982: 
 3983: When you start up a Forth compiler, a large number of definitions
 3984: already exist. In Forth, you develop a new application using bottom-up
 3985: programming techniques to create new definitions that are defined in
 3986: terms of existing definitions. As you create each definition you can
 3987: test and debug it interactively.
 3988: 
 3989: If you have tried out the examples in this section, you will probably
 3990: have typed them in by hand; when you leave Gforth, your definitions will
 3991: be lost. You can avoid this by using a text editor to enter Forth source
 3992: code into a file, and then loading code from the file using
 3993: @code{include} (@pxref{Forth source files}). A Forth source file is
 3994: processed by the text interpreter, just as though you had typed it in by
 3995: hand@footnote{Actually, there are some subtle differences -- see
 3996: @ref{The Text Interpreter}.}.
 3997: 
 3998: Gforth also supports the traditional Forth alternative to using text
 3999: files for program entry (@pxref{Blocks}).
 4000: 
 4001: In common with many, if not most, Forth compilers, most of Gforth is
 4002: actually written in Forth. All of the @file{.fs} files in the
 4003: installation directory@footnote{For example,
 4004: @file{/usr/local/share/gforth...}} are Forth source files, which you can
 4005: study to see examples of Forth programming.
 4006: 
 4007: Gforth maintains a history file that records every line that you type to
 4008: the text interpreter. This file is preserved between sessions, and is
 4009: used to provide a command-line recall facility. If you enter long
 4010: definitions by hand, you can use a text editor to paste them out of the
 4011: history file into a Forth source file for reuse at a later time
 4012: (for more information @pxref{Command-line editing}).
 4013: 
 4014: 
 4015: @comment ----------------------------------------------
 4016: @node Review - elements of a Forth system, Where to go next, Forth is written in Forth, Introduction
 4017: @section Review - elements of a Forth system
 4018: @cindex elements of a Forth system
 4019: 
 4020: To summarise this chapter:
 4021: 
 4022: @itemize @bullet
 4023: @item
 4024: Forth programs use @dfn{factoring} to break a problem down into small
 4025: fragments called @dfn{words} or @dfn{definitions}.
 4026: @item
 4027: Forth program development is an interactive process.
 4028: @item
 4029: The main command loop that accepts input, and controls both
 4030: interpretation and compilation, is called the @dfn{text interpreter}
 4031: (also known as the @dfn{outer interpreter}).
 4032: @item
 4033: Forth has a very simple syntax, consisting of words and numbers
 4034: separated by spaces or carriage-return characters. Any additional syntax
 4035: is imposed by @dfn{parsing words}.
 4036: @item
 4037: Forth uses a stack to pass parameters between words. As a result, it
 4038: uses postfix notation.
 4039: @item
 4040: To use a word that has previously been defined, the text interpreter
 4041: searches for the word in the @dfn{name dictionary}.
 4042: @item
 4043: Words have @dfn{interpretation semantics} and @dfn{compilation semantics}.
 4044: @item
 4045: The text interpreter uses the value of @code{state} to select between
 4046: the use of the @dfn{interpretation semantics} and the  @dfn{compilation
 4047: semantics} of a word that it encounters.
 4048: @item
 4049: The relationship between the @dfn{interpretation semantics} and
 4050: @dfn{compilation semantics} for a word
 4051: depend upon the way in which the word was defined (for example, whether
 4052: it is an @dfn{immediate} word).
 4053: @item
 4054: Forth definitions can be implemented in Forth (called @dfn{high-level
 4055: definitions}) or in some other way (usually a lower-level language and
 4056: as a result often called @dfn{low-level definitions}, @dfn{code
 4057: definitions} or @dfn{primitives}).
 4058: @item
 4059: Many Forth systems are implemented mainly in Forth.
 4060: @end itemize
 4061: 
 4062: 
 4063: @comment ----------------------------------------------
 4064: @node Where to go next, Exercises, Review - elements of a Forth system, Introduction
 4065: @section Where To Go Next
 4066: @cindex where to go next
 4067: 
 4068: Amazing as it may seem, if you have read (and understood) this far, you
 4069: know almost all the fundamentals about the inner workings of a Forth
 4070: system. You certainly know enough to be able to read and understand the
 4071: rest of this manual and the ANS Forth document, to learn more about the
 4072: facilities that Forth in general and Gforth in particular provide. Even
 4073: scarier, you know almost enough to implement your own Forth system.
 4074: However, that's not a good idea just yet... better to try writing some
 4075: programs in Gforth.
 4076: 
 4077: Forth has such a rich vocabulary that it can be hard to know where to
 4078: start in learning it. This section suggests a few sets of words that are
 4079: enough to write small but useful programs. Use the word index in this
 4080: document to learn more about each word, then try it out and try to write
 4081: small definitions using it. Start by experimenting with these words:
 4082: 
 4083: @itemize @bullet
 4084: @item
 4085: Arithmetic: @code{+ - * / /MOD */ ABS INVERT}
 4086: @item
 4087: Comparison: @code{MIN MAX =}
 4088: @item
 4089: Logic: @code{AND OR XOR NOT}
 4090: @item
 4091: Stack manipulation: @code{DUP DROP SWAP OVER}
 4092: @item
 4093: Loops and decisions: @code{IF ELSE ENDIF ?DO I LOOP}
 4094: @item
 4095: Input/Output: @code{. ." EMIT CR KEY}
 4096: @item
 4097: Defining words: @code{: ; CREATE}
 4098: @item
 4099: Memory allocation words: @code{ALLOT ,}
 4100: @item
 4101: Tools: @code{SEE WORDS .S MARKER}
 4102: @end itemize
 4103: 
 4104: When you have mastered those, go on to:
 4105: 
 4106: @itemize @bullet
 4107: @item
 4108: More defining words: @code{VARIABLE CONSTANT VALUE TO CREATE DOES>}
 4109: @item
 4110: Memory access: @code{@@ !}
 4111: @end itemize
 4112: 
 4113: When you have mastered these, there's nothing for it but to read through
 4114: the whole of this manual and find out what you've missed.
 4115: 
 4116: @comment ----------------------------------------------
 4117: @node Exercises,  , Where to go next, Introduction
 4118: @section Exercises
 4119: @cindex exercises
 4120: 
 4121: TODO: provide a set of programming excercises linked into the stuff done
 4122: already and into other sections of the manual. Provide solutions to all
 4123: the exercises in a .fs file in the distribution.
 4124: 
 4125: @c Get some inspiration from Starting Forth and Kelly&Spies.
 4126: 
 4127: @c excercises:
 4128: @c 1. take inches and convert to feet and inches.
 4129: @c 2. take temperature and convert from fahrenheight to celcius;
 4130: @c    may need to care about symmetric vs floored??
 4131: @c 3. take input line and do character substitution
 4132: @c    to encipher or decipher
 4133: @c 4. as above but work on a file for in and out
 4134: @c 5. take input line and convert to pig-latin 
 4135: @c
 4136: @c thing of sets of things to exercise then come up with
 4137: @c problems that need those things.
 4138: 
 4139: 
 4140: @c ******************************************************************
 4141: @node Words, Error messages, Introduction, Top
 4142: @chapter Forth Words
 4143: @cindex words
 4144: 
 4145: @menu
 4146: * Notation::                    
 4147: * Case insensitivity::          
 4148: * Comments::                    
 4149: * Boolean Flags::               
 4150: * Arithmetic::                  
 4151: * Stack Manipulation::          
 4152: * Memory::                      
 4153: * Control Structures::          
 4154: * Defining Words::              
 4155: * Interpretation and Compilation Semantics::  
 4156: * Tokens for Words::            
 4157: * Compiling words::             
 4158: * The Text Interpreter::        
 4159: * The Input Stream::            
 4160: * Word Lists::                  
 4161: * Environmental Queries::       
 4162: * Files::                       
 4163: * Blocks::                      
 4164: * Other I/O::                   
 4165: * Locals::                      
 4166: * Structures::                  
 4167: * Object-oriented Forth::       
 4168: * Programming Tools::           
 4169: * Assembler and Code Words::    
 4170: * Threading Words::             
 4171: * Passing Commands to the OS::  
 4172: * Keeping track of Time::       
 4173: * Miscellaneous Words::         
 4174: @end menu
 4175: 
 4176: @node Notation, Case insensitivity, Words, Words
 4177: @section Notation
 4178: @cindex notation of glossary entries
 4179: @cindex format of glossary entries
 4180: @cindex glossary notation format
 4181: @cindex word glossary entry format
 4182: 
 4183: The Forth words are described in this section in the glossary notation
 4184: that has become a de-facto standard for Forth texts:
 4185: 
 4186: @format
 4187: @i{word}     @i{Stack effect}   @i{wordset}   @i{pronunciation}
 4188: @end format
 4189: @i{Description}
 4190: 
 4191: @table @var
 4192: @item word
 4193: The name of the word.
 4194: 
 4195: @item Stack effect
 4196: @cindex stack effect
 4197: The stack effect is written in the notation @code{@i{before} --
 4198: @i{after}}, where @i{before} and @i{after} describe the top of
 4199: stack entries before and after the execution of the word. The rest of
 4200: the stack is not touched by the word. The top of stack is rightmost,
 4201: i.e., a stack sequence is written as it is typed in. Note that Gforth
 4202: uses a separate floating point stack, but a unified stack
 4203: notation. Also, return stack effects are not shown in @i{stack
 4204: effect}, but in @i{Description}. The name of a stack item describes
 4205: the type and/or the function of the item. See below for a discussion of
 4206: the types.
 4207: 
 4208: All words have two stack effects: A compile-time stack effect and a
 4209: run-time stack effect. The compile-time stack-effect of most words is
 4210: @i{ -- }. If the compile-time stack-effect of a word deviates from
 4211: this standard behaviour, or the word does other unusual things at
 4212: compile time, both stack effects are shown; otherwise only the run-time
 4213: stack effect is shown.
 4214: 
 4215: @cindex pronounciation of words
 4216: @item pronunciation
 4217: How the word is pronounced.
 4218: 
 4219: @cindex wordset
 4220: @cindex environment wordset
 4221: @item wordset
 4222: The ANS Forth standard is divided into several word sets. A standard
 4223: system need not support all of them. Therefore, in theory, the fewer
 4224: word sets your program uses the more portable it will be. However, we
 4225: suspect that most ANS Forth systems on personal machines will feature
 4226: all word sets. Words that are not defined in ANS Forth have
 4227: @code{gforth} or @code{gforth-internal} as word set. @code{gforth}
 4228: describes words that will work in future releases of Gforth;
 4229: @code{gforth-internal} words are more volatile. Environmental query
 4230: strings are also displayed like words; you can recognize them by the
 4231: @code{environment} in the word set field.
 4232: 
 4233: @item Description
 4234: A description of the behaviour of the word.
 4235: @end table
 4236: 
 4237: @cindex types of stack items
 4238: @cindex stack item types
 4239: The type of a stack item is specified by the character(s) the name
 4240: starts with:
 4241: 
 4242: @table @code
 4243: @item f
 4244: @cindex @code{f}, stack item type
 4245: Boolean flags, i.e. @code{false} or @code{true}.
 4246: @item c
 4247: @cindex @code{c}, stack item type
 4248: Char
 4249: @item w
 4250: @cindex @code{w}, stack item type
 4251: Cell, can contain an integer or an address
 4252: @item n
 4253: @cindex @code{n}, stack item type
 4254: signed integer
 4255: @item u
 4256: @cindex @code{u}, stack item type
 4257: unsigned integer
 4258: @item d
 4259: @cindex @code{d}, stack item type
 4260: double sized signed integer
 4261: @item ud
 4262: @cindex @code{ud}, stack item type
 4263: double sized unsigned integer
 4264: @item r
 4265: @cindex @code{r}, stack item type
 4266: Float (on the FP stack)
 4267: @item a-
 4268: @cindex @code{a_}, stack item type
 4269: Cell-aligned address
 4270: @item c-
 4271: @cindex @code{c_}, stack item type
 4272: Char-aligned address (note that a Char may have two bytes in Windows NT)
 4273: @item f-
 4274: @cindex @code{f_}, stack item type
 4275: Float-aligned address
 4276: @item df-
 4277: @cindex @code{df_}, stack item type
 4278: Address aligned for IEEE double precision float
 4279: @item sf-
 4280: @cindex @code{sf_}, stack item type
 4281: Address aligned for IEEE single precision float
 4282: @item xt
 4283: @cindex @code{xt}, stack item type
 4284: Execution token, same size as Cell
 4285: @item wid
 4286: @cindex @code{wid}, stack item type
 4287: Word list ID, same size as Cell
 4288: @item ior, wior
 4289: @cindex ior type description
 4290: @cindex wior type description
 4291: I/O result code, cell-sized.  In Gforth, you can @code{throw} iors.
 4292: @item f83name
 4293: @cindex @code{f83name}, stack item type
 4294: Pointer to a name structure
 4295: @item "
 4296: @cindex @code{"}, stack item type
 4297: string in the input stream (not on the stack). The terminating character
 4298: is a blank by default. If it is not a blank, it is shown in @code{<>}
 4299: quotes.
 4300: @end table
 4301: 
 4302: @comment ----------------------------------------------
 4303: @node Case insensitivity, Comments, Notation, Words
 4304: @section Case insensitivity
 4305: @cindex case sensitivity
 4306: @cindex upper and lower case
 4307: 
 4308: Gforth is case-insensitive; you can enter definitions and invoke
 4309: Standard words using upper, lower or mixed case (however,
 4310: @pxref{core-idef, Implementation-defined options, Implementation-defined
 4311: options}).
 4312: 
 4313: ANS Forth only @i{requires} implementations to recognise Standard words
 4314: when they are typed entirely in upper case. Therefore, a Standard
 4315: program must use upper case for all Standard words. You can use whatever
 4316: case you like for words that you define, but in a Standard program you
 4317: have to use the words in the same case that you defined them.
 4318: 
 4319: Gforth supports case sensitivity through @code{table}s (case-sensitive
 4320: wordlists, @pxref{Word Lists}).
 4321: 
 4322: Two people have asked how to convert Gforth to be case-sensitive; while
 4323: we think this is a bad idea, you can change all wordlists into tables
 4324: like this:
 4325: 
 4326: @example
 4327: ' table-find forth-wordlist wordlist-map @ !
 4328: @end example
 4329: 
 4330: Note that you now have to type the predefined words in the same case
 4331: that we defined them, which are varying.  You may want to convert them
 4332: to your favourite case before doing this operation (I won't explain how,
 4333: because if you are even contemplating doing this, you'd better have
 4334: enough knowledge of Forth systems to know this already).
 4335: 
 4336: @node Comments, Boolean Flags, Case insensitivity, Words
 4337: @section Comments
 4338: @cindex comments
 4339: 
 4340: Forth supports two styles of comment; the traditional @i{in-line} comment,
 4341: @code{(} and its modern cousin, the @i{comment to end of line}; @code{\}.
 4342: 
 4343: 
 4344: doc-(
 4345: doc-\
 4346: doc-\G
 4347: 
 4348: 
 4349: @node Boolean Flags, Arithmetic, Comments, Words
 4350: @section Boolean Flags
 4351: @cindex Boolean flags
 4352: 
 4353: A Boolean flag is cell-sized. A cell with all bits clear represents the
 4354: flag @code{false} and a flag with all bits set represents the flag
 4355: @code{true}. Words that check a flag (for example, @code{IF}) will treat
 4356: a cell that has @i{any} bit set as @code{true}.
 4357: @c on and off to Memory? 
 4358: @c true and false to "Bitwise operations" or "Numeric comparison"?
 4359: 
 4360: doc-true
 4361: doc-false
 4362: doc-on
 4363: doc-off
 4364: 
 4365: 
 4366: @node Arithmetic, Stack Manipulation, Boolean Flags, Words
 4367: @section Arithmetic
 4368: @cindex arithmetic words
 4369: 
 4370: @cindex division with potentially negative operands
 4371: Forth arithmetic is not checked, i.e., you will not hear about integer
 4372: overflow on addition or multiplication, you may hear about division by
 4373: zero if you are lucky. The operator is written after the operands, but
 4374: the operands are still in the original order. I.e., the infix @code{2-1}
 4375: corresponds to @code{2 1 -}. Forth offers a variety of division
 4376: operators. If you perform division with potentially negative operands,
 4377: you do not want to use @code{/} or @code{/mod} with its undefined
 4378: behaviour, but rather @code{fm/mod} or @code{sm/mod} (probably the
 4379: former, @pxref{Mixed precision}).
 4380: @comment TODO discuss the different division forms and the std approach
 4381: 
 4382: @menu
 4383: * Single precision::            
 4384: * Double precision::            Double-cell integer arithmetic
 4385: * Bitwise operations::          
 4386: * Numeric comparison::          
 4387: * Mixed precision::             Operations with single and double-cell integers
 4388: * Floating Point::              
 4389: @end menu
 4390: 
 4391: @node Single precision, Double precision, Arithmetic, Arithmetic
 4392: @subsection Single precision
 4393: @cindex single precision arithmetic words
 4394: 
 4395: @c !! cell undefined
 4396: 
 4397: By default, numbers in Forth are single-precision integers that are one
 4398: cell in size. They can be signed or unsigned, depending upon how you
 4399: treat them. For the rules used by the text interpreter for recognising
 4400: single-precision integers see @ref{Number Conversion}.
 4401: 
 4402: These words are all defined for signed operands, but some of them also
 4403: work for unsigned numbers: @code{+}, @code{1+}, @code{-}, @code{1-},
 4404: @code{*}.
 4405: 
 4406: doc-+
 4407: doc-1+
 4408: doc--
 4409: doc-1-
 4410: doc-*
 4411: doc-/
 4412: doc-mod
 4413: doc-/mod
 4414: doc-negate
 4415: doc-abs
 4416: doc-min
 4417: doc-max
 4418: doc-floored
 4419: 
 4420: 
 4421: @node Double precision, Bitwise operations, Single precision, Arithmetic
 4422: @subsection Double precision
 4423: @cindex double precision arithmetic words
 4424: 
 4425: For the rules used by the text interpreter for
 4426: recognising double-precision integers, see @ref{Number Conversion}.
 4427: 
 4428: A double precision number is represented by a cell pair, with the most
 4429: significant cell at the TOS. It is trivial to convert an unsigned single
 4430: to a double: simply push a @code{0} onto the TOS. Since numbers are
 4431: represented by Gforth using 2's complement arithmetic, converting a
 4432: signed single to a (signed) double requires sign-extension across the
 4433: most significant cell. This can be achieved using @code{s>d}. The moral
 4434: of the story is that you cannot convert a number without knowing whether
 4435: it represents an unsigned or a signed number.
 4436: 
 4437: These words are all defined for signed operands, but some of them also
 4438: work for unsigned numbers: @code{d+}, @code{d-}.
 4439: 
 4440: doc-s>d
 4441: doc-d>s
 4442: doc-d+
 4443: doc-d-
 4444: doc-dnegate
 4445: doc-dabs
 4446: doc-dmin
 4447: doc-dmax
 4448: 
 4449: 
 4450: @node Bitwise operations, Numeric comparison, Double precision, Arithmetic
 4451: @subsection Bitwise operations
 4452: @cindex bitwise operation words
 4453: 
 4454: 
 4455: doc-and
 4456: doc-or
 4457: doc-xor
 4458: doc-invert
 4459: doc-lshift
 4460: doc-rshift
 4461: doc-2*
 4462: doc-d2*
 4463: doc-2/
 4464: doc-d2/
 4465: 
 4466: 
 4467: @node Numeric comparison, Mixed precision, Bitwise operations, Arithmetic
 4468: @subsection Numeric comparison
 4469: @cindex numeric comparison words
 4470: 
 4471: Note that the words that compare for equality (@code{= <> 0= 0<> d= d<>
 4472: d0= d0<>}) work for for both signed and unsigned numbers.
 4473: 
 4474: doc-<
 4475: doc-<=
 4476: doc-<>
 4477: doc-=
 4478: doc->
 4479: doc->=
 4480: 
 4481: doc-0<
 4482: doc-0<=
 4483: doc-0<>
 4484: doc-0=
 4485: doc-0>
 4486: doc-0>=
 4487: 
 4488: doc-u<
 4489: doc-u<=
 4490: @c u<> and u= exist but are the same as <> and =
 4491: @c doc-u<>
 4492: @c doc-u=
 4493: doc-u>
 4494: doc-u>=
 4495: 
 4496: doc-within
 4497: 
 4498: doc-d<
 4499: doc-d<=
 4500: doc-d<>
 4501: doc-d=
 4502: doc-d>
 4503: doc-d>=
 4504: 
 4505: doc-d0<
 4506: doc-d0<=
 4507: doc-d0<>
 4508: doc-d0=
 4509: doc-d0>
 4510: doc-d0>=
 4511: 
 4512: doc-du<
 4513: doc-du<=
 4514: @c du<> and du= exist but are the same as d<> and d=
 4515: @c doc-du<>
 4516: @c doc-du=
 4517: doc-du>
 4518: doc-du>=
 4519: 
 4520: 
 4521: @node Mixed precision, Floating Point, Numeric comparison, Arithmetic
 4522: @subsection Mixed precision
 4523: @cindex mixed precision arithmetic words
 4524: 
 4525: 
 4526: doc-m+
 4527: doc-*/
 4528: doc-*/mod
 4529: doc-m*
 4530: doc-um*
 4531: doc-m*/
 4532: doc-um/mod
 4533: doc-fm/mod
 4534: doc-sm/rem
 4535: 
 4536: 
 4537: @node Floating Point,  , Mixed precision, Arithmetic
 4538: @subsection Floating Point
 4539: @cindex floating point arithmetic words
 4540: 
 4541: For the rules used by the text interpreter for
 4542: recognising floating-point numbers see @ref{Number Conversion}.
 4543: 
 4544: Gforth has a separate floating point stack, but the documentation uses
 4545: the unified notation.@footnote{It's easy to generate the separate
 4546: notation from that by just separating the floating-point numbers out:
 4547: e.g. @code{( n r1 u r2 -- r3 )} becomes @code{( n u -- ) ( F: r1 r2 --
 4548: r3 )}.}
 4549: 
 4550: @cindex floating-point arithmetic, pitfalls
 4551: Floating point numbers have a number of unpleasant surprises for the
 4552: unwary (e.g., floating point addition is not associative) and even a few
 4553: for the wary. You should not use them unless you know what you are doing
 4554: or you don't care that the results you get are totally bogus. If you
 4555: want to learn about the problems of floating point numbers (and how to
 4556: avoid them), you might start with @cite{David Goldberg,
 4557: @uref{http://www.validgh.com/goldberg/paper.ps,What Every Computer
 4558: Scientist Should Know About Floating-Point Arithmetic}, ACM Computing
 4559: Surveys 23(1):5@minus{}48, March 1991}.
 4560: 
 4561: 
 4562: doc-d>f
 4563: doc-f>d
 4564: doc-f+
 4565: doc-f-
 4566: doc-f*
 4567: doc-f/
 4568: doc-fnegate
 4569: doc-fabs
 4570: doc-fmax
 4571: doc-fmin
 4572: doc-floor
 4573: doc-fround
 4574: doc-f**
 4575: doc-fsqrt
 4576: doc-fexp
 4577: doc-fexpm1
 4578: doc-fln
 4579: doc-flnp1
 4580: doc-flog
 4581: doc-falog
 4582: doc-f2*
 4583: doc-f2/
 4584: doc-1/f
 4585: doc-precision
 4586: doc-set-precision
 4587: 
 4588: @cindex angles in trigonometric operations
 4589: @cindex trigonometric operations
 4590: Angles in floating point operations are given in radians (a full circle
 4591: has 2 pi radians).
 4592: 
 4593: doc-fsin
 4594: doc-fcos
 4595: doc-fsincos
 4596: doc-ftan
 4597: doc-fasin
 4598: doc-facos
 4599: doc-fatan
 4600: doc-fatan2
 4601: doc-fsinh
 4602: doc-fcosh
 4603: doc-ftanh
 4604: doc-fasinh
 4605: doc-facosh
 4606: doc-fatanh
 4607: doc-pi
 4608: 
 4609: @cindex equality of floats
 4610: @cindex floating-point comparisons
 4611: One particular problem with floating-point arithmetic is that comparison
 4612: for equality often fails when you would expect it to succeed.  For this
 4613: reason approximate equality is often preferred (but you still have to
 4614: know what you are doing).  Also note that IEEE NaNs may compare
 4615: differently from what you might expect.  The comparison words are:
 4616: 
 4617: doc-f~rel
 4618: doc-f~abs
 4619: doc-f~
 4620: doc-f=
 4621: doc-f<>
 4622: 
 4623: doc-f<
 4624: doc-f<=
 4625: doc-f>
 4626: doc-f>=
 4627: 
 4628: doc-f0<
 4629: doc-f0<=
 4630: doc-f0<>
 4631: doc-f0=
 4632: doc-f0>
 4633: doc-f0>=
 4634: 
 4635: 
 4636: @node Stack Manipulation, Memory, Arithmetic, Words
 4637: @section Stack Manipulation
 4638: @cindex stack manipulation words
 4639: 
 4640: @cindex floating-point stack in the standard
 4641: Gforth maintains a number of separate stacks:
 4642: 
 4643: @cindex data stack
 4644: @cindex parameter stack
 4645: @itemize @bullet
 4646: @item
 4647: A data stack (also known as the @dfn{parameter stack}) -- for
 4648: characters, cells, addresses, and double cells.
 4649: 
 4650: @cindex floating-point stack
 4651: @item
 4652: A floating point stack -- for holding floating point (FP) numbers.
 4653: 
 4654: @cindex return stack
 4655: @item
 4656: A return stack -- for holding the return addresses of colon
 4657: definitions and other (non-FP) data.
 4658: 
 4659: @cindex locals stack
 4660: @item
 4661: A locals stack -- for holding local variables.
 4662: @end itemize
 4663: 
 4664: @menu
 4665: * Data stack::                  
 4666: * Floating point stack::        
 4667: * Return stack::                
 4668: * Locals stack::                
 4669: * Stack pointer manipulation::  
 4670: @end menu
 4671: 
 4672: @node Data stack, Floating point stack, Stack Manipulation, Stack Manipulation
 4673: @subsection Data stack
 4674: @cindex data stack manipulation words
 4675: @cindex stack manipulations words, data stack
 4676: 
 4677: 
 4678: doc-drop
 4679: doc-nip
 4680: doc-dup
 4681: doc-over
 4682: doc-tuck
 4683: doc-swap
 4684: doc-pick
 4685: doc-rot
 4686: doc--rot
 4687: doc-?dup
 4688: doc-roll
 4689: doc-2drop
 4690: doc-2nip
 4691: doc-2dup
 4692: doc-2over
 4693: doc-2tuck
 4694: doc-2swap
 4695: doc-2rot
 4696: 
 4697: 
 4698: @node Floating point stack, Return stack, Data stack, Stack Manipulation
 4699: @subsection Floating point stack
 4700: @cindex floating-point stack manipulation words
 4701: @cindex stack manipulation words, floating-point stack
 4702: 
 4703: Whilst every sane Forth has a separate floating-point stack, it is not
 4704: strictly required; an ANS Forth system could theoretically keep
 4705: floating-point numbers on the data stack. As an additional difficulty,
 4706: you don't know how many cells a floating-point number takes. It is
 4707: reportedly possible to write words in a way that they work also for a
 4708: unified stack model, but we do not recommend trying it. Instead, just
 4709: say that your program has an environmental dependency on a separate
 4710: floating-point stack.
 4711: 
 4712: doc-floating-stack
 4713: 
 4714: doc-fdrop
 4715: doc-fnip
 4716: doc-fdup
 4717: doc-fover
 4718: doc-ftuck
 4719: doc-fswap
 4720: doc-fpick
 4721: doc-frot
 4722: 
 4723: 
 4724: @node Return stack, Locals stack, Floating point stack, Stack Manipulation
 4725: @subsection Return stack
 4726: @cindex return stack manipulation words
 4727: @cindex stack manipulation words, return stack
 4728: 
 4729: @cindex return stack and locals
 4730: @cindex locals and return stack
 4731: A Forth system is allowed to keep local variables on the
 4732: return stack. This is reasonable, as local variables usually eliminate
 4733: the need to use the return stack explicitly. So, if you want to produce
 4734: a standard compliant program and you are using local variables in a
 4735: word, forget about return stack manipulations in that word (refer to the
 4736: standard document for the exact rules).
 4737: 
 4738: doc->r
 4739: doc-r>
 4740: doc-r@
 4741: doc-rdrop
 4742: doc-2>r
 4743: doc-2r>
 4744: doc-2r@
 4745: doc-2rdrop
 4746: 
 4747: 
 4748: @node Locals stack, Stack pointer manipulation, Return stack, Stack Manipulation
 4749: @subsection Locals stack
 4750: 
 4751: Gforth uses an extra locals stack.  It is described, along with the
 4752: reasons for its existence, in @ref{Locals implementation}.
 4753: 
 4754: @node Stack pointer manipulation,  , Locals stack, Stack Manipulation
 4755: @subsection Stack pointer manipulation
 4756: @cindex stack pointer manipulation words
 4757: 
 4758: @c removed s0 r0 l0 -- they are obsolete aliases for sp0 rp0 lp0
 4759: doc-sp0
 4760: doc-sp@
 4761: doc-sp!
 4762: doc-fp0
 4763: doc-fp@
 4764: doc-fp!
 4765: doc-rp0
 4766: doc-rp@
 4767: doc-rp!
 4768: doc-lp0
 4769: doc-lp@
 4770: doc-lp!
 4771: 
 4772: 
 4773: @node Memory, Control Structures, Stack Manipulation, Words
 4774: @section Memory
 4775: @cindex memory words
 4776: 
 4777: @menu
 4778: * Memory model::                
 4779: * Dictionary allocation::       
 4780: * Heap Allocation::             
 4781: * Memory Access::               
 4782: * Address arithmetic::          
 4783: * Memory Blocks::               
 4784: @end menu
 4785: 
 4786: In addition to the standard Forth memory allocation words, there is also
 4787: a @uref{http://www.complang.tuwien.ac.at/forth/garbage-collection.zip,
 4788: garbage collector}.
 4789: 
 4790: @node Memory model, Dictionary allocation, Memory, Memory
 4791: @subsection ANS Forth and Gforth memory models
 4792: 
 4793: @c The ANS Forth description is a mess (e.g., is the heap part of
 4794: @c the dictionary?), so let's not stick to closely with it.
 4795: 
 4796: ANS Forth considers a Forth system as consisting of several address
 4797: spaces, of which only @dfn{data space} is managed and accessible with
 4798: the memory words.  Memory not necessarily in data space includes the
 4799: stacks, the code (called code space) and the headers (called name
 4800: space). In Gforth everything is in data space, but the code for the
 4801: primitives is usually read-only.
 4802: 
 4803: Data space is divided into a number of areas: The (data space portion of
 4804: the) dictionary@footnote{Sometimes, the term @dfn{dictionary} is used to
 4805: refer to the search data structure embodied in word lists and headers,
 4806: because it is used for looking up names, just as you would in a
 4807: conventional dictionary.}, the heap, and a number of system-allocated
 4808: buffers.
 4809: 
 4810: @cindex address arithmetic restrictions, ANS vs. Gforth
 4811: @cindex contiguous regions, ANS vs. Gforth
 4812: In ANS Forth data space is also divided into contiguous regions.  You
 4813: can only use address arithmetic within a contiguous region, not between
 4814: them.  Usually each allocation gives you one contiguous region, but the
 4815: dictionary allocation words have additional rules (@pxref{Dictionary
 4816: allocation}).
 4817: 
 4818: Gforth provides one big address space, and address arithmetic can be
 4819: performed between any addresses. However, in the dictionary headers or
 4820: code are interleaved with data, so almost the only contiguous data space
 4821: regions there are those described by ANS Forth as contiguous; but you
 4822: can be sure that the dictionary is allocated towards increasing
 4823: addresses even between contiguous regions.  The memory order of
 4824: allocations in the heap is platform-dependent (and possibly different
 4825: from one run to the next).
 4826: 
 4827: 
 4828: @node Dictionary allocation, Heap Allocation, Memory model, Memory
 4829: @subsection Dictionary allocation
 4830: @cindex reserving data space
 4831: @cindex data space - reserving some
 4832: 
 4833: Dictionary allocation is a stack-oriented allocation scheme, i.e., if
 4834: you want to deallocate X, you also deallocate everything
 4835: allocated after X.
 4836: 
 4837: @cindex contiguous regions in dictionary allocation
 4838: The allocations using the words below are contiguous and grow the region
 4839: towards increasing addresses.  Other words that allocate dictionary
 4840: memory of any kind (i.e., defining words including @code{:noname}) end
 4841: the contiguous region and start a new one.
 4842: 
 4843: In ANS Forth only @code{create}d words are guaranteed to produce an
 4844: address that is the start of the following contiguous region.  In
 4845: particular, the cell allocated by @code{variable} is not guaranteed to
 4846: be contiguous with following @code{allot}ed memory.
 4847: 
 4848: You can deallocate memory by using @code{allot} with a negative argument
 4849: (with some restrictions, see @code{allot}). For larger deallocations use
 4850: @code{marker}.
 4851: 
 4852: 
 4853: doc-here
 4854: doc-unused
 4855: doc-allot
 4856: doc-c,
 4857: doc-f,
 4858: doc-,
 4859: doc-2,
 4860: 
 4861: Memory accesses have to be aligned (@pxref{Address arithmetic}). So of
 4862: course you should allocate memory in an aligned way, too. I.e., before
 4863: allocating allocating a cell, @code{here} must be cell-aligned, etc.
 4864: The words below align @code{here} if it is not already.  Basically it is
 4865: only already aligned for a type, if the last allocation was a multiple
 4866: of the size of this type and if @code{here} was aligned for this type
 4867: before.
 4868: 
 4869: After freshly @code{create}ing a word, @code{here} is @code{align}ed in
 4870: ANS Forth (@code{maxalign}ed in Gforth).
 4871: 
 4872: doc-align
 4873: doc-falign
 4874: doc-sfalign
 4875: doc-dfalign
 4876: doc-maxalign
 4877: doc-cfalign
 4878: 
 4879: 
 4880: @node Heap Allocation, Memory Access, Dictionary allocation, Memory
 4881: @subsection Heap allocation
 4882: @cindex heap allocation
 4883: @cindex dynamic allocation of memory
 4884: @cindex memory-allocation word set
 4885: 
 4886: @cindex contiguous regions and heap allocation
 4887: Heap allocation supports deallocation of allocated memory in any
 4888: order. Dictionary allocation is not affected by it (i.e., it does not
 4889: end a contiguous region). In Gforth, these words are implemented using
 4890: the standard C library calls malloc(), free() and resize().
 4891: 
 4892: The memory region produced by one invocation of @code{allocate} or
 4893: @code{resize} is internally contiguous.  There is no contiguity between
 4894: such a region and any other region (including others allocated from the
 4895: heap).
 4896: 
 4897: doc-allocate
 4898: doc-free
 4899: doc-resize
 4900: 
 4901: 
 4902: @node Memory Access, Address arithmetic, Heap Allocation, Memory
 4903: @subsection Memory Access
 4904: @cindex memory access words
 4905: 
 4906: doc-@
 4907: doc-!
 4908: doc-+!
 4909: doc-c@
 4910: doc-c!
 4911: doc-2@
 4912: doc-2!
 4913: doc-f@
 4914: doc-f!
 4915: doc-sf@
 4916: doc-sf!
 4917: doc-df@
 4918: doc-df!
 4919: 
 4920: 
 4921: @node Address arithmetic, Memory Blocks, Memory Access, Memory
 4922: @subsection Address arithmetic
 4923: @cindex address arithmetic words
 4924: 
 4925: Address arithmetic is the foundation on which you can build data
 4926: structures like arrays, records (@pxref{Structures}) and objects
 4927: (@pxref{Object-oriented Forth}).
 4928: 
 4929: @cindex address unit
 4930: @cindex au (address unit)
 4931: ANS Forth does not specify the sizes of the data types. Instead, it
 4932: offers a number of words for computing sizes and doing address
 4933: arithmetic. Address arithmetic is performed in terms of address units
 4934: (aus); on most systems the address unit is one byte. Note that a
 4935: character may have more than one au, so @code{chars} is no noop (on
 4936: platforms where it is a noop, it compiles to nothing).
 4937: 
 4938: The basic address arithmetic words are @code{+} and @code{-}.  E.g., if
 4939: you have the address of a cell, perform @code{1 cells +}, and you will
 4940: have the address of the next cell.
 4941: 
 4942: @cindex contiguous regions and address arithmetic
 4943: In ANS Forth you can perform address arithmetic only within a contiguous
 4944: region, i.e., if you have an address into one region, you can only add
 4945: and subtract such that the result is still within the region; you can
 4946: only subtract or compare addresses from within the same contiguous
 4947: region.  Reasons: several contiguous regions can be arranged in memory
 4948: in any way; on segmented systems addresses may have unusual
 4949: representations, such that address arithmetic only works within a
 4950: region.  Gforth provides a few more guarantees (linear address space,
 4951: dictionary grows upwards), but in general I have found it easy to stay
 4952: within contiguous regions (exception: computing and comparing to the
 4953: address just beyond the end of an array).
 4954: 
 4955: @cindex alignment of addresses for types
 4956: ANS Forth also defines words for aligning addresses for specific
 4957: types. Many computers require that accesses to specific data types
 4958: must only occur at specific addresses; e.g., that cells may only be
 4959: accessed at addresses divisible by 4. Even if a machine allows unaligned
 4960: accesses, it can usually perform aligned accesses faster. 
 4961: 
 4962: For the performance-conscious: alignment operations are usually only
 4963: necessary during the definition of a data structure, not during the
 4964: (more frequent) accesses to it.
 4965: 
 4966: ANS Forth defines no words for character-aligning addresses. This is not
 4967: an oversight, but reflects the fact that addresses that are not
 4968: char-aligned have no use in the standard and therefore will not be
 4969: created.
 4970: 
 4971: @cindex @code{CREATE} and alignment
 4972: ANS Forth guarantees that addresses returned by @code{CREATE}d words
 4973: are cell-aligned; in addition, Gforth guarantees that these addresses
 4974: are aligned for all purposes.
 4975: 
 4976: Note that the ANS Forth word @code{char} has nothing to do with address
 4977: arithmetic.
 4978: 
 4979: 
 4980: doc-chars
 4981: doc-char+
 4982: doc-cells
 4983: doc-cell+
 4984: doc-cell
 4985: doc-aligned
 4986: doc-floats
 4987: doc-float+
 4988: doc-float
 4989: doc-faligned
 4990: doc-sfloats
 4991: doc-sfloat+
 4992: doc-sfaligned
 4993: doc-dfloats
 4994: doc-dfloat+
 4995: doc-dfaligned
 4996: doc-maxaligned
 4997: doc-cfaligned
 4998: doc-address-unit-bits
 4999: 
 5000: 
 5001: @node Memory Blocks,  , Address arithmetic, Memory
 5002: @subsection Memory Blocks
 5003: @cindex memory block words
 5004: @cindex character strings - moving and copying
 5005: 
 5006: Memory blocks often represent character strings; For ways of storing
 5007: character strings in memory see @ref{String Formats}.  For other
 5008: string-processing words see @ref{Displaying characters and strings}.
 5009: 
 5010: A few of these words work on address unit blocks.  In that case, you
 5011: usually have to insert @code{CHARS} before the word when working on
 5012: character strings.  Most words work on character blocks, and expect a
 5013: char-aligned address.
 5014: 
 5015: When copying characters between overlapping memory regions, use
 5016: @code{chars move} or choose carefully between @code{cmove} and
 5017: @code{cmove>}.
 5018: 
 5019: doc-move
 5020: doc-erase
 5021: doc-cmove
 5022: doc-cmove>
 5023: doc-fill
 5024: doc-blank
 5025: doc-compare
 5026: doc-str=
 5027: doc-str<
 5028: doc-string-prefix?
 5029: doc-search
 5030: doc--trailing
 5031: doc-/string
 5032: doc-bounds
 5033: 
 5034: 
 5035: @comment TODO examples
 5036: 
 5037: 
 5038: @node Control Structures, Defining Words, Memory, Words
 5039: @section Control Structures
 5040: @cindex control structures
 5041: 
 5042: Control structures in Forth cannot be used interpretively, only in a
 5043: colon definition@footnote{To be precise, they have no interpretation
 5044: semantics (@pxref{Interpretation and Compilation Semantics}).}. We do
 5045: not like this limitation, but have not seen a satisfying way around it
 5046: yet, although many schemes have been proposed.
 5047: 
 5048: @menu
 5049: * Selection::                   IF ... ELSE ... ENDIF
 5050: * Simple Loops::                BEGIN ...
 5051: * Counted Loops::               DO
 5052: * Arbitrary control structures::  
 5053: * Calls and returns::           
 5054: * Exception Handling::          
 5055: @end menu
 5056: 
 5057: @node Selection, Simple Loops, Control Structures, Control Structures
 5058: @subsection Selection
 5059: @cindex selection control structures
 5060: @cindex control structures for selection
 5061: 
 5062: @cindex @code{IF} control structure
 5063: @example
 5064: @i{flag}
 5065: IF
 5066:   @i{code}
 5067: ENDIF
 5068: @end example
 5069: @noindent
 5070: 
 5071: If @i{flag} is non-zero (as far as @code{IF} etc. are concerned, a cell
 5072: with any bit set represents truth) @i{code} is executed.
 5073: 
 5074: @example
 5075: @i{flag}
 5076: IF
 5077:   @i{code1}
 5078: ELSE
 5079:   @i{code2}
 5080: ENDIF
 5081: @end example
 5082: 
 5083: If @var{flag} is true, @i{code1} is executed, otherwise @i{code2} is
 5084: executed.
 5085: 
 5086: You can use @code{THEN} instead of @code{ENDIF}. Indeed, @code{THEN} is
 5087: standard, and @code{ENDIF} is not, although it is quite popular. We
 5088: recommend using @code{ENDIF}, because it is less confusing for people
 5089: who also know other languages (and is not prone to reinforcing negative
 5090: prejudices against Forth in these people). Adding @code{ENDIF} to a
 5091: system that only supplies @code{THEN} is simple:
 5092: @example
 5093: : ENDIF   POSTPONE then ; immediate
 5094: @end example
 5095: 
 5096: [According to @cite{Webster's New Encyclopedic Dictionary}, @dfn{then
 5097: (adv.)}  has the following meanings:
 5098: @quotation
 5099: ... 2b: following next after in order ... 3d: as a necessary consequence
 5100: (if you were there, then you saw them).
 5101: @end quotation
 5102: Forth's @code{THEN} has the meaning 2b, whereas @code{THEN} in Pascal
 5103: and many other programming languages has the meaning 3d.]
 5104: 
 5105: Gforth also provides the words @code{?DUP-IF} and @code{?DUP-0=-IF}, so
 5106: you can avoid using @code{?dup}. Using these alternatives is also more
 5107: efficient than using @code{?dup}. Definitions in ANS Forth
 5108: for @code{ENDIF}, @code{?DUP-IF} and @code{?DUP-0=-IF} are provided in
 5109: @file{compat/control.fs}.
 5110: 
 5111: @cindex @code{CASE} control structure
 5112: @example
 5113: @i{n}
 5114: CASE
 5115:   @i{n1} OF @i{code1} ENDOF
 5116:   @i{n2} OF @i{code2} ENDOF
 5117:   @dots{}
 5118:   ( n ) @i{default-code} ( n )
 5119: ENDCASE
 5120: @end example
 5121: 
 5122: Executes the first @i{codei}, where the @i{ni} is equal to @i{n}.  If no
 5123: @i{ni} matches, the optional @i{default-code} is executed. The optional
 5124: default case can be added by simply writing the code after the last
 5125: @code{ENDOF}. It may use @i{n}, which is on top of the stack, but must
 5126: not consume it.
 5127: 
 5128: @progstyle
 5129: To keep the code understandable, you should ensure that on all paths
 5130: through a selection construct the stack is changed in the same way
 5131: (wrt. number and types of stack items consumed and pushed).
 5132: 
 5133: @node Simple Loops, Counted Loops, Selection, Control Structures
 5134: @subsection Simple Loops
 5135: @cindex simple loops
 5136: @cindex loops without count 
 5137: 
 5138: @cindex @code{WHILE} loop
 5139: @example
 5140: BEGIN
 5141:   @i{code1}
 5142:   @i{flag}
 5143: WHILE
 5144:   @i{code2}
 5145: REPEAT
 5146: @end example
 5147: 
 5148: @i{code1} is executed and @i{flag} is computed. If it is true,
 5149: @i{code2} is executed and the loop is restarted; If @i{flag} is
 5150: false, execution continues after the @code{REPEAT}.
 5151: 
 5152: @cindex @code{UNTIL} loop
 5153: @example
 5154: BEGIN
 5155:   @i{code}
 5156:   @i{flag}
 5157: UNTIL
 5158: @end example
 5159: 
 5160: @i{code} is executed. The loop is restarted if @code{flag} is false.
 5161: 
 5162: @progstyle
 5163: To keep the code understandable, a complete iteration of the loop should
 5164: not change the number and types of the items on the stacks.
 5165: 
 5166: @cindex endless loop
 5167: @cindex loops, endless
 5168: @example
 5169: BEGIN
 5170:   @i{code}
 5171: AGAIN
 5172: @end example
 5173: 
 5174: This is an endless loop.
 5175: 
 5176: @node Counted Loops, Arbitrary control structures, Simple Loops, Control Structures
 5177: @subsection Counted Loops
 5178: @cindex counted loops
 5179: @cindex loops, counted
 5180: @cindex @code{DO} loops
 5181: 
 5182: The basic counted loop is:
 5183: @example
 5184: @i{limit} @i{start}
 5185: ?DO
 5186:   @i{body}
 5187: LOOP
 5188: @end example
 5189: 
 5190: This performs one iteration for every integer, starting from @i{start}
 5191: and up to, but excluding @i{limit}. The counter, or @i{index}, can be
 5192: accessed with @code{i}. For example, the loop:
 5193: @example
 5194: 10 0 ?DO
 5195:   i .
 5196: LOOP
 5197: @end example
 5198: @noindent
 5199: prints @code{0 1 2 3 4 5 6 7 8 9}
 5200: 
 5201: The index of the innermost loop can be accessed with @code{i}, the index
 5202: of the next loop with @code{j}, and the index of the third loop with
 5203: @code{k}.
 5204: 
 5205: 
 5206: doc-i
 5207: doc-j
 5208: doc-k
 5209: 
 5210: 
 5211: The loop control data are kept on the return stack, so there are some
 5212: restrictions on mixing return stack accesses and counted loop words. In
 5213: particuler, if you put values on the return stack outside the loop, you
 5214: cannot read them inside the loop@footnote{well, not in a way that is
 5215: portable.}. If you put values on the return stack within a loop, you
 5216: have to remove them before the end of the loop and before accessing the
 5217: index of the loop.
 5218: 
 5219: There are several variations on the counted loop:
 5220: 
 5221: @itemize @bullet
 5222: @item
 5223: @code{LEAVE} leaves the innermost counted loop immediately; execution
 5224: continues after the associated @code{LOOP} or @code{NEXT}. For example:
 5225: 
 5226: @example
 5227: 10 0 ?DO  i DUP . 3 = IF LEAVE THEN LOOP
 5228: @end example
 5229: prints @code{0 1 2 3}
 5230: 
 5231: 
 5232: @item
 5233: @code{UNLOOP} prepares for an abnormal loop exit, e.g., via
 5234: @code{EXIT}. @code{UNLOOP} removes the loop control parameters from the
 5235: return stack so @code{EXIT} can get to its return address. For example:
 5236: 
 5237: @example
 5238: : demo 10 0 ?DO i DUP . 3 = IF UNLOOP EXIT THEN LOOP ." Done" ;
 5239: @end example
 5240: prints @code{0 1 2 3}
 5241: 
 5242: 
 5243: @item
 5244: If @i{start} is greater than @i{limit}, a @code{?DO} loop is entered
 5245: (and @code{LOOP} iterates until they become equal by wrap-around
 5246: arithmetic). This behaviour is usually not what you want. Therefore,
 5247: Gforth offers @code{+DO} and @code{U+DO} (as replacements for
 5248: @code{?DO}), which do not enter the loop if @i{start} is greater than
 5249: @i{limit}; @code{+DO} is for signed loop parameters, @code{U+DO} for
 5250: unsigned loop parameters.
 5251: 
 5252: @item
 5253: @code{?DO} can be replaced by @code{DO}. @code{DO} always enters
 5254: the loop, independent of the loop parameters. Do not use @code{DO}, even
 5255: if you know that the loop is entered in any case. Such knowledge tends
 5256: to become invalid during maintenance of a program, and then the
 5257: @code{DO} will make trouble.
 5258: 
 5259: @item
 5260: @code{LOOP} can be replaced with @code{@i{n} +LOOP}; this updates the
 5261: index by @i{n} instead of by 1. The loop is terminated when the border
 5262: between @i{limit-1} and @i{limit} is crossed. E.g.:
 5263: 
 5264: @example
 5265: 4 0 +DO  i .  2 +LOOP
 5266: @end example
 5267: @noindent
 5268: prints @code{0 2}
 5269: 
 5270: @example
 5271: 4 1 +DO  i .  2 +LOOP
 5272: @end example
 5273: @noindent
 5274: prints @code{1 3}
 5275: 
 5276: @item
 5277: @cindex negative increment for counted loops
 5278: @cindex counted loops with negative increment
 5279: The behaviour of @code{@i{n} +LOOP} is peculiar when @i{n} is negative:
 5280: 
 5281: @example
 5282: -1 0 ?DO  i .  -1 +LOOP
 5283: @end example
 5284: @noindent
 5285: prints @code{0 -1}
 5286: 
 5287: @example
 5288: 0 0 ?DO  i .  -1 +LOOP
 5289: @end example
 5290: prints nothing.
 5291: 
 5292: Therefore we recommend avoiding @code{@i{n} +LOOP} with negative
 5293: @i{n}. One alternative is @code{@i{u} -LOOP}, which reduces the
 5294: index by @i{u} each iteration. The loop is terminated when the border
 5295: between @i{limit+1} and @i{limit} is crossed. Gforth also provides
 5296: @code{-DO} and @code{U-DO} for down-counting loops. E.g.:
 5297: 
 5298: @example
 5299: -2 0 -DO  i .  1 -LOOP
 5300: @end example
 5301: @noindent
 5302: prints @code{0 -1}
 5303: 
 5304: @example
 5305: -1 0 -DO  i .  1 -LOOP
 5306: @end example
 5307: @noindent
 5308: prints @code{0}
 5309: 
 5310: @example
 5311: 0 0 -DO  i .  1 -LOOP
 5312: @end example
 5313: @noindent
 5314: prints nothing.
 5315: 
 5316: @end itemize
 5317: 
 5318: Unfortunately, @code{+DO}, @code{U+DO}, @code{-DO}, @code{U-DO} and
 5319: @code{-LOOP} are not defined in ANS Forth. However, an implementation
 5320: for these words that uses only standard words is provided in
 5321: @file{compat/loops.fs}.
 5322: 
 5323: 
 5324: @cindex @code{FOR} loops
 5325: Another counted loop is:
 5326: @example
 5327: @i{n}
 5328: FOR
 5329:   @i{body}
 5330: NEXT
 5331: @end example
 5332: This is the preferred loop of native code compiler writers who are too
 5333: lazy to optimize @code{?DO} loops properly. This loop structure is not
 5334: defined in ANS Forth. In Gforth, this loop iterates @i{n+1} times;
 5335: @code{i} produces values starting with @i{n} and ending with 0. Other
 5336: Forth systems may behave differently, even if they support @code{FOR}
 5337: loops. To avoid problems, don't use @code{FOR} loops.
 5338: 
 5339: @node Arbitrary control structures, Calls and returns, Counted Loops, Control Structures
 5340: @subsection Arbitrary control structures
 5341: @cindex control structures, user-defined
 5342: 
 5343: @cindex control-flow stack
 5344: ANS Forth permits and supports using control structures in a non-nested
 5345: way. Information about incomplete control structures is stored on the
 5346: control-flow stack. This stack may be implemented on the Forth data
 5347: stack, and this is what we have done in Gforth.
 5348: 
 5349: @cindex @code{orig}, control-flow stack item
 5350: @cindex @code{dest}, control-flow stack item
 5351: An @i{orig} entry represents an unresolved forward branch, a @i{dest}
 5352: entry represents a backward branch target. A few words are the basis for
 5353: building any control structure possible (except control structures that
 5354: need storage, like calls, coroutines, and backtracking).
 5355: 
 5356: 
 5357: doc-if
 5358: doc-ahead
 5359: doc-then
 5360: doc-begin
 5361: doc-until
 5362: doc-again
 5363: doc-cs-pick
 5364: doc-cs-roll
 5365: 
 5366: 
 5367: The Standard words @code{CS-PICK} and @code{CS-ROLL} allow you to
 5368: manipulate the control-flow stack in a portable way. Without them, you
 5369: would need to know how many stack items are occupied by a control-flow
 5370: entry (many systems use one cell. In Gforth they currently take three,
 5371: but this may change in the future).
 5372: 
 5373: Some standard control structure words are built from these words:
 5374: 
 5375: 
 5376: doc-else
 5377: doc-while
 5378: doc-repeat
 5379: 
 5380: 
 5381: @noindent
 5382: Gforth adds some more control-structure words:
 5383: 
 5384: 
 5385: doc-endif
 5386: doc-?dup-if
 5387: doc-?dup-0=-if
 5388: 
 5389: 
 5390: @noindent
 5391: Counted loop words constitute a separate group of words:
 5392: 
 5393: 
 5394: doc-?do
 5395: doc-+do
 5396: doc-u+do
 5397: doc--do
 5398: doc-u-do
 5399: doc-do
 5400: doc-for
 5401: doc-loop
 5402: doc-+loop
 5403: doc--loop
 5404: doc-next
 5405: doc-leave
 5406: doc-?leave
 5407: doc-unloop
 5408: doc-done
 5409: 
 5410: 
 5411: The standard does not allow using @code{CS-PICK} and @code{CS-ROLL} on
 5412: @i{do-sys}. Gforth allows it, but it's your job to ensure that for
 5413: every @code{?DO} etc. there is exactly one @code{UNLOOP} on any path
 5414: through the definition (@code{LOOP} etc. compile an @code{UNLOOP} on the
 5415: fall-through path). Also, you have to ensure that all @code{LEAVE}s are
 5416: resolved (by using one of the loop-ending words or @code{DONE}).
 5417: 
 5418: @noindent
 5419: Another group of control structure words are:
 5420: 
 5421: 
 5422: doc-case
 5423: doc-endcase
 5424: doc-of
 5425: doc-endof
 5426: 
 5427: 
 5428: @i{case-sys} and @i{of-sys} cannot be processed using @code{CS-PICK} and
 5429: @code{CS-ROLL}.
 5430: 
 5431: @subsubsection Programming Style
 5432: @cindex control structures programming style
 5433: @cindex programming style, arbitrary control structures
 5434: 
 5435: In order to ensure readability we recommend that you do not create
 5436: arbitrary control structures directly, but define new control structure
 5437: words for the control structure you want and use these words in your
 5438: program. For example, instead of writing:
 5439: 
 5440: @example
 5441: BEGIN
 5442:   ...
 5443: IF [ 1 CS-ROLL ]
 5444:   ...
 5445: AGAIN THEN
 5446: @end example
 5447: 
 5448: @noindent
 5449: we recommend defining control structure words, e.g.,
 5450: 
 5451: @example
 5452: : WHILE ( DEST -- ORIG DEST )
 5453:  POSTPONE IF
 5454:  1 CS-ROLL ; immediate
 5455: 
 5456: : REPEAT ( orig dest -- )
 5457:  POSTPONE AGAIN
 5458:  POSTPONE THEN ; immediate
 5459: @end example
 5460: 
 5461: @noindent
 5462: and then using these to create the control structure:
 5463: 
 5464: @example
 5465: BEGIN
 5466:   ...
 5467: WHILE
 5468:   ...
 5469: REPEAT
 5470: @end example
 5471: 
 5472: That's much easier to read, isn't it? Of course, @code{REPEAT} and
 5473: @code{WHILE} are predefined, so in this example it would not be
 5474: necessary to define them.
 5475: 
 5476: @node Calls and returns, Exception Handling, Arbitrary control structures, Control Structures
 5477: @subsection Calls and returns
 5478: @cindex calling a definition
 5479: @cindex returning from a definition
 5480: 
 5481: @cindex recursive definitions
 5482: A definition can be called simply be writing the name of the definition
 5483: to be called. Normally a definition is invisible during its own
 5484: definition. If you want to write a directly recursive definition, you
 5485: can use @code{recursive} to make the current definition visible, or
 5486: @code{recurse} to call the current definition directly.
 5487: 
 5488: 
 5489: doc-recursive
 5490: doc-recurse
 5491: 
 5492: 
 5493: @comment TODO add example of the two recursion methods
 5494: @quotation
 5495: @progstyle
 5496: I prefer using @code{recursive} to @code{recurse}, because calling the
 5497: definition by name is more descriptive (if the name is well-chosen) than
 5498: the somewhat cryptic @code{recurse}.  E.g., in a quicksort
 5499: implementation, it is much better to read (and think) ``now sort the
 5500: partitions'' than to read ``now do a recursive call''.
 5501: @end quotation
 5502: 
 5503: For mutual recursion, use @code{Defer}red words, like this:
 5504: 
 5505: @example
 5506: Defer foo
 5507: 
 5508: : bar ( ... -- ... )
 5509:  ... foo ... ;
 5510: 
 5511: :noname ( ... -- ... )
 5512:  ... bar ... ;
 5513: IS foo
 5514: @end example
 5515: 
 5516: Deferred words are discussed in more detail in @ref{Deferred words}.
 5517: 
 5518: The current definition returns control to the calling definition when
 5519: the end of the definition is reached or @code{EXIT} is encountered.
 5520: 
 5521: doc-exit
 5522: doc-;s
 5523: 
 5524: 
 5525: @node Exception Handling,  , Calls and returns, Control Structures
 5526: @subsection Exception Handling
 5527: @cindex exceptions
 5528: 
 5529: @c quit is a very bad idea for error handling, 
 5530: @c because it does not translate into a THROW
 5531: @c it also does not belong into this chapter
 5532: 
 5533: If a word detects an error condition that it cannot handle, it can
 5534: @code{throw} an exception.  In the simplest case, this will terminate
 5535: your program, and report an appropriate error.
 5536: 
 5537: doc-throw
 5538: 
 5539: @code{Throw} consumes a cell-sized error number on the stack. There are
 5540: some predefined error numbers in ANS Forth (see @file{errors.fs}).  In
 5541: Gforth (and most other systems) you can use the iors produced by various
 5542: words as error numbers (e.g., a typical use of @code{allocate} is
 5543: @code{allocate throw}).  Gforth also provides the word @code{exception}
 5544: to define your own error numbers (with decent error reporting); an ANS
 5545: Forth version of this word (but without the error messages) is available
 5546: in @code{compat/except.fs}.  And finally, you can use your own error
 5547: numbers (anything outside the range -4095..0), but won't get nice error
 5548: messages, only numbers.  For example, try:
 5549: 
 5550: @example
 5551: -10 throw                    \ ANS defined
 5552: -267 throw                   \ system defined
 5553: s" my error" exception throw \ user defined
 5554: 7 throw                      \ arbitrary number
 5555: @end example
 5556: 
 5557: doc---exception-exception
 5558: 
 5559: A common idiom to @code{THROW} a specific error if a flag is true is
 5560: this:
 5561: 
 5562: @example
 5563: @code{( flag ) 0<> @i{errno} and throw}
 5564: @end example
 5565: 
 5566: Your program can provide exception handlers to catch exceptions.  An
 5567: exception handler can be used to correct the problem, or to clean up
 5568: some data structures and just throw the exception to the next exception
 5569: handler.  Note that @code{throw} jumps to the dynamically innermost
 5570: exception handler.  The system's exception handler is outermost, and just
 5571: prints an error and restarts command-line interpretation (or, in batch
 5572: mode (i.e., while processing the shell command line), leaves Gforth).
 5573: 
 5574: The ANS Forth way to catch exceptions is @code{catch}:
 5575: 
 5576: doc-catch
 5577: 
 5578: The most common use of exception handlers is to clean up the state when
 5579: an error happens.  E.g.,
 5580: 
 5581: @example
 5582: base @ >r hex \ actually the hex should be inside foo, or we h
 5583: ['] foo catch ( nerror|0 )
 5584: r> base !
 5585: ( nerror|0 ) throw \ pass it on
 5586: @end example
 5587: 
 5588: A use of @code{catch} for handling the error @code{myerror} might look
 5589: like this:
 5590: 
 5591: @example
 5592: ['] foo catch
 5593: CASE
 5594:   myerror OF ... ( do something about it ) ENDOF
 5595:   dup throw \ default: pass other errors on, do nothing on non-errors
 5596: ENDCASE
 5597: @end example
 5598: 
 5599: Having to wrap the code into a separate word is often cumbersome,
 5600: therefore Gforth provides an alternative syntax:
 5601: 
 5602: @example
 5603: TRY
 5604:   @i{code1}
 5605: RECOVER     \ optional
 5606:   @i{code2} \ optional
 5607: ENDTRY
 5608: @end example
 5609: 
 5610: This performs @i{Code1}.  If @i{code1} completes normally, execution
 5611: continues after the @code{endtry}.  If @i{Code1} throws, the stacks are
 5612: reset to the state during @code{try}, the throw value is pushed on the
 5613: data stack, and execution constinues at @i{code2}, and finally falls
 5614: through the @code{endtry} into the following code.
 5615: 
 5616: doc-try
 5617: doc-recover
 5618: doc-endtry
 5619: 
 5620: The cleanup example from above in this syntax:
 5621: 
 5622: @example
 5623: base @ >r TRY
 5624:   hex foo \ now the hex is placed correctly
 5625:   0       \ value for throw
 5626: RECOVER ENDTRY
 5627: r> base ! throw
 5628: @end example
 5629: 
 5630: And here's the error handling example:
 5631: 
 5632: @example
 5633: TRY
 5634:   foo
 5635: RECOVER
 5636:   CASE
 5637:     myerror OF ... ( do something about it ) ENDOF
 5638:     throw \ pass other errors on
 5639:   ENDCASE
 5640: ENDTRY
 5641: @end example
 5642: 
 5643: @progstyle
 5644: As usual, you should ensure that the stack depth is statically known at
 5645: the end: either after the @code{throw} for passing on errors, or after
 5646: the @code{ENDTRY} (or, if you use @code{catch}, after the end of the
 5647: selection construct for handling the error).
 5648: 
 5649: There are two alternatives to @code{throw}: @code{Abort"} is conditional
 5650: and you can provide an error message.  @code{Abort} just produces an
 5651: ``Aborted'' error.
 5652: 
 5653: The problem with these words is that exception handlers cannot
 5654: differentiate between different @code{abort"}s; they just look like
 5655: @code{-2 throw} to them (the error message cannot be accessed by
 5656: standard programs).  Similar @code{abort} looks like @code{-1 throw} to
 5657: exception handlers.
 5658: 
 5659: doc-abort"
 5660: doc-abort
 5661: 
 5662: 
 5663: 
 5664: @c -------------------------------------------------------------
 5665: @node Defining Words, Interpretation and Compilation Semantics, Control Structures, Words
 5666: @section Defining Words
 5667: @cindex defining words
 5668: 
 5669: Defining words are used to extend Forth by creating new entries in the dictionary.
 5670: 
 5671: @menu
 5672: * CREATE::                      
 5673: * Variables::                   Variables and user variables
 5674: * Constants::                   
 5675: * Values::                      Initialised variables
 5676: * Colon Definitions::           
 5677: * Anonymous Definitions::       Definitions without names
 5678: * Supplying names::             Passing definition names as strings
 5679: * User-defined Defining Words::  
 5680: * Deferred words::              Allow forward references
 5681: * Aliases::                     
 5682: @end menu
 5683: 
 5684: @node CREATE, Variables, Defining Words, Defining Words
 5685: @subsection @code{CREATE}
 5686: @cindex simple defining words
 5687: @cindex defining words, simple
 5688: 
 5689: Defining words are used to create new entries in the dictionary. The
 5690: simplest defining word is @code{CREATE}. @code{CREATE} is used like
 5691: this:
 5692: 
 5693: @example
 5694: CREATE new-word1
 5695: @end example
 5696: 
 5697: @code{CREATE} is a parsing word, i.e., it takes an argument from the
 5698: input stream (@code{new-word1} in our example).  It generates a
 5699: dictionary entry for @code{new-word1}. When @code{new-word1} is
 5700: executed, all that it does is leave an address on the stack. The address
 5701: represents the value of the data space pointer (@code{HERE}) at the time
 5702: that @code{new-word1} was defined. Therefore, @code{CREATE} is a way of
 5703: associating a name with the address of a region of memory.
 5704: 
 5705: doc-create
 5706: 
 5707: Note that in ANS Forth guarantees only for @code{create} that its body
 5708: is in dictionary data space (i.e., where @code{here}, @code{allot}
 5709: etc. work, @pxref{Dictionary allocation}).  Also, in ANS Forth only
 5710: @code{create}d words can be modified with @code{does>}
 5711: (@pxref{User-defined Defining Words}).  And in ANS Forth @code{>body}
 5712: can only be applied to @code{create}d words.
 5713: 
 5714: By extending this example to reserve some memory in data space, we end
 5715: up with something like a @i{variable}. Here are two different ways to do
 5716: it:
 5717: 
 5718: @example
 5719: CREATE new-word2 1 cells allot  \ reserve 1 cell - initial value undefined
 5720: CREATE new-word3 4 ,            \ reserve 1 cell and initialise it (to 4)
 5721: @end example
 5722: 
 5723: The variable can be examined and modified using @code{@@} (``fetch'') and
 5724: @code{!} (``store'') like this:
 5725: 
 5726: @example
 5727: new-word2 @@ .      \ get address, fetch from it and display
 5728: 1234 new-word2 !   \ new value, get address, store to it
 5729: @end example
 5730: 
 5731: @cindex arrays
 5732: A similar mechanism can be used to create arrays. For example, an
 5733: 80-character text input buffer:
 5734: 
 5735: @example
 5736: CREATE text-buf 80 chars allot
 5737: 
 5738: text-buf 0 chars c@@ \ the 1st character (offset 0)
 5739: text-buf 3 chars c@@ \ the 4th character (offset 3)
 5740: @end example
 5741: 
 5742: You can build arbitrarily complex data structures by allocating
 5743: appropriate areas of memory. For further discussions of this, and to
 5744: learn about some Gforth tools that make it easier,
 5745: @xref{Structures}.
 5746: 
 5747: 
 5748: @node Variables, Constants, CREATE, Defining Words
 5749: @subsection Variables
 5750: @cindex variables
 5751: 
 5752: The previous section showed how a sequence of commands could be used to
 5753: generate a variable.  As a final refinement, the whole code sequence can
 5754: be wrapped up in a defining word (pre-empting the subject of the next
 5755: section), making it easier to create new variables:
 5756: 
 5757: @example
 5758: : myvariableX ( "name" -- a-addr ) CREATE 1 cells allot ;
 5759: : myvariable0 ( "name" -- a-addr ) CREATE 0 , ;
 5760: 
 5761: myvariableX foo \ variable foo starts off with an unknown value
 5762: myvariable0 joe \ whilst joe is initialised to 0
 5763: 
 5764: 45 3 * foo !   \ set foo to 135
 5765: 1234 joe !     \ set joe to 1234
 5766: 3 joe +!       \ increment joe by 3.. to 1237
 5767: @end example
 5768: 
 5769: Not surprisingly, there is no need to define @code{myvariable}, since
 5770: Forth already has a definition @code{Variable}. ANS Forth does not
 5771: guarantee that a @code{Variable} is initialised when it is created
 5772: (i.e., it may behave like @code{myvariableX}). In contrast, Gforth's
 5773: @code{Variable} initialises the variable to 0 (i.e., it behaves exactly
 5774: like @code{myvariable0}). Forth also provides @code{2Variable} and
 5775: @code{fvariable} for double and floating-point variables, respectively
 5776: -- they are initialised to 0. and 0e in Gforth. If you use a @code{Variable} to
 5777: store a boolean, you can use @code{on} and @code{off} to toggle its
 5778: state.
 5779: 
 5780: doc-variable
 5781: doc-2variable
 5782: doc-fvariable
 5783: 
 5784: @cindex user variables
 5785: @cindex user space
 5786: The defining word @code{User} behaves in the same way as @code{Variable}.
 5787: The difference is that it reserves space in @i{user (data) space} rather
 5788: than normal data space. In a Forth system that has a multi-tasker, each
 5789: task has its own set of user variables.
 5790: 
 5791: doc-user
 5792: @c doc-udp
 5793: @c doc-uallot
 5794: 
 5795: @comment TODO is that stuff about user variables strictly correct? Is it
 5796: @comment just terminal tasks that have user variables?
 5797: @comment should document tasker.fs (with some examples) elsewhere
 5798: @comment in this manual, then expand on user space and user variables.
 5799: 
 5800: @node Constants, Values, Variables, Defining Words
 5801: @subsection Constants
 5802: @cindex constants
 5803: 
 5804: @code{Constant} allows you to declare a fixed value and refer to it by
 5805: name. For example:
 5806: 
 5807: @example
 5808: 12 Constant INCHES-PER-FOOT
 5809: 3E+08 fconstant SPEED-O-LIGHT
 5810: @end example
 5811: 
 5812: A @code{Variable} can be both read and written, so its run-time
 5813: behaviour is to supply an address through which its current value can be
 5814: manipulated. In contrast, the value of a @code{Constant} cannot be
 5815: changed once it has been declared@footnote{Well, often it can be -- but
 5816: not in a Standard, portable way. It's safer to use a @code{Value} (read
 5817: on).} so it's not necessary to supply the address -- it is more
 5818: efficient to return the value of the constant directly. That's exactly
 5819: what happens; the run-time effect of a constant is to put its value on
 5820: the top of the stack (You can find one
 5821: way of implementing @code{Constant} in @ref{User-defined Defining Words}).
 5822: 
 5823: Forth also provides @code{2Constant} and @code{fconstant} for defining
 5824: double and floating-point constants, respectively.
 5825: 
 5826: doc-constant
 5827: doc-2constant
 5828: doc-fconstant
 5829: 
 5830: @c that's too deep, and it's not necessarily true for all ANS Forths. - anton
 5831: @c nac-> How could that not be true in an ANS Forth? You can't define a
 5832: @c constant, use it and then delete the definition of the constant..
 5833: 
 5834: @c anton->An ANS Forth system can compile a constant to a literal; On
 5835: @c decompilation you would see only the number, just as if it had been used
 5836: @c in the first place.  The word will stay, of course, but it will only be
 5837: @c used by the text interpreter (no run-time duties, except when it is 
 5838: @c POSTPONEd or somesuch).
 5839: 
 5840: @c nac:
 5841: @c I agree that it's rather deep, but IMO it is an important difference
 5842: @c relative to other programming languages.. often it's annoying: it
 5843: @c certainly changes my programming style relative to C.
 5844: 
 5845: @c anton: In what way?
 5846: 
 5847: Constants in Forth behave differently from their equivalents in other
 5848: programming languages. In other languages, a constant (such as an EQU in
 5849: assembler or a #define in C) only exists at compile-time; in the
 5850: executable program the constant has been translated into an absolute
 5851: number and, unless you are using a symbolic debugger, it's impossible to
 5852: know what abstract thing that number represents. In Forth a constant has
 5853: an entry in the header space and remains there after the code that uses
 5854: it has been defined. In fact, it must remain in the dictionary since it
 5855: has run-time duties to perform. For example:
 5856: 
 5857: @example
 5858: 12 Constant INCHES-PER-FOOT
 5859: : FEET-TO-INCHES ( n1 -- n2 ) INCHES-PER-FOOT * ;
 5860: @end example
 5861: 
 5862: @cindex in-lining of constants
 5863: When @code{FEET-TO-INCHES} is executed, it will in turn execute the xt
 5864: associated with the constant @code{INCHES-PER-FOOT}. If you use
 5865: @code{see} to decompile the definition of @code{FEET-TO-INCHES}, you can
 5866: see that it makes a call to @code{INCHES-PER-FOOT}. Some Forth compilers
 5867: attempt to optimise constants by in-lining them where they are used. You
 5868: can force Gforth to in-line a constant like this:
 5869: 
 5870: @example
 5871: : FEET-TO-INCHES ( n1 -- n2 ) [ INCHES-PER-FOOT ] LITERAL * ;
 5872: @end example
 5873: 
 5874: If you use @code{see} to decompile @i{this} version of
 5875: @code{FEET-TO-INCHES}, you can see that @code{INCHES-PER-FOOT} is no
 5876: longer present. To understand how this works, read
 5877: @ref{Interpret/Compile states}, and @ref{Literals}.
 5878: 
 5879: In-lining constants in this way might improve execution time
 5880: fractionally, and can ensure that a constant is now only referenced at
 5881: compile-time. However, the definition of the constant still remains in
 5882: the dictionary. Some Forth compilers provide a mechanism for controlling
 5883: a second dictionary for holding transient words such that this second
 5884: dictionary can be deleted later in order to recover memory
 5885: space. However, there is no standard way of doing this.
 5886: 
 5887: 
 5888: @node Values, Colon Definitions, Constants, Defining Words
 5889: @subsection Values
 5890: @cindex values
 5891: 
 5892: A @code{Value} behaves like a @code{Constant}, but it can be changed.
 5893: @code{TO} is a parsing word that changes a @code{Values}.  In Gforth
 5894: (not in ANS Forth) you can access (and change) a @code{value} also with
 5895: @code{>body}.
 5896: 
 5897: Here are some
 5898: examples:
 5899: 
 5900: @example
 5901: 12 Value APPLES     \ Define APPLES with an initial value of 12
 5902: 34 TO APPLES        \ Change the value of APPLES. TO is a parsing word
 5903: 1 ' APPLES >body +! \ Increment APPLES.  Non-standard usage.
 5904: APPLES              \ puts 35 on the top of the stack.
 5905: @end example
 5906: 
 5907: doc-value
 5908: doc-to
 5909: 
 5910: 
 5911: 
 5912: @node Colon Definitions, Anonymous Definitions, Values, Defining Words
 5913: @subsection Colon Definitions
 5914: @cindex colon definitions
 5915: 
 5916: @example
 5917: : name ( ... -- ... )
 5918:     word1 word2 word3 ;
 5919: @end example
 5920: 
 5921: @noindent
 5922: Creates a word called @code{name} that, upon execution, executes
 5923: @code{word1 word2 word3}. @code{name} is a @dfn{(colon) definition}.
 5924: 
 5925: The explanation above is somewhat superficial. For simple examples of
 5926: colon definitions see @ref{Your first definition}.  For an in-depth
 5927: discussion of some of the issues involved, @xref{Interpretation and
 5928: Compilation Semantics}.
 5929: 
 5930: doc-:
 5931: doc-;
 5932: 
 5933: 
 5934: @node Anonymous Definitions, Supplying names, Colon Definitions, Defining Words
 5935: @subsection Anonymous Definitions
 5936: @cindex colon definitions
 5937: @cindex defining words without name
 5938: 
 5939: Sometimes you want to define an @dfn{anonymous word}; a word without a
 5940: name. You can do this with:
 5941: 
 5942: doc-:noname
 5943: 
 5944: This leaves the execution token for the word on the stack after the
 5945: closing @code{;}. Here's an example in which a deferred word is
 5946: initialised with an @code{xt} from an anonymous colon definition:
 5947: 
 5948: @example
 5949: Defer deferred
 5950: :noname ( ... -- ... )
 5951:   ... ;
 5952: IS deferred
 5953: @end example
 5954: 
 5955: @noindent
 5956: Gforth provides an alternative way of doing this, using two separate
 5957: words:
 5958: 
 5959: doc-noname
 5960: @cindex execution token of last defined word
 5961: doc-lastxt
 5962: 
 5963: @noindent
 5964: The previous example can be rewritten using @code{noname} and
 5965: @code{lastxt}:
 5966: 
 5967: @example
 5968: Defer deferred
 5969: noname : ( ... -- ... )
 5970:   ... ;
 5971: lastxt IS deferred
 5972: @end example
 5973: 
 5974: @noindent
 5975: @code{noname} works with any defining word, not just @code{:}.
 5976: 
 5977: @code{lastxt} also works when the last word was not defined as
 5978: @code{noname}.  It does not work for combined words, though.  It also has
 5979: the useful property that is is valid as soon as the header for a
 5980: definition has been built. Thus:
 5981: 
 5982: @example
 5983: lastxt . : foo [ lastxt . ] ; ' foo .
 5984: @end example
 5985: 
 5986: @noindent
 5987: prints 3 numbers; the last two are the same.
 5988: 
 5989: @node Supplying names, User-defined Defining Words, Anonymous Definitions, Defining Words
 5990: @subsection Supplying the name of a defined word
 5991: @cindex names for defined words
 5992: @cindex defining words, name given in a string
 5993: 
 5994: By default, a defining word takes the name for the defined word from the
 5995: input stream. Sometimes you want to supply the name from a string. You
 5996: can do this with:
 5997: 
 5998: doc-nextname
 5999: 
 6000: For example:
 6001: 
 6002: @example
 6003: s" foo" nextname create
 6004: @end example
 6005: 
 6006: @noindent
 6007: is equivalent to:
 6008: 
 6009: @example
 6010: create foo
 6011: @end example
 6012: 
 6013: @noindent
 6014: @code{nextname} works with any defining word.
 6015: 
 6016: 
 6017: @node User-defined Defining Words, Deferred words, Supplying names, Defining Words
 6018: @subsection User-defined Defining Words
 6019: @cindex user-defined defining words
 6020: @cindex defining words, user-defined
 6021: 
 6022: You can create a new defining word by wrapping defining-time code around
 6023: an existing defining word and putting the sequence in a colon
 6024: definition. 
 6025: 
 6026: @c anton: This example is very complex and leads in a quite different
 6027: @c direction from the CREATE-DOES> stuff that follows.  It should probably
 6028: @c be done elsewhere, or as a subsubsection of this subsection (or as a
 6029: @c subsection of Defining Words)
 6030: 
 6031: For example, suppose that you have a word @code{stats} that
 6032: gathers statistics about colon definitions given the @i{xt} of the
 6033: definition, and you want every colon definition in your application to
 6034: make a call to @code{stats}. You can define and use a new version of
 6035: @code{:} like this:
 6036: 
 6037: @example
 6038: : stats ( xt -- ) DUP ." (Gathering statistics for " . ." )"
 6039:   ... ;  \ other code
 6040: 
 6041: : my: : lastxt postpone literal ['] stats compile, ;
 6042: 
 6043: my: foo + - ;
 6044: @end example
 6045: 
 6046: When @code{foo} is defined using @code{my:} these steps occur:
 6047: 
 6048: @itemize @bullet
 6049: @item
 6050: @code{my:} is executed.
 6051: @item
 6052: The @code{:} within the definition (the one between @code{my:} and
 6053: @code{lastxt}) is executed, and does just what it always does; it parses
 6054: the input stream for a name, builds a dictionary header for the name
 6055: @code{foo} and switches @code{state} from interpret to compile.
 6056: @item
 6057: The word @code{lastxt} is executed. It puts the @i{xt} for the word that is
 6058: being defined -- @code{foo} -- onto the stack.
 6059: @item
 6060: The code that was produced by @code{postpone literal} is executed; this
 6061: causes the value on the stack to be compiled as a literal in the code
 6062: area of @code{foo}.
 6063: @item
 6064: The code @code{['] stats} compiles a literal into the definition of
 6065: @code{my:}. When @code{compile,} is executed, that literal -- the
 6066: execution token for @code{stats} -- is layed down in the code area of
 6067: @code{foo} , following the literal@footnote{Strictly speaking, the
 6068: mechanism that @code{compile,} uses to convert an @i{xt} into something
 6069: in the code area is implementation-dependent. A threaded implementation
 6070: might spit out the execution token directly whilst another
 6071: implementation might spit out a native code sequence.}.
 6072: @item
 6073: At this point, the execution of @code{my:} is complete, and control
 6074: returns to the text interpreter. The text interpreter is in compile
 6075: state, so subsequent text @code{+ -} is compiled into the definition of
 6076: @code{foo} and the @code{;} terminates the definition as always.
 6077: @end itemize
 6078: 
 6079: You can use @code{see} to decompile a word that was defined using
 6080: @code{my:} and see how it is different from a normal @code{:}
 6081: definition. For example:
 6082: 
 6083: @example
 6084: : bar + - ;  \ like foo but using : rather than my:
 6085: see bar
 6086: : bar
 6087:   + - ;
 6088: see foo
 6089: : foo
 6090:   107645672 stats + - ;
 6091: 
 6092: \ use ' stats . to show that 107645672 is the xt for stats
 6093: @end example
 6094: 
 6095: You can use techniques like this to make new defining words in terms of
 6096: @i{any} existing defining word.
 6097: 
 6098: 
 6099: @cindex defining defining words
 6100: @cindex @code{CREATE} ... @code{DOES>}
 6101: If you want the words defined with your defining words to behave
 6102: differently from words defined with standard defining words, you can
 6103: write your defining word like this:
 6104: 
 6105: @example
 6106: : def-word ( "name" -- )
 6107:     CREATE @i{code1}
 6108: DOES> ( ... -- ... )
 6109:     @i{code2} ;
 6110: 
 6111: def-word name
 6112: @end example
 6113: 
 6114: @cindex child words
 6115: This fragment defines a @dfn{defining word} @code{def-word} and then
 6116: executes it.  When @code{def-word} executes, it @code{CREATE}s a new
 6117: word, @code{name}, and executes the code @i{code1}. The code @i{code2}
 6118: is not executed at this time. The word @code{name} is sometimes called a
 6119: @dfn{child} of @code{def-word}.
 6120: 
 6121: When you execute @code{name}, the address of the body of @code{name} is
 6122: put on the data stack and @i{code2} is executed (the address of the body
 6123: of @code{name} is the address @code{HERE} returns immediately after the
 6124: @code{CREATE}, i.e., the address a @code{create}d word returns by
 6125: default).
 6126: 
 6127: @c anton:
 6128: @c www.dictionary.com says:
 6129: @c at·a·vism: 1.The reappearance of a characteristic in an organism after
 6130: @c several generations of absence, usually caused by the chance
 6131: @c recombination of genes.  2.An individual or a part that exhibits
 6132: @c atavism. Also called throwback.  3.The return of a trait or recurrence
 6133: @c of previous behavior after a period of absence.
 6134: @c
 6135: @c Doesn't seem to fit.
 6136: 
 6137: @c @cindex atavism in child words
 6138: You can use @code{def-word} to define a set of child words that behave
 6139: similarly; they all have a common run-time behaviour determined by
 6140: @i{code2}. Typically, the @i{code1} sequence builds a data area in the
 6141: body of the child word. The structure of the data is common to all
 6142: children of @code{def-word}, but the data values are specific -- and
 6143: private -- to each child word. When a child word is executed, the
 6144: address of its private data area is passed as a parameter on TOS to be
 6145: used and manipulated@footnote{It is legitimate both to read and write to
 6146: this data area.} by @i{code2}.
 6147: 
 6148: The two fragments of code that make up the defining words act (are
 6149: executed) at two completely separate times:
 6150: 
 6151: @itemize @bullet
 6152: @item
 6153: At @i{define time}, the defining word executes @i{code1} to generate a
 6154: child word
 6155: @item
 6156: At @i{child execution time}, when a child word is invoked, @i{code2}
 6157: is executed, using parameters (data) that are private and specific to
 6158: the child word.
 6159: @end itemize
 6160: 
 6161: Another way of understanding the behaviour of @code{def-word} and
 6162: @code{name} is to say that, if you make the following definitions:
 6163: @example
 6164: : def-word1 ( "name" -- )
 6165:     CREATE @i{code1} ;
 6166: 
 6167: : action1 ( ... -- ... )
 6168:     @i{code2} ;
 6169: 
 6170: def-word1 name1
 6171: @end example
 6172: 
 6173: @noindent
 6174: Then using @code{name1 action1} is equivalent to using @code{name}.
 6175: 
 6176: The classic example is that you can define @code{CONSTANT} in this way:
 6177: 
 6178: @example
 6179: : CONSTANT ( w "name" -- )
 6180:     CREATE ,
 6181: DOES> ( -- w )
 6182:     @@ ;
 6183: @end example
 6184: 
 6185: @comment There is a beautiful description of how this works and what
 6186: @comment it does in the Forthwrite 100th edition.. as well as an elegant
 6187: @comment commentary on the Counting Fruits problem.
 6188: 
 6189: When you create a constant with @code{5 CONSTANT five}, a set of
 6190: define-time actions take place; first a new word @code{five} is created,
 6191: then the value 5 is laid down in the body of @code{five} with
 6192: @code{,}. When @code{five} is executed, the address of the body is put on
 6193: the stack, and @code{@@} retrieves the value 5. The word @code{five} has
 6194: no code of its own; it simply contains a data field and a pointer to the
 6195: code that follows @code{DOES>} in its defining word. That makes words
 6196: created in this way very compact.
 6197: 
 6198: The final example in this section is intended to remind you that space
 6199: reserved in @code{CREATE}d words is @i{data} space and therefore can be
 6200: both read and written by a Standard program@footnote{Exercise: use this
 6201: example as a starting point for your own implementation of @code{Value}
 6202: and @code{TO} -- if you get stuck, investigate the behaviour of @code{'} and
 6203: @code{[']}.}:
 6204: 
 6205: @example
 6206: : foo ( "name" -- )
 6207:     CREATE -1 ,
 6208: DOES> ( -- )
 6209:     @@ . ;
 6210: 
 6211: foo first-word
 6212: foo second-word
 6213: 
 6214: 123 ' first-word >BODY !
 6215: @end example
 6216: 
 6217: If @code{first-word} had been a @code{CREATE}d word, we could simply
 6218: have executed it to get the address of its data field. However, since it
 6219: was defined to have @code{DOES>} actions, its execution semantics are to
 6220: perform those @code{DOES>} actions. To get the address of its data field
 6221: it's necessary to use @code{'} to get its xt, then @code{>BODY} to
 6222: translate the xt into the address of the data field.  When you execute
 6223: @code{first-word}, it will display @code{123}. When you execute
 6224: @code{second-word} it will display @code{-1}.
 6225: 
 6226: @cindex stack effect of @code{DOES>}-parts
 6227: @cindex @code{DOES>}-parts, stack effect
 6228: In the examples above the stack comment after the @code{DOES>} specifies
 6229: the stack effect of the defined words, not the stack effect of the
 6230: following code (the following code expects the address of the body on
 6231: the top of stack, which is not reflected in the stack comment). This is
 6232: the convention that I use and recommend (it clashes a bit with using
 6233: locals declarations for stack effect specification, though).
 6234: 
 6235: @menu
 6236: * CREATE..DOES> applications::  
 6237: * CREATE..DOES> details::       
 6238: * Advanced does> usage example::  
 6239: * @code{Const-does>}::          
 6240: @end menu
 6241: 
 6242: @node CREATE..DOES> applications, CREATE..DOES> details, User-defined Defining Words, User-defined Defining Words
 6243: @subsubsection Applications of @code{CREATE..DOES>}
 6244: @cindex @code{CREATE} ... @code{DOES>}, applications
 6245: 
 6246: You may wonder how to use this feature. Here are some usage patterns:
 6247: 
 6248: @cindex factoring similar colon definitions
 6249: When you see a sequence of code occurring several times, and you can
 6250: identify a meaning, you will factor it out as a colon definition. When
 6251: you see similar colon definitions, you can factor them using
 6252: @code{CREATE..DOES>}. E.g., an assembler usually defines several words
 6253: that look very similar:
 6254: @example
 6255: : ori, ( reg-target reg-source n -- )
 6256:     0 asm-reg-reg-imm ;
 6257: : andi, ( reg-target reg-source n -- )
 6258:     1 asm-reg-reg-imm ;
 6259: @end example
 6260: 
 6261: @noindent
 6262: This could be factored with:
 6263: @example
 6264: : reg-reg-imm ( op-code -- )
 6265:     CREATE ,
 6266: DOES> ( reg-target reg-source n -- )
 6267:     @@ asm-reg-reg-imm ;
 6268: 
 6269: 0 reg-reg-imm ori,
 6270: 1 reg-reg-imm andi,
 6271: @end example
 6272: 
 6273: @cindex currying
 6274: Another view of @code{CREATE..DOES>} is to consider it as a crude way to
 6275: supply a part of the parameters for a word (known as @dfn{currying} in
 6276: the functional language community). E.g., @code{+} needs two
 6277: parameters. Creating versions of @code{+} with one parameter fixed can
 6278: be done like this:
 6279: 
 6280: @example
 6281: : curry+ ( n1 "name" -- )
 6282:     CREATE ,
 6283: DOES> ( n2 -- n1+n2 )
 6284:     @@ + ;
 6285: 
 6286:  3 curry+ 3+
 6287: -2 curry+ 2-
 6288: @end example
 6289: 
 6290: 
 6291: @node CREATE..DOES> details, Advanced does> usage example, CREATE..DOES> applications, User-defined Defining Words
 6292: @subsubsection The gory details of @code{CREATE..DOES>}
 6293: @cindex @code{CREATE} ... @code{DOES>}, details
 6294: 
 6295: doc-does>
 6296: 
 6297: @cindex @code{DOES>} in a separate definition
 6298: This means that you need not use @code{CREATE} and @code{DOES>} in the
 6299: same definition; you can put the @code{DOES>}-part in a separate
 6300: definition. This allows us to, e.g., select among different @code{DOES>}-parts:
 6301: @example
 6302: : does1 
 6303: DOES> ( ... -- ... )
 6304:     ... ;
 6305: 
 6306: : does2
 6307: DOES> ( ... -- ... )
 6308:     ... ;
 6309: 
 6310: : def-word ( ... -- ... )
 6311:     create ...
 6312:     IF
 6313:        does1
 6314:     ELSE
 6315:        does2
 6316:     ENDIF ;
 6317: @end example
 6318: 
 6319: In this example, the selection of whether to use @code{does1} or
 6320: @code{does2} is made at definition-time; at the time that the child word is
 6321: @code{CREATE}d.
 6322: 
 6323: @cindex @code{DOES>} in interpretation state
 6324: In a standard program you can apply a @code{DOES>}-part only if the last
 6325: word was defined with @code{CREATE}. In Gforth, the @code{DOES>}-part
 6326: will override the behaviour of the last word defined in any case. In a
 6327: standard program, you can use @code{DOES>} only in a colon
 6328: definition. In Gforth, you can also use it in interpretation state, in a
 6329: kind of one-shot mode; for example:
 6330: @example
 6331: CREATE name ( ... -- ... )
 6332:   @i{initialization}
 6333: DOES>
 6334:   @i{code} ;
 6335: @end example
 6336: 
 6337: @noindent
 6338: is equivalent to the standard:
 6339: @example
 6340: :noname
 6341: DOES>
 6342:     @i{code} ;
 6343: CREATE name EXECUTE ( ... -- ... )
 6344:     @i{initialization}
 6345: @end example
 6346: 
 6347: doc->body
 6348: 
 6349: @node Advanced does> usage example, @code{Const-does>}, CREATE..DOES> details, User-defined Defining Words
 6350: @subsubsection Advanced does> usage example
 6351: 
 6352: The MIPS disassembler (@file{arch/mips/disasm.fs}) contains many words
 6353: for disassembling instructions, that follow a very repetetive scheme:
 6354: 
 6355: @example
 6356: :noname @var{disasm-operands} s" @var{inst-name}" type ;
 6357: @var{entry-num} cells @var{table} + !
 6358: @end example
 6359: 
 6360: Of course, this inspires the idea to factor out the commonalities to
 6361: allow a definition like
 6362: 
 6363: @example
 6364: @var{disasm-operands} @var{entry-num} @var{table} define-inst @var{inst-name}
 6365: @end example
 6366: 
 6367: The parameters @var{disasm-operands} and @var{table} are usually
 6368: correlated.  Moreover, before I wrote the disassembler, there already
 6369: existed code that defines instructions like this:
 6370: 
 6371: @example
 6372: @var{entry-num} @var{inst-format} @var{inst-name}
 6373: @end example
 6374: 
 6375: This code comes from the assembler and resides in
 6376: @file{arch/mips/insts.fs}.
 6377: 
 6378: So I had to define the @var{inst-format} words that performed the scheme
 6379: above when executed.  At first I chose to use run-time code-generation:
 6380: 
 6381: @example
 6382: : @var{inst-format} ( entry-num "name" -- ; compiled code: addr w -- )
 6383:   :noname Postpone @var{disasm-operands}
 6384:   name Postpone sliteral Postpone type Postpone ;
 6385:   swap cells @var{table} + ! ;
 6386: @end example
 6387: 
 6388: Note that this supplies the other two parameters of the scheme above.
 6389: 
 6390: An alternative would have been to write this using
 6391: @code{create}/@code{does>}:
 6392: 
 6393: @example
 6394: : @var{inst-format} ( entry-num "name" -- )
 6395:   here name string, ( entry-num c-addr ) \ parse and save "name"
 6396:   noname create , ( entry-num )
 6397:   lastxt swap cells @var{table} + !
 6398: does> ( addr w -- )
 6399:   \ disassemble instruction w at addr
 6400:   @@ >r 
 6401:   @var{disasm-operands}
 6402:   r> count type ;
 6403: @end example
 6404: 
 6405: Somehow the first solution is simpler, mainly because it's simpler to
 6406: shift a string from definition-time to use-time with @code{sliteral}
 6407: than with @code{string,} and friends.
 6408: 
 6409: I wrote a lot of words following this scheme and soon thought about
 6410: factoring out the commonalities among them.  Note that this uses a
 6411: two-level defining word, i.e., a word that defines ordinary defining
 6412: words.
 6413: 
 6414: This time a solution involving @code{postpone} and friends seemed more
 6415: difficult (try it as an exercise), so I decided to use a
 6416: @code{create}/@code{does>} word; since I was already at it, I also used
 6417: @code{create}/@code{does>} for the lower level (try using
 6418: @code{postpone} etc. as an exercise), resulting in the following
 6419: definition:
 6420: 
 6421: @example
 6422: : define-format ( disasm-xt table-xt -- )
 6423:     \ define an instruction format that uses disasm-xt for
 6424:     \ disassembling and enters the defined instructions into table
 6425:     \ table-xt
 6426:     create 2,
 6427: does> ( u "inst" -- )
 6428:     \ defines an anonymous word for disassembling instruction inst,
 6429:     \ and enters it as u-th entry into table-xt
 6430:     2@@ swap here name string, ( u table-xt disasm-xt c-addr ) \ remember string
 6431:     noname create 2,      \ define anonymous word
 6432:     execute lastxt swap ! \ enter xt of defined word into table-xt
 6433: does> ( addr w -- )
 6434:     \ disassemble instruction w at addr
 6435:     2@@ >r ( addr w disasm-xt R: c-addr )
 6436:     execute ( R: c-addr ) \ disassemble operands
 6437:     r> count type ; \ print name 
 6438: @end example
 6439: 
 6440: Note that the tables here (in contrast to above) do the @code{cells +}
 6441: by themselves (that's why you have to pass an xt).  This word is used in
 6442: the following way:
 6443: 
 6444: @example
 6445: ' @var{disasm-operands} ' @var{table} define-format @var{inst-format}
 6446: @end example
 6447: 
 6448: As shown above, the defined instruction format is then used like this:
 6449: 
 6450: @example
 6451: @var{entry-num} @var{inst-format} @var{inst-name}
 6452: @end example
 6453: 
 6454: In terms of currying, this kind of two-level defining word provides the
 6455: parameters in three stages: first @var{disasm-operands} and @var{table},
 6456: then @var{entry-num} and @var{inst-name}, finally @code{addr w}, i.e.,
 6457: the instruction to be disassembled.  
 6458: 
 6459: Of course this did not quite fit all the instruction format names used
 6460: in @file{insts.fs}, so I had to define a few wrappers that conditioned
 6461: the parameters into the right form.
 6462: 
 6463: If you have trouble following this section, don't worry.  First, this is
 6464: involved and takes time (and probably some playing around) to
 6465: understand; second, this is the first two-level
 6466: @code{create}/@code{does>} word I have written in seventeen years of
 6467: Forth; and if I did not have @file{insts.fs} to start with, I may well
 6468: have elected to use just a one-level defining word (with some repeating
 6469: of parameters when using the defining word). So it is not necessary to
 6470: understand this, but it may improve your understanding of Forth.
 6471: 
 6472: 
 6473: @node @code{Const-does>},  , Advanced does> usage example, User-defined Defining Words
 6474: @subsubsection @code{Const-does>}
 6475: 
 6476: A frequent use of @code{create}...@code{does>} is for transferring some
 6477: values from definition-time to run-time.  Gforth supports this use with
 6478: 
 6479: doc-const-does>
 6480: 
 6481: A typical use of this word is:
 6482: 
 6483: @example
 6484: : curry+ ( n1 "name" -- )
 6485: 1 0 CONST-DOES> ( n2 -- n1+n2 )
 6486:     + ;
 6487: 
 6488: 3 curry+ 3+
 6489: @end example
 6490: 
 6491: Here the @code{1 0} means that 1 cell and 0 floats are transferred from
 6492: definition to run-time.
 6493: 
 6494: The advantages of using @code{const-does>} are:
 6495: 
 6496: @itemize
 6497: 
 6498: @item
 6499: You don't have to deal with storing and retrieving the values, i.e.,
 6500: your program becomes more writable and readable.
 6501: 
 6502: @item
 6503: When using @code{does>}, you have to introduce a @code{@@} that cannot
 6504: be optimized away (because you could change the data using
 6505: @code{>body}...@code{!}); @code{const-does>} avoids this problem.
 6506: 
 6507: @end itemize
 6508: 
 6509: An ANS Forth implementation of @code{const-does>} is available in
 6510: @file{compat/const-does.fs}.
 6511: 
 6512: 
 6513: @node Deferred words, Aliases, User-defined Defining Words, Defining Words
 6514: @subsection Deferred words
 6515: @cindex deferred words
 6516: 
 6517: The defining word @code{Defer} allows you to define a word by name
 6518: without defining its behaviour; the definition of its behaviour is
 6519: deferred. Here are two situation where this can be useful:
 6520: 
 6521: @itemize @bullet
 6522: @item
 6523: Where you want to allow the behaviour of a word to be altered later, and
 6524: for all precompiled references to the word to change when its behaviour
 6525: is changed.
 6526: @item
 6527: For mutual recursion; @xref{Calls and returns}.
 6528: @end itemize
 6529: 
 6530: In the following example, @code{foo} always invokes the version of
 6531: @code{greet} that prints ``@code{Good morning}'' whilst @code{bar}
 6532: always invokes the version that prints ``@code{Hello}''. There is no way
 6533: of getting @code{foo} to use the later version without re-ordering the
 6534: source code and recompiling it.
 6535: 
 6536: @example
 6537: : greet ." Good morning" ;
 6538: : foo ... greet ... ;
 6539: : greet ." Hello" ;
 6540: : bar ... greet ... ;
 6541: @end example
 6542: 
 6543: This problem can be solved by defining @code{greet} as a @code{Defer}red
 6544: word. The behaviour of a @code{Defer}red word can be defined and
 6545: redefined at any time by using @code{IS} to associate the xt of a
 6546: previously-defined word with it. The previous example becomes:
 6547: 
 6548: @example
 6549: Defer greet ( -- )
 6550: : foo ... greet ... ;
 6551: : bar ... greet ... ;
 6552: : greet1 ( -- ) ." Good morning" ;
 6553: : greet2 ( -- ) ." Hello" ;
 6554: ' greet2 <IS> greet  \ make greet behave like greet2
 6555: @end example
 6556: 
 6557: @progstyle
 6558: You should write a stack comment for every deferred word, and put only
 6559: XTs into deferred words that conform to this stack effect.  Otherwise
 6560: it's too difficult to use the deferred word.
 6561: 
 6562: A deferred word can be used to improve the statistics-gathering example
 6563: from @ref{User-defined Defining Words}; rather than edit the
 6564: application's source code to change every @code{:} to a @code{my:}, do
 6565: this:
 6566: 
 6567: @example
 6568: : real: : ;     \ retain access to the original
 6569: defer :         \ redefine as a deferred word
 6570: ' my: <IS> :      \ use special version of :
 6571: \
 6572: \ load application here
 6573: \
 6574: ' real: <IS> :    \ go back to the original
 6575: @end example
 6576: 
 6577: 
 6578: One thing to note is that @code{<IS>} consumes its name when it is
 6579: executed.  If you want to specify the name at compile time, use
 6580: @code{[IS]}:
 6581: 
 6582: @example
 6583: : set-greet ( xt -- )
 6584:   [IS] greet ;
 6585: 
 6586: ' greet1 set-greet
 6587: @end example
 6588: 
 6589: A deferred word can only inherit execution semantics from the xt
 6590: (because that is all that an xt can represent -- for more discussion of
 6591: this @pxref{Tokens for Words}); by default it will have default
 6592: interpretation and compilation semantics deriving from this execution
 6593: semantics.  However, you can change the interpretation and compilation
 6594: semantics of the deferred word in the usual ways:
 6595: 
 6596: @example
 6597: : bar .... ; compile-only
 6598: Defer fred immediate
 6599: Defer jim
 6600: 
 6601: ' bar <IS> jim  \ jim has default semantics
 6602: ' bar <IS> fred \ fred is immediate
 6603: @end example
 6604: 
 6605: doc-defer
 6606: doc-<is>
 6607: doc-[is]
 6608: doc-is
 6609: @comment TODO document these: what's defers [is]
 6610: doc-what's
 6611: doc-defers
 6612: 
 6613: @c Use @code{words-deferred} to see a list of deferred words.
 6614: 
 6615: Definitions in ANS Forth for @code{defer}, @code{<is>} and @code{[is]}
 6616: are provided in @file{compat/defer.fs}.
 6617: 
 6618: 
 6619: @node Aliases,  , Deferred words, Defining Words
 6620: @subsection Aliases
 6621: @cindex aliases
 6622: 
 6623: The defining word @code{Alias} allows you to define a word by name that
 6624: has the same behaviour as some other word. Here are two situation where
 6625: this can be useful:
 6626: 
 6627: @itemize @bullet
 6628: @item
 6629: When you want access to a word's definition from a different word list
 6630: (for an example of this, see the definition of the @code{Root} word list
 6631: in the Gforth source).
 6632: @item
 6633: When you want to create a synonym; a definition that can be known by
 6634: either of two names (for example, @code{THEN} and @code{ENDIF} are
 6635: aliases).
 6636: @end itemize
 6637: 
 6638: Like deferred words, an alias has default compilation and interpretation
 6639: semantics at the beginning (not the modifications of the other word),
 6640: but you can change them in the usual ways (@code{immediate},
 6641: @code{compile-only}). For example:
 6642: 
 6643: @example
 6644: : foo ... ; immediate
 6645: 
 6646: ' foo Alias bar \ bar is not an immediate word
 6647: ' foo Alias fooby immediate \ fooby is an immediate word
 6648: @end example
 6649: 
 6650: Words that are aliases have the same xt, different headers in the
 6651: dictionary, and consequently different name tokens (@pxref{Tokens for
 6652: Words}) and possibly different immediate flags.  An alias can only have
 6653: default or immediate compilation semantics; you can define aliases for
 6654: combined words with @code{interpret/compile:} -- see @ref{Combined words}.
 6655: 
 6656: doc-alias
 6657: 
 6658: 
 6659: @node Interpretation and Compilation Semantics, Tokens for Words, Defining Words, Words
 6660: @section Interpretation and Compilation Semantics
 6661: @cindex semantics, interpretation and compilation
 6662: 
 6663: @c !! state and ' are used without explanation
 6664: @c example for immediate/compile-only? or is the tutorial enough
 6665: 
 6666: @cindex interpretation semantics
 6667: The @dfn{interpretation semantics} of a (named) word are what the text
 6668: interpreter does when it encounters the word in interpret state. It also
 6669: appears in some other contexts, e.g., the execution token returned by
 6670: @code{' @i{word}} identifies the interpretation semantics of @i{word}
 6671: (in other words, @code{' @i{word} execute} is equivalent to
 6672: interpret-state text interpretation of @code{@i{word}}).
 6673: 
 6674: @cindex compilation semantics
 6675: The @dfn{compilation semantics} of a (named) word are what the text
 6676: interpreter does when it encounters the word in compile state. It also
 6677: appears in other contexts, e.g, @code{POSTPONE @i{word}}
 6678: compiles@footnote{In standard terminology, ``appends to the current
 6679: definition''.} the compilation semantics of @i{word}.
 6680: 
 6681: @cindex execution semantics
 6682: The standard also talks about @dfn{execution semantics}. They are used
 6683: only for defining the interpretation and compilation semantics of many
 6684: words. By default, the interpretation semantics of a word are to
 6685: @code{execute} its execution semantics, and the compilation semantics of
 6686: a word are to @code{compile,} its execution semantics.@footnote{In
 6687: standard terminology: The default interpretation semantics are its
 6688: execution semantics; the default compilation semantics are to append its
 6689: execution semantics to the execution semantics of the current
 6690: definition.}
 6691: 
 6692: Unnamed words (@pxref{Anonymous Definitions}) cannot be encountered by
 6693: the text interpreter, ticked, or @code{postpone}d, so they have no
 6694: interpretation or compilation semantics.  Their behaviour is represented
 6695: by their XT (@pxref{Tokens for Words}), and we call it execution
 6696: semantics, too.
 6697: 
 6698: @comment TODO expand, make it co-operate with new sections on text interpreter.
 6699: 
 6700: @cindex immediate words
 6701: @cindex compile-only words
 6702: You can change the semantics of the most-recently defined word:
 6703: 
 6704: 
 6705: doc-immediate
 6706: doc-compile-only
 6707: doc-restrict
 6708: 
 6709: By convention, words with non-default compilation semantics (e.g.,
 6710: immediate words) often have names surrounded with brackets (e.g.,
 6711: @code{[']}, @pxref{Execution token}).
 6712: 
 6713: Note that ticking (@code{'}) a compile-only word gives an error
 6714: (``Interpreting a compile-only word'').
 6715: 
 6716: @menu
 6717: * Combined words::              
 6718: @end menu
 6719: 
 6720: 
 6721: @node Combined words,  , Interpretation and Compilation Semantics, Interpretation and Compilation Semantics
 6722: @subsection Combined Words
 6723: @cindex combined words
 6724: 
 6725: Gforth allows you to define @dfn{combined words} -- words that have an
 6726: arbitrary combination of interpretation and compilation semantics.
 6727: 
 6728: doc-interpret/compile:
 6729: 
 6730: This feature was introduced for implementing @code{TO} and @code{S"}. I
 6731: recommend that you do not define such words, as cute as they may be:
 6732: they make it hard to get at both parts of the word in some contexts.
 6733: E.g., assume you want to get an execution token for the compilation
 6734: part. Instead, define two words, one that embodies the interpretation
 6735: part, and one that embodies the compilation part.  Once you have done
 6736: that, you can define a combined word with @code{interpret/compile:} for
 6737: the convenience of your users.
 6738: 
 6739: You might try to use this feature to provide an optimizing
 6740: implementation of the default compilation semantics of a word. For
 6741: example, by defining:
 6742: @example
 6743: :noname
 6744:    foo bar ;
 6745: :noname
 6746:    POSTPONE foo POSTPONE bar ;
 6747: interpret/compile: opti-foobar
 6748: @end example
 6749: 
 6750: @noindent
 6751: as an optimizing version of:
 6752: 
 6753: @example
 6754: : foobar
 6755:     foo bar ;
 6756: @end example
 6757: 
 6758: Unfortunately, this does not work correctly with @code{[compile]},
 6759: because @code{[compile]} assumes that the compilation semantics of all
 6760: @code{interpret/compile:} words are non-default. I.e., @code{[compile]
 6761: opti-foobar} would compile compilation semantics, whereas
 6762: @code{[compile] foobar} would compile interpretation semantics.
 6763: 
 6764: @cindex state-smart words (are a bad idea)
 6765: @anchor{state-smartness}
 6766: Some people try to use @dfn{state-smart} words to emulate the feature provided
 6767: by @code{interpret/compile:} (words are state-smart if they check
 6768: @code{STATE} during execution). E.g., they would try to code
 6769: @code{foobar} like this:
 6770: 
 6771: @example
 6772: : foobar
 6773:   STATE @@
 6774:   IF ( compilation state )
 6775:     POSTPONE foo POSTPONE bar
 6776:   ELSE
 6777:     foo bar
 6778:   ENDIF ; immediate
 6779: @end example
 6780: 
 6781: Although this works if @code{foobar} is only processed by the text
 6782: interpreter, it does not work in other contexts (like @code{'} or
 6783: @code{POSTPONE}). E.g., @code{' foobar} will produce an execution token
 6784: for a state-smart word, not for the interpretation semantics of the
 6785: original @code{foobar}; when you execute this execution token (directly
 6786: with @code{EXECUTE} or indirectly through @code{COMPILE,}) in compile
 6787: state, the result will not be what you expected (i.e., it will not
 6788: perform @code{foo bar}). State-smart words are a bad idea. Simply don't
 6789: write them@footnote{For a more detailed discussion of this topic, see
 6790: M. Anton Ertl,
 6791: @cite{@uref{http://www.complang.tuwien.ac.at/papers/ertl98.ps.gz,@code{State}-smartness---Why
 6792: it is Evil and How to Exorcise it}}, EuroForth '98.}!
 6793: 
 6794: @cindex defining words with arbitrary semantics combinations
 6795: It is also possible to write defining words that define words with
 6796: arbitrary combinations of interpretation and compilation semantics. In
 6797: general, they look like this:
 6798: 
 6799: @example
 6800: : def-word
 6801:     create-interpret/compile
 6802:     @i{code1}
 6803: interpretation>
 6804:     @i{code2}
 6805: <interpretation
 6806: compilation>
 6807:     @i{code3}
 6808: <compilation ;
 6809: @end example
 6810: 
 6811: For a @i{word} defined with @code{def-word}, the interpretation
 6812: semantics are to push the address of the body of @i{word} and perform
 6813: @i{code2}, and the compilation semantics are to push the address of
 6814: the body of @i{word} and perform @i{code3}. E.g., @code{constant}
 6815: can also be defined like this (except that the defined constants don't
 6816: behave correctly when @code{[compile]}d):
 6817: 
 6818: @example
 6819: : constant ( n "name" -- )
 6820:     create-interpret/compile
 6821:     ,
 6822: interpretation> ( -- n )
 6823:     @@
 6824: <interpretation
 6825: compilation> ( compilation. -- ; run-time. -- n )
 6826:     @@ postpone literal
 6827: <compilation ;
 6828: @end example
 6829: 
 6830: 
 6831: doc-create-interpret/compile
 6832: doc-interpretation>
 6833: doc-<interpretation
 6834: doc-compilation>
 6835: doc-<compilation
 6836: 
 6837: 
 6838: Words defined with @code{interpret/compile:} and
 6839: @code{create-interpret/compile} have an extended header structure that
 6840: differs from other words; however, unless you try to access them with
 6841: plain address arithmetic, you should not notice this. Words for
 6842: accessing the header structure usually know how to deal with this; e.g.,
 6843: @code{'} @i{word} @code{>body} also gives you the body of a word created
 6844: with @code{create-interpret/compile}.
 6845: 
 6846: 
 6847: @c -------------------------------------------------------------
 6848: @node Tokens for Words, Compiling words, Interpretation and Compilation Semantics, Words
 6849: @section Tokens for Words
 6850: @cindex tokens for words
 6851: 
 6852: This section describes the creation and use of tokens that represent
 6853: words.
 6854: 
 6855: @menu
 6856: * Execution token::             represents execution/interpretation semantics
 6857: * Compilation token::           represents compilation semantics
 6858: * Name token::                  represents named words
 6859: @end menu
 6860: 
 6861: @node Execution token, Compilation token, Tokens for Words, Tokens for Words
 6862: @subsection Execution token
 6863: 
 6864: @cindex xt
 6865: @cindex execution token
 6866: An @dfn{execution token} (@i{XT}) represents some behaviour of a word.
 6867: You can use @code{execute} to invoke this behaviour.
 6868: 
 6869: @cindex tick (')
 6870: You can use @code{'} to get an execution token that represents the
 6871: interpretation semantics of a named word:
 6872: 
 6873: @example
 6874: 5 ' .   ( n xt ) 
 6875: execute ( )      \ execute the xt (i.e., ".")
 6876: @end example
 6877: 
 6878: doc-'
 6879: 
 6880: @code{'} parses at run-time; there is also a word @code{[']} that parses
 6881: when it is compiled, and compiles the resulting XT:
 6882: 
 6883: @example
 6884: : foo ['] . execute ;
 6885: 5 foo
 6886: : bar ' execute ; \ by contrast,
 6887: 5 bar .           \ ' parses "." when bar executes
 6888: @end example
 6889: 
 6890: doc-[']
 6891: 
 6892: If you want the execution token of @i{word}, write @code{['] @i{word}}
 6893: in compiled code and @code{' @i{word}} in interpreted code.  Gforth's
 6894: @code{'} and @code{[']} behave somewhat unusually by complaining about
 6895: compile-only words (because these words have no interpretation
 6896: semantics).  You might get what you want by using @code{COMP' @i{word}
 6897: DROP} or @code{[COMP'] @i{word} DROP} (for details @pxref{Compilation
 6898: token}).
 6899: 
 6900: Another way to get an XT is @code{:noname} or @code{lastxt}
 6901: (@pxref{Anonymous Definitions}).  For anonymous words this gives an xt
 6902: for the only behaviour the word has (the execution semantics).  For
 6903: named words, @code{lastxt} produces an XT for the same behaviour it
 6904: would produce if the word was defined anonymously.
 6905: 
 6906: @example
 6907: :noname ." hello" ;
 6908: execute
 6909: @end example
 6910: 
 6911: An XT occupies one cell and can be manipulated like any other cell.
 6912: 
 6913: @cindex code field address
 6914: @cindex CFA
 6915: In ANS Forth the XT is just an abstract data type (i.e., defined by the
 6916: operations that produce or consume it).  For old hands: In Gforth, the
 6917: XT is implemented as a code field address (CFA).
 6918: 
 6919: doc-execute
 6920: doc-perform
 6921: 
 6922: @node Compilation token, Name token, Execution token, Tokens for Words
 6923: @subsection Compilation token
 6924: 
 6925: @cindex compilation token
 6926: @cindex CT (compilation token)
 6927: Gforth represents the compilation semantics of a named word by a
 6928: @dfn{compilation token} consisting of two cells: @i{w xt}. The top cell
 6929: @i{xt} is an execution token. The compilation semantics represented by
 6930: the compilation token can be performed with @code{execute}, which
 6931: consumes the whole compilation token, with an additional stack effect
 6932: determined by the represented compilation semantics.
 6933: 
 6934: At present, the @i{w} part of a compilation token is an execution token,
 6935: and the @i{xt} part represents either @code{execute} or
 6936: @code{compile,}@footnote{Depending upon the compilation semantics of the
 6937: word. If the word has default compilation semantics, the @i{xt} will
 6938: represent @code{compile,}. Otherwise (e.g., for immediate words), the
 6939: @i{xt} will represent @code{execute}.}. However, don't rely on that
 6940: knowledge, unless necessary; future versions of Gforth may introduce
 6941: unusual compilation tokens (e.g., a compilation token that represents
 6942: the compilation semantics of a literal).
 6943: 
 6944: You can perform the compilation semantics represented by the compilation
 6945: token with @code{execute}.  You can compile the compilation semantics
 6946: with @code{postpone,}. I.e., @code{COMP' @i{word} postpone,} is
 6947: equivalent to @code{postpone @i{word}}.
 6948: 
 6949: doc-[comp']
 6950: doc-comp'
 6951: doc-postpone,
 6952: 
 6953: @node Name token,  , Compilation token, Tokens for Words
 6954: @subsection Name token
 6955: 
 6956: @cindex name token
 6957: @cindex name field address
 6958: @cindex NFA
 6959: Gforth represents named words by the @dfn{name token}, (@i{nt}). In
 6960: Gforth, the abstract data type @emph{name token} is implemented as a
 6961: name field address (NFA).
 6962: 
 6963: doc-find-name
 6964: doc-name>int
 6965: doc-name?int
 6966: doc-name>comp
 6967: doc-name>string
 6968: doc-id.
 6969: doc-.name
 6970: doc-.id
 6971: 
 6972: @c ----------------------------------------------------------
 6973: @node Compiling words, The Text Interpreter, Tokens for Words, Words
 6974: @section Compiling words
 6975: @cindex compiling words
 6976: @cindex macros
 6977: 
 6978: In contrast to most other languages, Forth has no strict boundary
 6979: between compilation and run-time.  E.g., you can run arbitrary code
 6980: between defining words (or for computing data used by defining words
 6981: like @code{constant}). Moreover, @code{Immediate} (@pxref{Interpretation
 6982: and Compilation Semantics} and @code{[}...@code{]} (see below) allow
 6983: running arbitrary code while compiling a colon definition (exception:
 6984: you must not allot dictionary space).
 6985: 
 6986: @menu
 6987: * Literals::                    Compiling data values
 6988: * Macros::                      Compiling words
 6989: @end menu
 6990: 
 6991: @node Literals, Macros, Compiling words, Compiling words
 6992: @subsection Literals
 6993: @cindex Literals
 6994: 
 6995: The simplest and most frequent example is to compute a literal during
 6996: compilation.  E.g., the following definition prints an array of strings,
 6997: one string per line:
 6998: 
 6999: @example
 7000: : .strings ( addr u -- ) \ gforth
 7001:     2* cells bounds U+DO
 7002: 	cr i 2@@ type
 7003:     2 cells +LOOP ;  
 7004: @end example
 7005: 
 7006: With a simple-minded compiler like Gforth's, this computes @code{2
 7007: cells} on every loop iteration.  You can compute this value once and for
 7008: all at compile time and compile it into the definition like this:
 7009: 
 7010: @example
 7011: : .strings ( addr u -- ) \ gforth
 7012:     2* cells bounds U+DO
 7013: 	cr i 2@@ type
 7014:     [ 2 cells ] literal +LOOP ;  
 7015: @end example
 7016: 
 7017: @code{[} switches the text interpreter to interpret state (you will get
 7018: an @code{ok} prompt if you type this example interactively and insert a
 7019: newline between @code{[} and @code{]}), so it performs the
 7020: interpretation semantics of @code{2 cells}; this computes a number.
 7021: @code{]} switches the text interpreter back into compile state.  It then
 7022: performs @code{Literal}'s compilation semantics, which are to compile
 7023: this number into the current word.  You can decompile the word with
 7024: @code{see .strings} to see the effect on the compiled code.
 7025: 
 7026: You can also optimize the @code{2* cells} into @code{[ 2 cells ] literal
 7027: *} in this way.
 7028: 
 7029: doc-[
 7030: doc-]
 7031: doc-literal
 7032: doc-]L
 7033: 
 7034: There are also words for compiling other data types than single cells as
 7035: literals:
 7036: 
 7037: doc-2literal
 7038: doc-fliteral
 7039: doc-sliteral
 7040: 
 7041: @cindex colon-sys, passing data across @code{:}
 7042: @cindex @code{:}, passing data across
 7043: You might be tempted to pass data from outside a colon definition to the
 7044: inside on the data stack.  This does not work, because @code{:} puhes a
 7045: colon-sys, making stuff below unaccessible.  E.g., this does not work:
 7046: 
 7047: @example
 7048: 5 : foo literal ; \ error: "unstructured"
 7049: @end example
 7050: 
 7051: Instead, you have to pass the value in some other way, e.g., through a
 7052: variable:
 7053: 
 7054: @example
 7055: variable temp
 7056: 5 temp !
 7057: : foo [ temp @@ ] literal ;
 7058: @end example
 7059: 
 7060: 
 7061: @node Macros,  , Literals, Compiling words
 7062: @subsection Macros
 7063: @cindex Macros
 7064: @cindex compiling compilation semantics
 7065: 
 7066: @code{Literal} and friends compile data values into the current
 7067: definition.  You can also write words that compile other words into the
 7068: current definition.  E.g.,
 7069: 
 7070: @example
 7071: : compile-+ ( -- ) \ compiled code: ( n1 n2 -- n )
 7072:   POSTPONE + ;
 7073: 
 7074: : foo ( n1 n2 -- n )
 7075:   [ compile-+ ] ;
 7076: 1 2 foo .
 7077: @end example
 7078: 
 7079: This is equivalent to @code{: foo + ;} (@code{see foo} to check this).
 7080: What happens in this example?  @code{Postpone} compiles the compilation
 7081: semantics of @code{+} into @code{compile-+}; later the text interpreter
 7082: executes @code{compile-+} and thus the compilation semantics of +, which
 7083: compile (the execution semantics of) @code{+} into
 7084: @code{foo}.@footnote{A recent RFI answer requires that compiling words
 7085: should only be executed in compile state, so this example is not
 7086: guaranteed to work on all standard systems, but on any decent system it
 7087: will work.}
 7088: 
 7089: doc-postpone
 7090: doc-[compile]
 7091: 
 7092: Compiling words like @code{compile-+} are usually immediate (or similar)
 7093: so you do not have to switch to interpret state to execute them;
 7094: mopifying the last example accordingly produces:
 7095: 
 7096: @example
 7097: : [compile-+] ( compilation: --; interpretation: -- )
 7098:   \ compiled code: ( n1 n2 -- n )
 7099:   POSTPONE + ; immediate
 7100: 
 7101: : foo ( n1 n2 -- n )
 7102:   [compile-+] ;
 7103: 1 2 foo .
 7104: @end example
 7105: 
 7106: Immediate compiling words are similar to macros in other languages (in
 7107: particular, Lisp).  The important differences to macros in, e.g., C are:
 7108: 
 7109: @itemize @bullet
 7110: 
 7111: @item
 7112: You use the same language for defining and processing macros, not a
 7113: separate preprocessing language and processor.
 7114: 
 7115: @item
 7116: Consequently, the full power of Forth is available in macro definitions.
 7117: E.g., you can perform arbitrarily complex computations, or generate
 7118: different code conditionally or in a loop (e.g., @pxref{Advanced macros
 7119: Tutorial}).  This power is very useful when writing a parser generators
 7120: or other code-generating software.
 7121: 
 7122: @item
 7123: Macros defined using @code{postpone} etc. deal with the language at a
 7124: higher level than strings; name binding happens at macro definition
 7125: time, so you can avoid the pitfalls of name collisions that can happen
 7126: in C macros.  Of course, Forth is a liberal language and also allows to
 7127: shoot yourself in the foot with text-interpreted macros like
 7128: 
 7129: @example
 7130: : [compile-+] s" +" evaluate ; immediate
 7131: @end example
 7132: 
 7133: Apart from binding the name at macro use time, using @code{evaluate}
 7134: also makes your definition @code{state}-smart (@pxref{state-smartness}).
 7135: @end itemize
 7136: 
 7137: You may want the macro to compile a number into a word.  The word to do
 7138: it is @code{literal}, but you have to @code{postpone} it, so its
 7139: compilation semantics take effect when the macro is executed, not when
 7140: it is compiled:
 7141: 
 7142: @example
 7143: : [compile-5] ( -- ) \ compiled code: ( -- n )
 7144:   5 POSTPONE literal ; immediate
 7145: 
 7146: : foo [compile-5] ;
 7147: foo .
 7148: @end example
 7149: 
 7150: You may want to pass parameters to a macro, that the macro should
 7151: compile into the current definition.  If the parameter is a number, then
 7152: you can use @code{postpone literal} (similar for other values).
 7153: 
 7154: If you want to pass a word that is to be compiled, the usual way is to
 7155: pass an execution token and @code{compile,} it:
 7156: 
 7157: @example
 7158: : twice1 ( xt -- ) \ compiled code: ... -- ...
 7159:   dup compile, compile, ;
 7160: 
 7161: : 2+ ( n1 -- n2 )
 7162:   [ ' 1+ twice1 ] ;
 7163: @end example
 7164: 
 7165: doc-compile,
 7166: 
 7167: An alternative available in Gforth, that allows you to pass compile-only
 7168: words as parameters is to use the compilation token (@pxref{Compilation
 7169: token}).  The same example in this technique:
 7170: 
 7171: @example
 7172: : twice ( ... ct -- ... ) \ compiled code: ... -- ...
 7173:   2dup 2>r execute 2r> execute ;
 7174: 
 7175: : 2+ ( n1 -- n2 )
 7176:   [ comp' 1+ twice ] ;
 7177: @end example
 7178: 
 7179: In the example above @code{2>r} and @code{2r>} ensure that @code{twice}
 7180: works even if the executed compilation semantics has an effect on the
 7181: data stack.
 7182: 
 7183: You can also define complete definitions with these words; this provides
 7184: an alternative to using @code{does>} (@pxref{User-defined Defining
 7185: Words}).  E.g., instead of
 7186: 
 7187: @example
 7188: : curry+ ( n1 "name" -- )
 7189:     CREATE ,
 7190: DOES> ( n2 -- n1+n2 )
 7191:     @@ + ;
 7192: @end example
 7193: 
 7194: you could define
 7195: 
 7196: @example
 7197: : curry+ ( n1 "name" -- )
 7198:   \ name execution: ( n2 -- n1+n2 )
 7199:   >r : r> POSTPONE literal POSTPONE + POSTPONE ; ;
 7200: 
 7201: -3 curry+ 3-
 7202: see 3-
 7203: @end example
 7204: 
 7205: The sequence @code{>r : r>} is necessary, because @code{:} puts a
 7206: colon-sys on the data stack that makes everything below it unaccessible.
 7207: 
 7208: This way of writing defining words is sometimes more, sometimes less
 7209: convenient than using @code{does>} (@pxref{Advanced does> usage
 7210: example}).  One advantage of this method is that it can be optimized
 7211: better, because the compiler knows that the value compiled with
 7212: @code{literal} is fixed, whereas the data associated with a
 7213: @code{create}d word can be changed.
 7214: 
 7215: @c ----------------------------------------------------------
 7216: @node The Text Interpreter, The Input Stream, Compiling words, Words
 7217: @section  The Text Interpreter
 7218: @cindex interpreter - outer
 7219: @cindex text interpreter
 7220: @cindex outer interpreter
 7221: 
 7222: @c Should we really describe all these ugly details?  IMO the text
 7223: @c interpreter should be much cleaner, but that may not be possible within
 7224: @c ANS Forth. - anton
 7225: @c nac-> I wanted to explain how it works to show how you can exploit
 7226: @c it in your own programs. When I was writing a cross-compiler, figuring out
 7227: @c some of these gory details was very helpful to me. None of the textbooks
 7228: @c I've seen cover it, and the most modern Forth textbook -- Forth Inc's,
 7229: @c seems to positively avoid going into too much detail for some of
 7230: @c the internals.
 7231: 
 7232: @c anton: ok.  I wonder, though, if this is the right place; for some stuff
 7233: @c it is; for the ugly details, I would prefer another place.  I wonder
 7234: @c whether we should have a chapter before "Words" that describes some
 7235: @c basic concepts referred to in words, and a chapter after "Words" that
 7236: @c describes implementation details.
 7237: 
 7238: The text interpreter@footnote{This is an expanded version of the
 7239: material in @ref{Introducing the Text Interpreter}.} is an endless loop
 7240: that processes input from the current input device. It is also called
 7241: the outer interpreter, in contrast to the inner interpreter
 7242: (@pxref{Engine}) which executes the compiled Forth code on interpretive
 7243: implementations.
 7244: 
 7245: @cindex interpret state
 7246: @cindex compile state
 7247: The text interpreter operates in one of two states: @dfn{interpret
 7248: state} and @dfn{compile state}. The current state is defined by the
 7249: aptly-named variable @code{state}.
 7250: 
 7251: This section starts by describing how the text interpreter behaves when
 7252: it is in interpret state, processing input from the user input device --
 7253: the keyboard. This is the mode that a Forth system is in after it starts
 7254: up.
 7255: 
 7256: @cindex input buffer
 7257: @cindex terminal input buffer
 7258: The text interpreter works from an area of memory called the @dfn{input
 7259: buffer}@footnote{When the text interpreter is processing input from the
 7260: keyboard, this area of memory is called the @dfn{terminal input buffer}
 7261: (TIB) and is addressed by the (obsolescent) words @code{TIB} and
 7262: @code{#TIB}.}, which stores your keyboard input when you press the
 7263: @key{RET} key. Starting at the beginning of the input buffer, it skips
 7264: leading spaces (called @dfn{delimiters}) then parses a string (a
 7265: sequence of non-space characters) until it reaches either a space
 7266: character or the end of the buffer. Having parsed a string, it makes two
 7267: attempts to process it:
 7268: 
 7269: @cindex dictionary
 7270: @itemize @bullet
 7271: @item
 7272: It looks for the string in a @dfn{dictionary} of definitions. If the
 7273: string is found, the string names a @dfn{definition} (also known as a
 7274: @dfn{word}) and the dictionary search returns information that allows
 7275: the text interpreter to perform the word's @dfn{interpretation
 7276: semantics}. In most cases, this simply means that the word will be
 7277: executed.
 7278: @item
 7279: If the string is not found in the dictionary, the text interpreter
 7280: attempts to treat it as a number, using the rules described in
 7281: @ref{Number Conversion}. If the string represents a legal number in the
 7282: current radix, the number is pushed onto a parameter stack (the data
 7283: stack for integers, the floating-point stack for floating-point
 7284: numbers).
 7285: @end itemize
 7286: 
 7287: If both attempts fail, or if the word is found in the dictionary but has
 7288: no interpretation semantics@footnote{This happens if the word was
 7289: defined as @code{COMPILE-ONLY}.} the text interpreter discards the
 7290: remainder of the input buffer, issues an error message and waits for
 7291: more input. If one of the attempts succeeds, the text interpreter
 7292: repeats the parsing process until the whole of the input buffer has been
 7293: processed, at which point it prints the status message ``@code{ ok}''
 7294: and waits for more input.
 7295: 
 7296: @c anton: this should be in the input stream subsection (or below it)
 7297: 
 7298: @cindex parse area
 7299: The text interpreter keeps track of its position in the input buffer by
 7300: updating a variable called @code{>IN} (pronounced ``to-in''). The value
 7301: of @code{>IN} starts out as 0, indicating an offset of 0 from the start
 7302: of the input buffer. The region from offset @code{>IN @@} to the end of
 7303: the input buffer is called the @dfn{parse area}@footnote{In other words,
 7304: the text interpreter processes the contents of the input buffer by
 7305: parsing strings from the parse area until the parse area is empty.}.
 7306: This example shows how @code{>IN} changes as the text interpreter parses
 7307: the input buffer:
 7308: 
 7309: @example
 7310: : remaining >IN @@ SOURCE 2 PICK - -ROT + SWAP
 7311:   CR ." ->" TYPE ." <-" ; IMMEDIATE 
 7312: 
 7313: 1 2 3 remaining + remaining . 
 7314: 
 7315: : foo 1 2 3 remaining SWAP remaining ;
 7316: @end example
 7317: 
 7318: @noindent
 7319: The result is:
 7320: 
 7321: @example
 7322: ->+ remaining .<-
 7323: ->.<-5  ok
 7324: 
 7325: ->SWAP remaining ;-<
 7326: ->;<-  ok
 7327: @end example
 7328: 
 7329: @cindex parsing words
 7330: The value of @code{>IN} can also be modified by a word in the input
 7331: buffer that is executed by the text interpreter.  This means that a word
 7332: can ``trick'' the text interpreter into either skipping a section of the
 7333: input buffer@footnote{This is how parsing words work.} or into parsing a
 7334: section twice. For example:
 7335: 
 7336: @example
 7337: : lat ." <<foo>>" ;
 7338: : flat ." <<bar>>" >IN DUP @@ 3 - SWAP ! ;
 7339: @end example
 7340: 
 7341: @noindent
 7342: When @code{flat} is executed, this output is produced@footnote{Exercise
 7343: for the reader: what would happen if the @code{3} were replaced with
 7344: @code{4}?}:
 7345: 
 7346: @example
 7347: <<bar>><<foo>>
 7348: @end example
 7349: 
 7350: This technique can be used to work around some of the interoperability
 7351: problems of parsing words.  Of course, it's better to avoid parsing
 7352: words where possible.
 7353: 
 7354: @noindent
 7355: Two important notes about the behaviour of the text interpreter:
 7356: 
 7357: @itemize @bullet
 7358: @item
 7359: It processes each input string to completion before parsing additional
 7360: characters from the input buffer.
 7361: @item
 7362: It treats the input buffer as a read-only region (and so must your code).
 7363: @end itemize
 7364: 
 7365: @noindent
 7366: When the text interpreter is in compile state, its behaviour changes in
 7367: these ways:
 7368: 
 7369: @itemize @bullet
 7370: @item
 7371: If a parsed string is found in the dictionary, the text interpreter will
 7372: perform the word's @dfn{compilation semantics}. In most cases, this
 7373: simply means that the execution semantics of the word will be appended
 7374: to the current definition.
 7375: @item
 7376: When a number is encountered, it is compiled into the current definition
 7377: (as a literal) rather than being pushed onto a parameter stack.
 7378: @item
 7379: If an error occurs, @code{state} is modified to put the text interpreter
 7380: back into interpret state.
 7381: @item
 7382: Each time a line is entered from the keyboard, Gforth prints
 7383: ``@code{ compiled}'' rather than `` @code{ok}''.
 7384: @end itemize
 7385: 
 7386: @cindex text interpreter - input sources
 7387: When the text interpreter is using an input device other than the
 7388: keyboard, its behaviour changes in these ways:
 7389: 
 7390: @itemize @bullet
 7391: @item
 7392: When the parse area is empty, the text interpreter attempts to refill
 7393: the input buffer from the input source. When the input source is
 7394: exhausted, the input source is set back to the previous input source.
 7395: @item
 7396: It doesn't print out ``@code{ ok}'' or ``@code{ compiled}'' messages each
 7397: time the parse area is emptied.
 7398: @item
 7399: If an error occurs, the input source is set back to the user input
 7400: device.
 7401: @end itemize
 7402: 
 7403: You can read about this in more detail in @ref{Input Sources}.
 7404: 
 7405: doc->in
 7406: doc-source
 7407: 
 7408: doc-tib
 7409: doc-#tib
 7410: 
 7411: 
 7412: @menu
 7413: * Input Sources::               
 7414: * Number Conversion::           
 7415: * Interpret/Compile states::    
 7416: * Interpreter Directives::      
 7417: @end menu
 7418: 
 7419: @node Input Sources, Number Conversion, The Text Interpreter, The Text Interpreter
 7420: @subsection Input Sources
 7421: @cindex input sources
 7422: @cindex text interpreter - input sources
 7423: 
 7424: By default, the text interpreter processes input from the user input
 7425: device (the keyboard) when Forth starts up. The text interpreter can
 7426: process input from any of these sources:
 7427: 
 7428: @itemize @bullet
 7429: @item
 7430: The user input device -- the keyboard.
 7431: @item
 7432: A file, using the words described in @ref{Forth source files}.
 7433: @item
 7434: A block, using the words described in @ref{Blocks}.
 7435: @item
 7436: A text string, using @code{evaluate}.
 7437: @end itemize
 7438: 
 7439: A program can identify the current input device from the values of
 7440: @code{source-id} and @code{blk}.
 7441: 
 7442: 
 7443: doc-source-id
 7444: doc-blk
 7445: 
 7446: doc-save-input
 7447: doc-restore-input
 7448: 
 7449: doc-evaluate
 7450: doc-query
 7451: 
 7452: 
 7453: 
 7454: @node Number Conversion, Interpret/Compile states, Input Sources, The Text Interpreter
 7455: @subsection Number Conversion
 7456: @cindex number conversion
 7457: @cindex double-cell numbers, input format
 7458: @cindex input format for double-cell numbers
 7459: @cindex single-cell numbers, input format
 7460: @cindex input format for single-cell numbers
 7461: @cindex floating-point numbers, input format
 7462: @cindex input format for floating-point numbers
 7463: 
 7464: This section describes the rules that the text interpreter uses when it
 7465: tries to convert a string into a number.
 7466: 
 7467: Let <digit> represent any character that is a legal digit in the current
 7468: number base@footnote{For example, 0-9 when the number base is decimal or
 7469: 0-9, A-F when the number base is hexadecimal.}.
 7470: 
 7471: Let <decimal digit> represent any character in the range 0-9.
 7472: 
 7473: Let @{@i{a b}@} represent the @i{optional} presence of any of the characters
 7474: in the braces (@i{a} or @i{b} or neither).
 7475: 
 7476: Let * represent any number of instances of the previous character
 7477: (including none).
 7478: 
 7479: Let any other character represent itself.
 7480: 
 7481: @noindent
 7482: Now, the conversion rules are:
 7483: 
 7484: @itemize @bullet
 7485: @item
 7486: A string of the form <digit><digit>* is treated as a single-precision
 7487: (cell-sized) positive integer. Examples are 0 123 6784532 32343212343456 42
 7488: @item
 7489: A string of the form -<digit><digit>* is treated as a single-precision
 7490: (cell-sized) negative integer, and is represented using 2's-complement
 7491: arithmetic. Examples are -45 -5681 -0
 7492: @item
 7493: A string of the form <digit><digit>*.<digit>* is treated as a double-precision
 7494: (double-cell-sized) positive integer. Examples are 3465. 3.465 34.65
 7495: (all three of these represent the same number).
 7496: @item
 7497: A string of the form -<digit><digit>*.<digit>* is treated as a
 7498: double-precision (double-cell-sized) negative integer, and is
 7499: represented using 2's-complement arithmetic. Examples are -3465. -3.465
 7500: -34.65 (all three of these represent the same number).
 7501: @item
 7502: A string of the form @{+ -@}<decimal digit>@{.@}<decimal digit>*@{e
 7503: E@}@{+ -@}<decimal digit><decimal digit>* is treated as a floating-point
 7504: number. Examples are 1e 1e0 1.e 1.e0 +1e+0 (which all represent the same
 7505: number) +12.E-4
 7506: @end itemize
 7507: 
 7508: By default, the number base used for integer number conversion is given
 7509: by the contents of the variable @code{base}.  Note that a lot of
 7510: confusion can result from unexpected values of @code{base}.  If you
 7511: change @code{base} anywhere, make sure to save the old value and restore
 7512: it afterwards.  In general I recommend keeping @code{base} decimal, and
 7513: using the prefixes described below for the popular non-decimal bases.
 7514: 
 7515: doc-dpl
 7516: doc-base
 7517: doc-hex
 7518: doc-decimal
 7519: 
 7520: 
 7521: @cindex '-prefix for character strings
 7522: @cindex &-prefix for decimal numbers
 7523: @cindex %-prefix for binary numbers
 7524: @cindex $-prefix for hexadecimal numbers
 7525: Gforth allows you to override the value of @code{base} by using a
 7526: prefix@footnote{Some Forth implementations provide a similar scheme by
 7527: implementing @code{$} etc. as parsing words that process the subsequent
 7528: number in the input stream and push it onto the stack. For example, see
 7529: @cite{Number Conversion and Literals}, by Wil Baden; Forth Dimensions
 7530: 20(3) pages 26--27. In such implementations, unlike in Gforth, a space
 7531: is required between the prefix and the number.} before the first digit
 7532: of an (integer) number. Four prefixes are supported:
 7533: 
 7534: @itemize @bullet
 7535: @item
 7536: @code{&} -- decimal
 7537: @item
 7538: @code{%} -- binary
 7539: @item
 7540: @code{$} -- hexadecimal
 7541: @item
 7542: @code{'} -- base @code{max-char+1}
 7543: @end itemize
 7544: 
 7545: Here are some examples, with the equivalent decimal number shown after
 7546: in braces:
 7547: 
 7548: -$41 (-65), %1001101 (205), %1001.0001 (145 - a double-precision number),
 7549: 'AB (16706; ascii A is 65, ascii B is 66, number is 65*256 + 66),
 7550: 'ab (24930; ascii a is 97, ascii B is 98, number is 97*256 + 98),
 7551: &905 (905), $abc (2478), $ABC (2478).
 7552: 
 7553: @cindex number conversion - traps for the unwary
 7554: @noindent
 7555: Number conversion has a number of traps for the unwary:
 7556: 
 7557: @itemize @bullet
 7558: @item
 7559: You cannot determine the current number base using the code sequence
 7560: @code{base @@ .} -- the number base is always 10 in the current number
 7561: base. Instead, use something like @code{base @@ dec.}
 7562: @item
 7563: If the number base is set to a value greater than 14 (for example,
 7564: hexadecimal), the number 123E4 is ambiguous; the conversion rules allow
 7565: it to be intepreted as either a single-precision integer or a
 7566: floating-point number (Gforth treats it as an integer). The ambiguity
 7567: can be resolved by explicitly stating the sign of the mantissa and/or
 7568: exponent: 123E+4 or +123E4 -- if the number base is decimal, no
 7569: ambiguity arises; either representation will be treated as a
 7570: floating-point number.
 7571: @item
 7572: There is a word @code{bin} but it does @i{not} set the number base!
 7573: It is used to specify file types.
 7574: @item
 7575: ANS Forth requires the @code{.} of a double-precision number to be the
 7576: final character in the string.  Gforth allows the @code{.} to be
 7577: anywhere after the first digit.
 7578: @item
 7579: The number conversion process does not check for overflow.
 7580: @item
 7581: In an ANS Forth program @code{base} is required to be decimal when
 7582: converting floating-point numbers.  In Gforth, number conversion to
 7583: floating-point numbers always uses base &10, irrespective of the value
 7584: of @code{base}.
 7585: @end itemize
 7586: 
 7587: You can read numbers into your programs with the words described in
 7588: @ref{Input}.
 7589: 
 7590: @node Interpret/Compile states, Interpreter Directives, Number Conversion, The Text Interpreter
 7591: @subsection Interpret/Compile states
 7592: @cindex Interpret/Compile states
 7593: 
 7594: A standard program is not permitted to change @code{state}
 7595: explicitly. However, it can change @code{state} implicitly, using the
 7596: words @code{[} and @code{]}. When @code{[} is executed it switches
 7597: @code{state} to interpret state, and therefore the text interpreter
 7598: starts interpreting. When @code{]} is executed it switches @code{state}
 7599: to compile state and therefore the text interpreter starts
 7600: compiling. The most common usage for these words is for switching into
 7601: interpret state and back from within a colon definition; this technique
 7602: can be used to compile a literal (for an example, @pxref{Literals}) or
 7603: for conditional compilation (for an example, @pxref{Interpreter
 7604: Directives}).
 7605: 
 7606: 
 7607: @c This is a bad example: It's non-standard, and it's not necessary.
 7608: @c However, I can't think of a good example for switching into compile
 7609: @c state when there is no current word (@code{state}-smart words are not a
 7610: @c good reason).  So maybe we should use an example for switching into
 7611: @c interpret @code{state} in a colon def. - anton
 7612: @c nac-> I agree. I started out by putting in the example, then realised
 7613: @c that it was non-ANS, so wrote more words around it. I hope this
 7614: @c re-written version is acceptable to you. I do want to keep the example
 7615: @c as it is helpful for showing what is and what is not portable, particularly
 7616: @c where it outlaws a style in common use.
 7617: 
 7618: @c anton: it's more important to show what's portable.  After we have done
 7619: @c that, we can also show what's not.  In any case, I have written a
 7620: @c section Compiling Words which also deals with [ ].
 7621: 
 7622: @c  !! The following example does not work in Gforth 0.5.9 or later.
 7623: 
 7624: @c  @code{[} and @code{]} also give you the ability to switch into compile
 7625: @c  state and back, but we cannot think of any useful Standard application
 7626: @c  for this ability. Pre-ANS Forth textbooks have examples like this:
 7627: 
 7628: @c  @example
 7629: @c  : AA ." this is A" ;
 7630: @c  : BB ." this is B" ;
 7631: @c  : CC ." this is C" ;
 7632: 
 7633: @c  create table ] aa bb cc [
 7634: 
 7635: @c  : go ( n -- ) \ n is offset into table.. 0 for 1st entry
 7636: @c    cells table + @@ execute ;
 7637: @c  @end example
 7638: 
 7639: @c  This example builds a jump table; @code{0 go} will display ``@code{this
 7640: @c  is A}''. Using @code{[} and @code{]} in this example is equivalent to
 7641: @c  defining @code{table} like this:
 7642: 
 7643: @c  @example
 7644: @c  create table ' aa COMPILE, ' bb COMPILE, ' cc COMPILE,
 7645: @c  @end example
 7646: 
 7647: @c  The problem with this code is that the definition of @code{table} is not
 7648: @c  portable -- it @i{compile}s execution tokens into code space. Whilst it
 7649: @c  @i{may} work on systems where code space and data space co-incide, the
 7650: @c  Standard only allows data space to be assigned for a @code{CREATE}d
 7651: @c  word. In addition, the Standard only allows @code{@@} to access data
 7652: @c  space, whilst this example is using it to access code space. The only
 7653: @c  portable, Standard way to build this table is to build it in data space,
 7654: @c  like this:
 7655: 
 7656: @c  @example
 7657: @c  create table ' aa , ' bb , ' cc ,
 7658: @c  @end example
 7659: 
 7660: @c  doc-state
 7661: 
 7662: 
 7663: @node Interpreter Directives,  , Interpret/Compile states, The Text Interpreter
 7664: @subsection Interpreter Directives
 7665: @cindex interpreter directives
 7666: @cindex conditional compilation
 7667: 
 7668: These words are usually used in interpret state; typically to control
 7669: which parts of a source file are processed by the text
 7670: interpreter. There are only a few ANS Forth Standard words, but Gforth
 7671: supplements these with a rich set of immediate control structure words
 7672: to compensate for the fact that the non-immediate versions can only be
 7673: used in compile state (@pxref{Control Structures}). Typical usages:
 7674: 
 7675: @example
 7676: FALSE Constant HAVE-ASSEMBLER
 7677: .
 7678: .
 7679: HAVE-ASSEMBLER [IF]
 7680: : ASSEMBLER-FEATURE
 7681:   ...
 7682: ;
 7683: [ENDIF]
 7684: .
 7685: .
 7686: : SEE
 7687:   ... \ general-purpose SEE code
 7688:   [ HAVE-ASSEMBLER [IF] ]
 7689:   ... \ assembler-specific SEE code
 7690:   [ [ENDIF] ]
 7691: ;
 7692: @end example
 7693: 
 7694: 
 7695: doc-[IF]
 7696: doc-[ELSE]
 7697: doc-[THEN]
 7698: doc-[ENDIF]
 7699: 
 7700: doc-[IFDEF]
 7701: doc-[IFUNDEF]
 7702: 
 7703: doc-[?DO]
 7704: doc-[DO]
 7705: doc-[FOR]
 7706: doc-[LOOP]
 7707: doc-[+LOOP]
 7708: doc-[NEXT]
 7709: 
 7710: doc-[BEGIN]
 7711: doc-[UNTIL]
 7712: doc-[AGAIN]
 7713: doc-[WHILE]
 7714: doc-[REPEAT]
 7715: 
 7716: 
 7717: @c -------------------------------------------------------------
 7718: @node The Input Stream, Word Lists, The Text Interpreter, Words
 7719: @section The Input Stream
 7720: @cindex input stream
 7721: 
 7722: @c !! integrate this better with the "Text Interpreter" section
 7723: The text interpreter reads from the input stream, which can come from
 7724: several sources (@pxref{Input Sources}).  Some words, in particular
 7725: defining words, but also words like @code{'}, read parameters from the
 7726: input stream instead of from the stack.
 7727: 
 7728: Such words are called parsing words, because they parse the input
 7729: stream.  Parsing words are hard to use in other words, because it is
 7730: hard to pass program-generated parameters through the input stream.
 7731: They also usually have an unintuitive combination of interpretation and
 7732: compilation semantics when implemented naively, leading to various
 7733: approaches that try to produce a more intuitive behaviour
 7734: (@pxref{Combined words}).
 7735: 
 7736: It should be obvious by now that parsing words are a bad idea.  If you
 7737: want to implement a parsing word for convenience, also provide a factor
 7738: of the word that does not parse, but takes the parameters on the stack.
 7739: To implement the parsing word on top if it, you can use the following
 7740: words:
 7741: 
 7742: @c anton: these belong in the input stream section
 7743: doc-parse
 7744: doc-parse-word
 7745: doc-name
 7746: doc-word
 7747: doc-\"-parse
 7748: doc-refill
 7749: 
 7750: Conversely, if you have the bad luck (or lack of foresight) to have to
 7751: deal with parsing words without having such factors, how do you pass a
 7752: string that is not in the input stream to it?
 7753: 
 7754: doc-execute-parsing
 7755: 
 7756: If you want to run a parsing word on a file, the following word should
 7757: help:
 7758: 
 7759: doc-execute-parsing-file
 7760: 
 7761: @c -------------------------------------------------------------
 7762: @node Word Lists, Environmental Queries, The Input Stream, Words
 7763: @section Word Lists
 7764: @cindex word lists
 7765: @cindex header space
 7766: 
 7767: A wordlist is a list of named words; you can add new words and look up
 7768: words by name (and you can remove words in a restricted way with
 7769: markers).  Every named (and @code{reveal}ed) word is in one wordlist.
 7770: 
 7771: @cindex search order stack
 7772: The text interpreter searches the wordlists present in the search order
 7773: (a stack of wordlists), from the top to the bottom.  Within each
 7774: wordlist, the search starts conceptually at the newest word; i.e., if
 7775: two words in a wordlist have the same name, the newer word is found.
 7776: 
 7777: @cindex compilation word list
 7778: New words are added to the @dfn{compilation wordlist} (aka current
 7779: wordlist).
 7780: 
 7781: @cindex wid
 7782: A word list is identified by a cell-sized word list identifier (@i{wid})
 7783: in much the same way as a file is identified by a file handle. The
 7784: numerical value of the wid has no (portable) meaning, and might change
 7785: from session to session.
 7786: 
 7787: The ANS Forth ``Search order'' word set is intended to provide a set of
 7788: low-level tools that allow various different schemes to be
 7789: implemented. Gforth also provides @code{vocabulary}, a traditional Forth
 7790: word.  @file{compat/vocabulary.fs} provides an implementation in ANS
 7791: Forth.
 7792: 
 7793: @comment TODO: locals section refers to here, saying that every word list (aka
 7794: @comment vocabulary) has its own methods for searching etc. Need to document that.
 7795: @c anton: but better in a separate subsection on wordlist internals
 7796: 
 7797: @comment TODO: document markers, reveal, tables, mappedwordlist
 7798: 
 7799: @comment the gforthman- prefix is used to pick out the true definition of a
 7800: @comment word from the source files, rather than some alias.
 7801: 
 7802: doc-forth-wordlist
 7803: doc-definitions
 7804: doc-get-current
 7805: doc-set-current
 7806: doc-get-order
 7807: doc---gforthman-set-order
 7808: doc-wordlist
 7809: doc-table
 7810: doc->order
 7811: doc-previous
 7812: doc-also
 7813: doc---gforthman-forth
 7814: doc-only
 7815: doc---gforthman-order
 7816: 
 7817: doc-find
 7818: doc-search-wordlist
 7819: 
 7820: doc-words
 7821: doc-vlist
 7822: @c doc-words-deferred
 7823: 
 7824: @c doc-mappedwordlist @c map-structure undefined, implemantation-specific
 7825: doc-root
 7826: doc-vocabulary
 7827: doc-seal
 7828: doc-vocs
 7829: doc-current
 7830: doc-context
 7831: 
 7832: 
 7833: @menu
 7834: * Vocabularies::                
 7835: * Why use word lists?::         
 7836: * Word list example::           
 7837: @end menu
 7838: 
 7839: @node Vocabularies, Why use word lists?, Word Lists, Word Lists
 7840: @subsection Vocabularies
 7841: @cindex Vocabularies, detailed explanation
 7842: 
 7843: Here is an example of creating and using a new wordlist using ANS
 7844: Forth words:
 7845: 
 7846: @example
 7847: wordlist constant my-new-words-wordlist
 7848: : my-new-words get-order nip my-new-words-wordlist swap set-order ;
 7849: 
 7850: \ add it to the search order
 7851: also my-new-words
 7852: 
 7853: \ alternatively, add it to the search order and make it
 7854: \ the compilation word list
 7855: also my-new-words definitions
 7856: \ type "order" to see the problem
 7857: @end example
 7858: 
 7859: The problem with this example is that @code{order} has no way to
 7860: associate the name @code{my-new-words} with the wid of the word list (in
 7861: Gforth, @code{order} and @code{vocs} will display @code{???}  for a wid
 7862: that has no associated name). There is no Standard way of associating a
 7863: name with a wid.
 7864: 
 7865: In Gforth, this example can be re-coded using @code{vocabulary}, which
 7866: associates a name with a wid:
 7867: 
 7868: @example
 7869: vocabulary my-new-words
 7870: 
 7871: \ add it to the search order
 7872: also my-new-words
 7873: 
 7874: \ alternatively, add it to the search order and make it
 7875: \ the compilation word list
 7876: my-new-words definitions
 7877: \ type "order" to see that the problem is solved
 7878: @end example
 7879: 
 7880: 
 7881: @node Why use word lists?, Word list example, Vocabularies, Word Lists
 7882: @subsection Why use word lists?
 7883: @cindex word lists - why use them?
 7884: 
 7885: Here are some reasons why people use wordlists:
 7886: 
 7887: @itemize @bullet
 7888: 
 7889: @c anton: Gforth's hashing implementation makes the search speed
 7890: @c independent from the number of words.  But it is linear with the number
 7891: @c of wordlists that have to be searched, so in effect using more wordlists
 7892: @c actually slows down compilation.
 7893: 
 7894: @c @item
 7895: @c To improve compilation speed by reducing the number of header space
 7896: @c entries that must be searched. This is achieved by creating a new
 7897: @c word list that contains all of the definitions that are used in the
 7898: @c definition of a Forth system but which would not usually be used by
 7899: @c programs running on that system. That word list would be on the search
 7900: @c list when the Forth system was compiled but would be removed from the
 7901: @c search list for normal operation. This can be a useful technique for
 7902: @c low-performance systems (for example, 8-bit processors in embedded
 7903: @c systems) but is unlikely to be necessary in high-performance desktop
 7904: @c systems.
 7905: 
 7906: @item
 7907: To prevent a set of words from being used outside the context in which
 7908: they are valid. Two classic examples of this are an integrated editor
 7909: (all of the edit commands are defined in a separate word list; the
 7910: search order is set to the editor word list when the editor is invoked;
 7911: the old search order is restored when the editor is terminated) and an
 7912: integrated assembler (the op-codes for the machine are defined in a
 7913: separate word list which is used when a @code{CODE} word is defined).
 7914: 
 7915: @item
 7916: To organize the words of an application or library into a user-visible
 7917: set (in @code{forth-wordlist} or some other common wordlist) and a set
 7918: of helper words used just for the implementation (hidden in a separate
 7919: wordlist).  This keeps @code{words}' output smaller, separates
 7920: implementation and interface, and reduces the chance of name conflicts
 7921: within the common wordlist.
 7922: 
 7923: @item
 7924: To prevent a name-space clash between multiple definitions with the same
 7925: name. For example, when building a cross-compiler you might have a word
 7926: @code{IF} that generates conditional code for your target system. By
 7927: placing this definition in a different word list you can control whether
 7928: the host system's @code{IF} or the target system's @code{IF} get used in
 7929: any particular context by controlling the order of the word lists on the
 7930: search order stack.
 7931: 
 7932: @end itemize
 7933: 
 7934: The downsides of using wordlists are:
 7935: 
 7936: @itemize
 7937: 
 7938: @item
 7939: Debugging becomes more cumbersome.
 7940: 
 7941: @item
 7942: Name conflicts worked around with wordlists are still there, and you
 7943: have to arrange the search order carefully to get the desired results;
 7944: if you forget to do that, you get hard-to-find errors (as in any case
 7945: where you read the code differently from the compiler; @code{see} can
 7946: help seeing which of several possible words the name resolves to in such
 7947: cases).  @code{See} displays just the name of the words, not what
 7948: wordlist they belong to, so it might be misleading.  Using unique names
 7949: is a better approach to avoid name conflicts.
 7950: 
 7951: @item
 7952: You have to explicitly undo any changes to the search order.  In many
 7953: cases it would be more convenient if this happened implicitly.  Gforth
 7954: currently does not provide such a feature, but it may do so in the
 7955: future.
 7956: @end itemize
 7957: 
 7958: 
 7959: @node Word list example,  , Why use word lists?, Word Lists
 7960: @subsection Word list example
 7961: @cindex word lists - example
 7962: 
 7963: The following example is from the
 7964: @uref{http://www.complang.tuwien.ac.at/forth/garbage-collection.zip,
 7965: garbage collector} and uses wordlists to separate public words from
 7966: helper words:
 7967: 
 7968: @example
 7969: get-current ( wid )
 7970: vocabulary garbage-collector also garbage-collector definitions
 7971: ... \ define helper words
 7972: ( wid ) set-current \ restore original (i.e., public) compilation wordlist
 7973: ... \ define the public (i.e., API) words
 7974:     \ they can refer to the helper words
 7975: previous \ restore original search order (helper words become invisible)
 7976: @end example
 7977: 
 7978: @c -------------------------------------------------------------
 7979: @node Environmental Queries, Files, Word Lists, Words
 7980: @section Environmental Queries
 7981: @cindex environmental queries
 7982: 
 7983: ANS Forth introduced the idea of ``environmental queries'' as a way
 7984: for a program running on a system to determine certain characteristics of the system.
 7985: The Standard specifies a number of strings that might be recognised by a system.
 7986: 
 7987: The Standard requires that the header space used for environmental queries
 7988: be distinct from the header space used for definitions.
 7989: 
 7990: Typically, environmental queries are supported by creating a set of
 7991: definitions in a word list that is @i{only} used during environmental
 7992: queries; that is what Gforth does. There is no Standard way of adding
 7993: definitions to the set of recognised environmental queries, but any
 7994: implementation that supports the loading of optional word sets must have
 7995: some mechanism for doing this (after loading the word set, the
 7996: associated environmental query string must return @code{true}). In
 7997: Gforth, the word list used to honour environmental queries can be
 7998: manipulated just like any other word list.
 7999: 
 8000: 
 8001: doc-environment?
 8002: doc-environment-wordlist
 8003: 
 8004: doc-gforth
 8005: doc-os-class
 8006: 
 8007: 
 8008: Note that, whilst the documentation for (e.g.) @code{gforth} shows it
 8009: returning two items on the stack, querying it using @code{environment?}
 8010: will return an additional item; the @code{true} flag that shows that the
 8011: string was recognised.
 8012: 
 8013: @comment TODO Document the standard strings or note where they are documented herein
 8014: 
 8015: Here are some examples of using environmental queries:
 8016: 
 8017: @example
 8018: s" address-unit-bits" environment? 0=
 8019: [IF]
 8020:      cr .( environmental attribute address-units-bits unknown... ) cr
 8021: [ELSE]
 8022:      drop \ ensure balanced stack effect
 8023: [THEN]
 8024: 
 8025: \ this might occur in the prelude of a standard program that uses THROW
 8026: s" exception" environment? [IF]
 8027:    0= [IF]
 8028:       : throw abort" exception thrown" ;
 8029:    [THEN]
 8030: [ELSE] \ we don't know, so make sure
 8031:    : throw abort" exception thrown" ;
 8032: [THEN]
 8033: 
 8034: s" gforth" environment? [IF] .( Gforth version ) TYPE
 8035:                         [ELSE] .( Not Gforth..) [THEN]
 8036: 
 8037: \ a program using v*
 8038: s" gforth" environment? [IF]
 8039:   s" 0.5.0" compare 0< [IF] \ v* is a primitive since 0.5.0
 8040:    : v* ( f_addr1 nstride1 f_addr2 nstride2 ucount -- r )
 8041:      >r swap 2swap swap 0e r> 0 ?DO
 8042:        dup f@ over + 2swap dup f@ f* f+ over + 2swap
 8043:      LOOP
 8044:      2drop 2drop ; 
 8045:   [THEN]
 8046: [ELSE] \ 
 8047:   : v* ( f_addr1 nstride1 f_addr2 nstride2 ucount -- r )
 8048:   ...
 8049: [THEN]
 8050: @end example
 8051: 
 8052: Here is an example of adding a definition to the environment word list:
 8053: 
 8054: @example
 8055: get-current environment-wordlist set-current
 8056: true constant block
 8057: true constant block-ext
 8058: set-current
 8059: @end example
 8060: 
 8061: You can see what definitions are in the environment word list like this:
 8062: 
 8063: @example
 8064: environment-wordlist >order words previous
 8065: @end example
 8066: 
 8067: 
 8068: @c -------------------------------------------------------------
 8069: @node Files, Blocks, Environmental Queries, Words
 8070: @section Files
 8071: @cindex files
 8072: @cindex I/O - file-handling
 8073: 
 8074: Gforth provides facilities for accessing files that are stored in the
 8075: host operating system's file-system. Files that are processed by Gforth
 8076: can be divided into two categories:
 8077: 
 8078: @itemize @bullet
 8079: @item
 8080: Files that are processed by the Text Interpreter (@dfn{Forth source files}).
 8081: @item
 8082: Files that are processed by some other program (@dfn{general files}).
 8083: @end itemize
 8084: 
 8085: @menu
 8086: * Forth source files::          
 8087: * General files::               
 8088: * Search Paths::                
 8089: @end menu
 8090: 
 8091: @c -------------------------------------------------------------
 8092: @node Forth source files, General files, Files, Files
 8093: @subsection Forth source files
 8094: @cindex including files
 8095: @cindex Forth source files
 8096: 
 8097: The simplest way to interpret the contents of a file is to use one of
 8098: these two formats:
 8099: 
 8100: @example
 8101: include mysource.fs
 8102: s" mysource.fs" included
 8103: @end example
 8104: 
 8105: You usually want to include a file only if it is not included already
 8106: (by, say, another source file). In that case, you can use one of these
 8107: three formats:
 8108: 
 8109: @example
 8110: require mysource.fs
 8111: needs mysource.fs
 8112: s" mysource.fs" required
 8113: @end example
 8114: 
 8115: @cindex stack effect of included files
 8116: @cindex including files, stack effect
 8117: It is good practice to write your source files such that interpreting them
 8118: does not change the stack. Source files designed in this way can be used with
 8119: @code{required} and friends without complications. For example:
 8120: 
 8121: @example
 8122: 1024 require foo.fs drop
 8123: @end example
 8124: 
 8125: Here you want to pass the argument 1024 (e.g., a buffer size) to
 8126: @file{foo.fs}.  Interpreting @file{foo.fs} has the stack effect ( n -- n
 8127: ), which allows its use with @code{require}.  Of course with such
 8128: parameters to required files, you have to ensure that the first
 8129: @code{require} fits for all uses (i.e., @code{require} it early in the
 8130: master load file).
 8131: 
 8132: doc-include-file
 8133: doc-included
 8134: doc-included?
 8135: doc-include
 8136: doc-required
 8137: doc-require
 8138: doc-needs
 8139: @c doc-init-included-files @c internal
 8140: doc-sourcefilename
 8141: doc-sourceline#
 8142: 
 8143: A definition in ANS Forth for @code{required} is provided in
 8144: @file{compat/required.fs}.
 8145: 
 8146: @c -------------------------------------------------------------
 8147: @node General files, Search Paths, Forth source files, Files
 8148: @subsection General files
 8149: @cindex general files
 8150: @cindex file-handling
 8151: 
 8152: Files are opened/created by name and type. The following file access
 8153: methods (FAMs) are recognised:
 8154: 
 8155: @cindex fam (file access method)
 8156: doc-r/o
 8157: doc-r/w
 8158: doc-w/o
 8159: doc-bin
 8160: 
 8161: 
 8162: When a file is opened/created, it returns a file identifier,
 8163: @i{wfileid} that is used for all other file commands. All file
 8164: commands also return a status value, @i{wior}, that is 0 for a
 8165: successful operation and an implementation-defined non-zero value in the
 8166: case of an error.
 8167: 
 8168: 
 8169: doc-open-file
 8170: doc-create-file
 8171: 
 8172: doc-close-file
 8173: doc-delete-file
 8174: doc-rename-file
 8175: doc-read-file
 8176: doc-read-line
 8177: doc-write-file
 8178: doc-write-line
 8179: doc-emit-file
 8180: doc-flush-file
 8181: 
 8182: doc-file-status
 8183: doc-file-position
 8184: doc-reposition-file
 8185: doc-file-size
 8186: doc-resize-file
 8187: 
 8188: doc-slurp-file
 8189: doc-slurp-fid
 8190: doc-stdin
 8191: doc-stdout
 8192: doc-stderr
 8193: 
 8194: @c ---------------------------------------------------------
 8195: @node Search Paths,  , General files, Files
 8196: @subsection Search Paths
 8197: @cindex path for @code{included}
 8198: @cindex file search path
 8199: @cindex @code{include} search path
 8200: @cindex search path for files
 8201: 
 8202: If you specify an absolute filename (i.e., a filename starting with
 8203: @file{/} or @file{~}, or with @file{:} in the second position (as in
 8204: @samp{C:...})) for @code{included} and friends, that file is included
 8205: just as you would expect.
 8206: 
 8207: If the filename starts with @file{./}, this refers to the directory that
 8208: the present file was @code{included} from.  This allows files to include
 8209: other files relative to their own position (irrespective of the current
 8210: working directory or the absolute position).  This feature is essential
 8211: for libraries consisting of several files, where a file may include
 8212: other files from the library.  It corresponds to @code{#include "..."}
 8213: in C. If the current input source is not a file, @file{.} refers to the
 8214: directory of the innermost file being included, or, if there is no file
 8215: being included, to the current working directory.
 8216: 
 8217: For relative filenames (not starting with @file{./}), Gforth uses a
 8218: search path similar to Forth's search order (@pxref{Word Lists}). It
 8219: tries to find the given filename in the directories present in the path,
 8220: and includes the first one it finds. There are separate search paths for
 8221: Forth source files and general files.  If the search path contains the
 8222: directory @file{.}, this refers to the directory of the current file, or
 8223: the working directory, as if the file had been specified with @file{./}.
 8224: 
 8225: Use @file{~+} to refer to the current working directory (as in the
 8226: @code{bash}).
 8227: 
 8228: @c anton: fold the following subsubsections into this subsection?
 8229: 
 8230: @menu
 8231: * Source Search Paths::         
 8232: * General Search Paths::        
 8233: @end menu
 8234: 
 8235: @c ---------------------------------------------------------
 8236: @node Source Search Paths, General Search Paths, Search Paths, Search Paths
 8237: @subsubsection Source Search Paths
 8238: @cindex search path control, source files
 8239: 
 8240: The search path is initialized when you start Gforth (@pxref{Invoking
 8241: Gforth}). You can display it and change it using @code{fpath} in
 8242: combination with the general path handling words.
 8243: 
 8244: doc-fpath
 8245: @c the functionality of the following words is easily available through
 8246: @c   fpath and the general path words.  The may go away.
 8247: @c doc-.fpath
 8248: @c doc-fpath+
 8249: @c doc-fpath=
 8250: @c doc-open-fpath-file
 8251: 
 8252: @noindent
 8253: Here is an example of using @code{fpath} and @code{require}:
 8254: 
 8255: @example
 8256: fpath path= /usr/lib/forth/|./
 8257: require timer.fs
 8258: @end example
 8259: 
 8260: 
 8261: @c ---------------------------------------------------------
 8262: @node General Search Paths,  , Source Search Paths, Search Paths
 8263: @subsubsection General Search Paths
 8264: @cindex search path control, source files
 8265: 
 8266: Your application may need to search files in several directories, like
 8267: @code{included} does. To facilitate this, Gforth allows you to define
 8268: and use your own search paths, by providing generic equivalents of the
 8269: Forth search path words:
 8270: 
 8271: doc-open-path-file
 8272: doc-path-allot
 8273: doc-clear-path
 8274: doc-also-path
 8275: doc-.path
 8276: doc-path+
 8277: doc-path=
 8278: 
 8279: @c anton: better define a word for it, say "path-allot ( ucount -- path-addr )
 8280: 
 8281: Here's an example of creating an empty search path:
 8282: @c
 8283: @example
 8284: create mypath 500 path-allot \ maximum length 500 chars (is checked)
 8285: @end example
 8286: 
 8287: @c -------------------------------------------------------------
 8288: @node Blocks, Other I/O, Files, Words
 8289: @section Blocks
 8290: @cindex I/O - blocks
 8291: @cindex blocks
 8292: 
 8293: When you run Gforth on a modern desk-top computer, it runs under the
 8294: control of an operating system which provides certain services.  One of
 8295: these services is @var{file services}, which allows Forth source code
 8296: and data to be stored in files and read into Gforth (@pxref{Files}).
 8297: 
 8298: Traditionally, Forth has been an important programming language on
 8299: systems where it has interfaced directly to the underlying hardware with
 8300: no intervening operating system. Forth provides a mechanism, called
 8301: @dfn{blocks}, for accessing mass storage on such systems.
 8302: 
 8303: A block is a 1024-byte data area, which can be used to hold data or
 8304: Forth source code. No structure is imposed on the contents of the
 8305: block. A block is identified by its number; blocks are numbered
 8306: contiguously from 1 to an implementation-defined maximum.
 8307: 
 8308: A typical system that used blocks but no operating system might use a
 8309: single floppy-disk drive for mass storage, with the disks formatted to
 8310: provide 256-byte sectors. Blocks would be implemented by assigning the
 8311: first four sectors of the disk to block 1, the second four sectors to
 8312: block 2 and so on, up to the limit of the capacity of the disk. The disk
 8313: would not contain any file system information, just the set of blocks.
 8314: 
 8315: @cindex blocks file
 8316: On systems that do provide file services, blocks are typically
 8317: implemented by storing a sequence of blocks within a single @dfn{blocks
 8318: file}.  The size of the blocks file will be an exact multiple of 1024
 8319: bytes, corresponding to the number of blocks it contains. This is the
 8320: mechanism that Gforth uses.
 8321: 
 8322: @cindex @file{blocks.fb}
 8323: Only one blocks file can be open at a time. If you use block words without
 8324: having specified a blocks file, Gforth defaults to the blocks file
 8325: @file{blocks.fb}. Gforth uses the Forth search path when attempting to
 8326: locate a blocks file (@pxref{Source Search Paths}).
 8327: 
 8328: @cindex block buffers
 8329: When you read and write blocks under program control, Gforth uses a
 8330: number of @dfn{block buffers} as intermediate storage. These buffers are
 8331: not used when you use @code{load} to interpret the contents of a block.
 8332: 
 8333: The behaviour of the block buffers is analagous to that of a cache.
 8334: Each block buffer has three states:
 8335: 
 8336: @itemize @bullet
 8337: @item
 8338: Unassigned
 8339: @item
 8340: Assigned-clean
 8341: @item
 8342: Assigned-dirty
 8343: @end itemize
 8344: 
 8345: Initially, all block buffers are @i{unassigned}. In order to access a
 8346: block, the block (specified by its block number) must be assigned to a
 8347: block buffer.
 8348: 
 8349: The assignment of a block to a block buffer is performed by @code{block}
 8350: or @code{buffer}. Use @code{block} when you wish to modify the existing
 8351: contents of a block. Use @code{buffer} when you don't care about the
 8352: existing contents of the block@footnote{The ANS Forth definition of
 8353: @code{buffer} is intended not to cause disk I/O; if the data associated
 8354: with the particular block is already stored in a block buffer due to an
 8355: earlier @code{block} command, @code{buffer} will return that block
 8356: buffer and the existing contents of the block will be
 8357: available. Otherwise, @code{buffer} will simply assign a new, empty
 8358: block buffer for the block.}.
 8359: 
 8360: Once a block has been assigned to a block buffer using @code{block} or
 8361: @code{buffer}, that block buffer becomes the @i{current block
 8362: buffer}. Data may only be manipulated (read or written) within the
 8363: current block buffer.
 8364: 
 8365: When the contents of the current block buffer has been modified it is
 8366: necessary, @emph{before calling @code{block} or @code{buffer} again}, to
 8367: either abandon the changes (by doing nothing) or mark the block as
 8368: changed (assigned-dirty), using @code{update}. Using @code{update} does
 8369: not change the blocks file; it simply changes a block buffer's state to
 8370: @i{assigned-dirty}.  The block will be written implicitly when it's
 8371: buffer is needed for another block, or explicitly by @code{flush} or
 8372: @code{save-buffers}.
 8373: 
 8374: word @code{Flush} writes all @i{assigned-dirty} blocks back to the
 8375: blocks file on disk. Leaving Gforth with @code{bye} also performs a
 8376: @code{flush}.
 8377: 
 8378: In Gforth, @code{block} and @code{buffer} use a @i{direct-mapped}
 8379: algorithm to assign a block buffer to a block. That means that any
 8380: particular block can only be assigned to one specific block buffer,
 8381: called (for the particular operation) the @i{victim buffer}. If the
 8382: victim buffer is @i{unassigned} or @i{assigned-clean} it is allocated to
 8383: the new block immediately. If it is @i{assigned-dirty} its current
 8384: contents are written back to the blocks file on disk before it is
 8385: allocated to the new block.
 8386: 
 8387: Although no structure is imposed on the contents of a block, it is
 8388: traditional to display the contents as 16 lines each of 64 characters.  A
 8389: block provides a single, continuous stream of input (for example, it
 8390: acts as a single parse area) -- there are no end-of-line characters
 8391: within a block, and no end-of-file character at the end of a
 8392: block. There are two consequences of this:
 8393: 
 8394: @itemize @bullet
 8395: @item
 8396: The last character of one line wraps straight into the first character
 8397: of the following line
 8398: @item
 8399: The word @code{\} -- comment to end of line -- requires special
 8400: treatment; in the context of a block it causes all characters until the
 8401: end of the current 64-character ``line'' to be ignored.
 8402: @end itemize
 8403: 
 8404: In Gforth, when you use @code{block} with a non-existent block number,
 8405: the current blocks file will be extended to the appropriate size and the
 8406: block buffer will be initialised with spaces.
 8407: 
 8408: Gforth includes a simple block editor (type @code{use blocked.fb 0 list}
 8409: for details) but doesn't encourage the use of blocks; the mechanism is
 8410: only provided for backward compatibility -- ANS Forth requires blocks to
 8411: be available when files are.
 8412: 
 8413: Common techniques that are used when working with blocks include:
 8414: 
 8415: @itemize @bullet
 8416: @item
 8417: A screen editor that allows you to edit blocks without leaving the Forth
 8418: environment.
 8419: @item
 8420: Shadow screens; where every code block has an associated block
 8421: containing comments (for example: code in odd block numbers, comments in
 8422: even block numbers). Typically, the block editor provides a convenient
 8423: mechanism to toggle between code and comments.
 8424: @item
 8425: Load blocks; a single block (typically block 1) contains a number of
 8426: @code{thru} commands which @code{load} the whole of the application.
 8427: @end itemize
 8428: 
 8429: See Frank Sergeant's Pygmy Forth to see just how well blocks can be
 8430: integrated into a Forth programming environment.
 8431: 
 8432: @comment TODO what about errors on open-blocks?
 8433: 
 8434: doc-open-blocks
 8435: doc-use
 8436: doc-block-offset
 8437: doc-get-block-fid
 8438: doc-block-position
 8439: 
 8440: doc-list
 8441: doc-scr
 8442: 
 8443: doc---gforthman-block
 8444: doc-buffer
 8445: 
 8446: doc-empty-buffers
 8447: doc-empty-buffer
 8448: doc-update
 8449: doc-updated?
 8450: doc-save-buffers
 8451: doc-save-buffer
 8452: doc-flush
 8453: 
 8454: doc-load
 8455: doc-thru
 8456: doc-+load
 8457: doc-+thru
 8458: doc---gforthman--->
 8459: doc-block-included
 8460: 
 8461: 
 8462: @c -------------------------------------------------------------
 8463: @node Other I/O, Locals, Blocks, Words
 8464: @section Other I/O
 8465: @cindex I/O - keyboard and display
 8466: 
 8467: @menu
 8468: * Simple numeric output::       Predefined formats
 8469: * Formatted numeric output::    Formatted (pictured) output
 8470: * String Formats::              How Forth stores strings in memory
 8471: * Displaying characters and strings::  Other stuff
 8472: * Input::                       Input
 8473: * Pipes::                       How to create your own pipes
 8474: @end menu
 8475: 
 8476: @node Simple numeric output, Formatted numeric output, Other I/O, Other I/O
 8477: @subsection Simple numeric output
 8478: @cindex numeric output - simple/free-format
 8479: 
 8480: The simplest output functions are those that display numbers from the
 8481: data or floating-point stacks. Floating-point output is always displayed
 8482: using base 10. Numbers displayed from the data stack use the value stored
 8483: in @code{base}.
 8484: 
 8485: 
 8486: doc-.
 8487: doc-dec.
 8488: doc-hex.
 8489: doc-u.
 8490: doc-.r
 8491: doc-u.r
 8492: doc-d.
 8493: doc-ud.
 8494: doc-d.r
 8495: doc-ud.r
 8496: doc-f.
 8497: doc-fe.
 8498: doc-fs.
 8499: doc-f.rdp
 8500: 
 8501: Examples of printing the number 1234.5678E23 in the different floating-point output
 8502: formats are shown below:
 8503: 
 8504: @example
 8505: f. 123456779999999000000000000.
 8506: fe. 123.456779999999E24
 8507: fs. 1.23456779999999E26
 8508: @end example
 8509: 
 8510: 
 8511: @node Formatted numeric output, String Formats, Simple numeric output, Other I/O
 8512: @subsection Formatted numeric output
 8513: @cindex formatted numeric output
 8514: @cindex pictured numeric output
 8515: @cindex numeric output - formatted
 8516: 
 8517: Forth traditionally uses a technique called @dfn{pictured numeric
 8518: output} for formatted printing of integers.  In this technique, digits
 8519: are extracted from the number (using the current output radix defined by
 8520: @code{base}), converted to ASCII codes and appended to a string that is
 8521: built in a scratch-pad area of memory (@pxref{core-idef,
 8522: Implementation-defined options, Implementation-defined
 8523: options}). Arbitrary characters can be appended to the string during the
 8524: extraction process. The completed string is specified by an address
 8525: and length and can be manipulated (@code{TYPE}ed, copied, modified)
 8526: under program control.
 8527: 
 8528: All of the integer output words described in the previous section
 8529: (@pxref{Simple numeric output}) are implemented in Gforth using pictured
 8530: numeric output.
 8531: 
 8532: Three important things to remember about pictured numeric output:
 8533: 
 8534: @itemize @bullet
 8535: @item
 8536: It always operates on double-precision numbers; to display a
 8537: single-precision number, convert it first (for ways of doing this
 8538: @pxref{Double precision}).
 8539: @item
 8540: It always treats the double-precision number as though it were
 8541: unsigned. The examples below show ways of printing signed numbers.
 8542: @item
 8543: The string is built up from right to left; least significant digit first.
 8544: @end itemize
 8545: 
 8546: 
 8547: doc-<#
 8548: doc-<<#
 8549: doc-#
 8550: doc-#s
 8551: doc-hold
 8552: doc-sign
 8553: doc-#>
 8554: doc-#>>
 8555: 
 8556: doc-represent
 8557: doc-f>str-rdp
 8558: doc-f>buf-rdp
 8559: 
 8560: 
 8561: @noindent
 8562: Here are some examples of using pictured numeric output:
 8563: 
 8564: @example
 8565: : my-u. ( u -- )
 8566:   \ Simplest use of pns.. behaves like Standard u. 
 8567:   0              \ convert to unsigned double
 8568:   <<#            \ start conversion
 8569:   #s             \ convert all digits
 8570:   #>             \ complete conversion
 8571:   TYPE SPACE     \ display, with trailing space
 8572:   #>> ;          \ release hold area
 8573: 
 8574: : cents-only ( u -- )
 8575:   0              \ convert to unsigned double
 8576:   <<#            \ start conversion
 8577:   # #            \ convert two least-significant digits
 8578:   #>             \ complete conversion, discard other digits
 8579:   TYPE SPACE     \ display, with trailing space
 8580:   #>> ;          \ release hold area
 8581: 
 8582: : dollars-and-cents ( u -- )
 8583:   0              \ convert to unsigned double
 8584:   <<#            \ start conversion
 8585:   # #            \ convert two least-significant digits
 8586:   [char] . hold  \ insert decimal point
 8587:   #s             \ convert remaining digits
 8588:   [char] $ hold  \ append currency symbol
 8589:   #>             \ complete conversion
 8590:   TYPE SPACE     \ display, with trailing space
 8591:   #>> ;          \ release hold area
 8592: 
 8593: : my-. ( n -- )
 8594:   \ handling negatives.. behaves like Standard .
 8595:   s>d            \ convert to signed double
 8596:   swap over dabs \ leave sign byte followed by unsigned double
 8597:   <<#            \ start conversion
 8598:   #s             \ convert all digits
 8599:   rot sign       \ get at sign byte, append "-" if needed
 8600:   #>             \ complete conversion
 8601:   TYPE SPACE     \ display, with trailing space
 8602:   #>> ;          \ release hold area
 8603: 
 8604: : account. ( n -- )
 8605:   \ accountants don't like minus signs, they use parentheses
 8606:   \ for negative numbers
 8607:   s>d            \ convert to signed double
 8608:   swap over dabs \ leave sign byte followed by unsigned double
 8609:   <<#            \ start conversion
 8610:   2 pick         \ get copy of sign byte
 8611:   0< IF [char] ) hold THEN \ right-most character of output
 8612:   #s             \ convert all digits
 8613:   rot            \ get at sign byte
 8614:   0< IF [char] ( hold THEN
 8615:   #>             \ complete conversion
 8616:   TYPE SPACE     \ display, with trailing space
 8617:   #>> ;          \ release hold area
 8618: 
 8619: @end example
 8620: 
 8621: Here are some examples of using these words:
 8622: 
 8623: @example
 8624: 1 my-u. 1
 8625: hex -1 my-u. decimal FFFFFFFF
 8626: 1 cents-only 01
 8627: 1234 cents-only 34
 8628: 2 dollars-and-cents $0.02
 8629: 1234 dollars-and-cents $12.34
 8630: 123 my-. 123
 8631: -123 my. -123
 8632: 123 account. 123
 8633: -456 account. (456)
 8634: @end example
 8635: 
 8636: 
 8637: @node String Formats, Displaying characters and strings, Formatted numeric output, Other I/O
 8638: @subsection String Formats
 8639: @cindex strings - see character strings
 8640: @cindex character strings - formats
 8641: @cindex I/O - see character strings
 8642: @cindex counted strings
 8643: 
 8644: @c anton: this does not really belong here; maybe the memory section,
 8645: @c  or the principles chapter
 8646: 
 8647: Forth commonly uses two different methods for representing character
 8648: strings:
 8649: 
 8650: @itemize @bullet
 8651: @item
 8652: @cindex address of counted string
 8653: @cindex counted string
 8654: As a @dfn{counted string}, represented by a @i{c-addr}. The char
 8655: addressed by @i{c-addr} contains a character-count, @i{n}, of the
 8656: string and the string occupies the subsequent @i{n} char addresses in
 8657: memory.
 8658: @item
 8659: As cell pair on the stack; @i{c-addr u}, where @i{u} is the length
 8660: of the string in characters, and @i{c-addr} is the address of the
 8661: first byte of the string.
 8662: @end itemize
 8663: 
 8664: ANS Forth encourages the use of the second format when representing
 8665: strings.
 8666: 
 8667: 
 8668: doc-count
 8669: 
 8670: 
 8671: For words that move, copy and search for strings see @ref{Memory
 8672: Blocks}. For words that display characters and strings see
 8673: @ref{Displaying characters and strings}.
 8674: 
 8675: @node Displaying characters and strings, Input, String Formats, Other I/O
 8676: @subsection Displaying characters and strings
 8677: @cindex characters - compiling and displaying
 8678: @cindex character strings - compiling and displaying
 8679: 
 8680: This section starts with a glossary of Forth words and ends with a set
 8681: of examples.
 8682: 
 8683: 
 8684: doc-bl
 8685: doc-space
 8686: doc-spaces
 8687: doc-emit
 8688: doc-toupper
 8689: doc-."
 8690: doc-.(
 8691: doc-.\"
 8692: doc-type
 8693: doc-typewhite
 8694: doc-cr
 8695: @cindex cursor control
 8696: doc-at-xy
 8697: doc-page
 8698: doc-s"
 8699: doc-s\"
 8700: doc-c"
 8701: doc-char
 8702: doc-[char]
 8703: 
 8704: 
 8705: @noindent
 8706: As an example, consider the following text, stored in a file @file{test.fs}:
 8707: 
 8708: @example
 8709: .( text-1)
 8710: : my-word
 8711:   ." text-2" cr
 8712:   .( text-3)
 8713: ;
 8714: 
 8715: ." text-4"
 8716: 
 8717: : my-char
 8718:   [char] ALPHABET emit
 8719:   char emit
 8720: ;
 8721: @end example
 8722: 
 8723: When you load this code into Gforth, the following output is generated:
 8724: 
 8725: @example
 8726: @kbd{include test.fs @key{RET}} text-1text-3text-4 ok
 8727: @end example
 8728: 
 8729: @itemize @bullet
 8730: @item
 8731: Messages @code{text-1} and @code{text-3} are displayed because @code{.(} 
 8732: is an immediate word; it behaves in the same way whether it is used inside
 8733: or outside a colon definition.
 8734: @item
 8735: Message @code{text-4} is displayed because of Gforth's added interpretation
 8736: semantics for @code{."}.
 8737: @item
 8738: Message @code{text-2} is @i{not} displayed, because the text interpreter
 8739: performs the compilation semantics for @code{."} within the definition of
 8740: @code{my-word}.
 8741: @end itemize
 8742: 
 8743: Here are some examples of executing @code{my-word} and @code{my-char}:
 8744: 
 8745: @example
 8746: @kbd{my-word @key{RET}} text-2
 8747:  ok
 8748: @kbd{my-char fred @key{RET}} Af ok
 8749: @kbd{my-char jim @key{RET}} Aj ok
 8750: @end example
 8751: 
 8752: @itemize @bullet
 8753: @item
 8754: Message @code{text-2} is displayed because of the run-time behaviour of
 8755: @code{."}.
 8756: @item
 8757: @code{[char]} compiles the ``A'' from ``ALPHABET'' and puts its display code
 8758: on the stack at run-time. @code{emit} always displays the character
 8759: when @code{my-char} is executed.
 8760: @item
 8761: @code{char} parses a string at run-time and the second @code{emit} displays
 8762: the first character of the string.
 8763: @item
 8764: If you type @code{see my-char} you can see that @code{[char]} discarded
 8765: the text ``LPHABET'' and only compiled the display code for ``A'' into the
 8766: definition of @code{my-char}.
 8767: @end itemize
 8768: 
 8769: 
 8770: 
 8771: @node Input, Pipes, Displaying characters and strings, Other I/O
 8772: @subsection Input
 8773: @cindex input
 8774: @cindex I/O - see input
 8775: @cindex parsing a string
 8776: 
 8777: For ways of storing character strings in memory see @ref{String Formats}.
 8778: 
 8779: @comment TODO examples for >number >float accept key key? pad parse word refill
 8780: @comment then index them
 8781: 
 8782: 
 8783: doc-key
 8784: doc-key?
 8785: doc-ekey
 8786: doc-ekey?
 8787: doc-ekey>char
 8788: doc->number
 8789: doc->float
 8790: doc-accept
 8791: doc-edit-line
 8792: doc-pad
 8793: @comment obsolescent words..
 8794: doc-convert
 8795: doc-expect
 8796: doc-span
 8797: 
 8798: 
 8799: @node Pipes,  , Input, Other I/O
 8800: @subsection Pipes
 8801: @cindex pipes, creating your own
 8802: 
 8803: In addition to using Gforth in pipes created by other processes
 8804: (@pxref{Gforth in pipes}), you can create your own pipe with
 8805: @code{open-pipe}, and read from or write to it.
 8806: 
 8807: doc-open-pipe
 8808: doc-close-pipe
 8809: 
 8810: If you write to a pipe, Gforth can throw a @code{broken-pipe-error}; if
 8811: you don't catch this exception, Gforth will catch it and exit, usually
 8812: silently (@pxref{Gforth in pipes}).  Since you probably do not want
 8813: this, you should wrap a @code{catch} or @code{try} block around the code
 8814: from @code{open-pipe} to @code{close-pipe}, so you can deal with the
 8815: problem yourself, and then return to regular processing.
 8816: 
 8817: doc-broken-pipe-error
 8818: 
 8819: 
 8820: @c -------------------------------------------------------------
 8821: @node Locals, Structures, Other I/O, Words
 8822: @section Locals
 8823: @cindex locals
 8824: 
 8825: Local variables can make Forth programming more enjoyable and Forth
 8826: programs easier to read. Unfortunately, the locals of ANS Forth are
 8827: laden with restrictions. Therefore, we provide not only the ANS Forth
 8828: locals wordset, but also our own, more powerful locals wordset (we
 8829: implemented the ANS Forth locals wordset through our locals wordset).
 8830: 
 8831: The ideas in this section have also been published in M. Anton Ertl,
 8832: @cite{@uref{http://www.complang.tuwien.ac.at/papers/ertl94l.ps.gz,
 8833: Automatic Scoping of Local Variables}}, EuroForth '94.
 8834: 
 8835: @menu
 8836: * Gforth locals::               
 8837: * ANS Forth locals::            
 8838: @end menu
 8839: 
 8840: @node Gforth locals, ANS Forth locals, Locals, Locals
 8841: @subsection Gforth locals
 8842: @cindex Gforth locals
 8843: @cindex locals, Gforth style
 8844: 
 8845: Locals can be defined with
 8846: 
 8847: @example
 8848: @{ local1 local2 ... -- comment @}
 8849: @end example
 8850: or
 8851: @example
 8852: @{ local1 local2 ... @}
 8853: @end example
 8854: 
 8855: E.g.,
 8856: @example
 8857: : max @{ n1 n2 -- n3 @}
 8858:  n1 n2 > if
 8859:    n1
 8860:  else
 8861:    n2
 8862:  endif ;
 8863: @end example
 8864: 
 8865: The similarity of locals definitions with stack comments is intended. A
 8866: locals definition often replaces the stack comment of a word. The order
 8867: of the locals corresponds to the order in a stack comment and everything
 8868: after the @code{--} is really a comment.
 8869: 
 8870: This similarity has one disadvantage: It is too easy to confuse locals
 8871: declarations with stack comments, causing bugs and making them hard to
 8872: find. However, this problem can be avoided by appropriate coding
 8873: conventions: Do not use both notations in the same program. If you do,
 8874: they should be distinguished using additional means, e.g. by position.
 8875: 
 8876: @cindex types of locals
 8877: @cindex locals types
 8878: The name of the local may be preceded by a type specifier, e.g.,
 8879: @code{F:} for a floating point value:
 8880: 
 8881: @example
 8882: : CX* @{ F: Ar F: Ai F: Br F: Bi -- Cr Ci @}
 8883: \ complex multiplication
 8884:  Ar Br f* Ai Bi f* f-
 8885:  Ar Bi f* Ai Br f* f+ ;
 8886: @end example
 8887: 
 8888: @cindex flavours of locals
 8889: @cindex locals flavours
 8890: @cindex value-flavoured locals
 8891: @cindex variable-flavoured locals
 8892: Gforth currently supports cells (@code{W:}, @code{W^}), doubles
 8893: (@code{D:}, @code{D^}), floats (@code{F:}, @code{F^}) and characters
 8894: (@code{C:}, @code{C^}) in two flavours: a value-flavoured local (defined
 8895: with @code{W:}, @code{D:} etc.) produces its value and can be changed
 8896: with @code{TO}. A variable-flavoured local (defined with @code{W^} etc.)
 8897: produces its address (which becomes invalid when the variable's scope is
 8898: left). E.g., the standard word @code{emit} can be defined in terms of
 8899: @code{type} like this:
 8900: 
 8901: @example
 8902: : emit @{ C^ char* -- @}
 8903:     char* 1 type ;
 8904: @end example
 8905: 
 8906: @cindex default type of locals
 8907: @cindex locals, default type
 8908: A local without type specifier is a @code{W:} local. Both flavours of
 8909: locals are initialized with values from the data or FP stack.
 8910: 
 8911: Currently there is no way to define locals with user-defined data
 8912: structures, but we are working on it.
 8913: 
 8914: Gforth allows defining locals everywhere in a colon definition. This
 8915: poses the following questions:
 8916: 
 8917: @menu
 8918: * Where are locals visible by name?::  
 8919: * How long do locals live?::    
 8920: * Locals programming style::    
 8921: * Locals implementation::       
 8922: @end menu
 8923: 
 8924: @node Where are locals visible by name?, How long do locals live?, Gforth locals, Gforth locals
 8925: @subsubsection Where are locals visible by name?
 8926: @cindex locals visibility
 8927: @cindex visibility of locals
 8928: @cindex scope of locals
 8929: 
 8930: Basically, the answer is that locals are visible where you would expect
 8931: it in block-structured languages, and sometimes a little longer. If you
 8932: want to restrict the scope of a local, enclose its definition in
 8933: @code{SCOPE}...@code{ENDSCOPE}.
 8934: 
 8935: 
 8936: doc-scope
 8937: doc-endscope
 8938: 
 8939: 
 8940: These words behave like control structure words, so you can use them
 8941: with @code{CS-PICK} and @code{CS-ROLL} to restrict the scope in
 8942: arbitrary ways.
 8943: 
 8944: If you want a more exact answer to the visibility question, here's the
 8945: basic principle: A local is visible in all places that can only be
 8946: reached through the definition of the local@footnote{In compiler
 8947: construction terminology, all places dominated by the definition of the
 8948: local.}. In other words, it is not visible in places that can be reached
 8949: without going through the definition of the local. E.g., locals defined
 8950: in @code{IF}...@code{ENDIF} are visible until the @code{ENDIF}, locals
 8951: defined in @code{BEGIN}...@code{UNTIL} are visible after the
 8952: @code{UNTIL} (until, e.g., a subsequent @code{ENDSCOPE}).
 8953: 
 8954: The reasoning behind this solution is: We want to have the locals
 8955: visible as long as it is meaningful. The user can always make the
 8956: visibility shorter by using explicit scoping. In a place that can
 8957: only be reached through the definition of a local, the meaning of a
 8958: local name is clear. In other places it is not: How is the local
 8959: initialized at the control flow path that does not contain the
 8960: definition? Which local is meant, if the same name is defined twice in
 8961: two independent control flow paths?
 8962: 
 8963: This should be enough detail for nearly all users, so you can skip the
 8964: rest of this section. If you really must know all the gory details and
 8965: options, read on.
 8966: 
 8967: In order to implement this rule, the compiler has to know which places
 8968: are unreachable. It knows this automatically after @code{AHEAD},
 8969: @code{AGAIN}, @code{EXIT} and @code{LEAVE}; in other cases (e.g., after
 8970: most @code{THROW}s), you can use the word @code{UNREACHABLE} to tell the
 8971: compiler that the control flow never reaches that place. If
 8972: @code{UNREACHABLE} is not used where it could, the only consequence is
 8973: that the visibility of some locals is more limited than the rule above
 8974: says. If @code{UNREACHABLE} is used where it should not (i.e., if you
 8975: lie to the compiler), buggy code will be produced.
 8976: 
 8977: 
 8978: doc-unreachable
 8979: 
 8980: 
 8981: Another problem with this rule is that at @code{BEGIN}, the compiler
 8982: does not know which locals will be visible on the incoming
 8983: back-edge. All problems discussed in the following are due to this
 8984: ignorance of the compiler (we discuss the problems using @code{BEGIN}
 8985: loops as examples; the discussion also applies to @code{?DO} and other
 8986: loops). Perhaps the most insidious example is:
 8987: @example
 8988: AHEAD
 8989: BEGIN
 8990:   x
 8991: [ 1 CS-ROLL ] THEN
 8992:   @{ x @}
 8993:   ...
 8994: UNTIL
 8995: @end example
 8996: 
 8997: This should be legal according to the visibility rule. The use of
 8998: @code{x} can only be reached through the definition; but that appears
 8999: textually below the use.
 9000: 
 9001: From this example it is clear that the visibility rules cannot be fully
 9002: implemented without major headaches. Our implementation treats common
 9003: cases as advertised and the exceptions are treated in a safe way: The
 9004: compiler makes a reasonable guess about the locals visible after a
 9005: @code{BEGIN}; if it is too pessimistic, the
 9006: user will get a spurious error about the local not being defined; if the
 9007: compiler is too optimistic, it will notice this later and issue a
 9008: warning. In the case above the compiler would complain about @code{x}
 9009: being undefined at its use. You can see from the obscure examples in
 9010: this section that it takes quite unusual control structures to get the
 9011: compiler into trouble, and even then it will often do fine.
 9012: 
 9013: If the @code{BEGIN} is reachable from above, the most optimistic guess
 9014: is that all locals visible before the @code{BEGIN} will also be
 9015: visible after the @code{BEGIN}. This guess is valid for all loops that
 9016: are entered only through the @code{BEGIN}, in particular, for normal
 9017: @code{BEGIN}...@code{WHILE}...@code{REPEAT} and
 9018: @code{BEGIN}...@code{UNTIL} loops and it is implemented in our
 9019: compiler. When the branch to the @code{BEGIN} is finally generated by
 9020: @code{AGAIN} or @code{UNTIL}, the compiler checks the guess and
 9021: warns the user if it was too optimistic:
 9022: @example
 9023: IF
 9024:   @{ x @}
 9025: BEGIN
 9026:   \ x ? 
 9027: [ 1 cs-roll ] THEN
 9028:   ...
 9029: UNTIL
 9030: @end example
 9031: 
 9032: Here, @code{x} lives only until the @code{BEGIN}, but the compiler
 9033: optimistically assumes that it lives until the @code{THEN}. It notices
 9034: this difference when it compiles the @code{UNTIL} and issues a
 9035: warning. The user can avoid the warning, and make sure that @code{x}
 9036: is not used in the wrong area by using explicit scoping:
 9037: @example
 9038: IF
 9039:   SCOPE
 9040:   @{ x @}
 9041:   ENDSCOPE
 9042: BEGIN
 9043: [ 1 cs-roll ] THEN
 9044:   ...
 9045: UNTIL
 9046: @end example
 9047: 
 9048: Since the guess is optimistic, there will be no spurious error messages
 9049: about undefined locals.
 9050: 
 9051: If the @code{BEGIN} is not reachable from above (e.g., after
 9052: @code{AHEAD} or @code{EXIT}), the compiler cannot even make an
 9053: optimistic guess, as the locals visible after the @code{BEGIN} may be
 9054: defined later. Therefore, the compiler assumes that no locals are
 9055: visible after the @code{BEGIN}. However, the user can use
 9056: @code{ASSUME-LIVE} to make the compiler assume that the same locals are
 9057: visible at the BEGIN as at the point where the top control-flow stack
 9058: item was created.
 9059: 
 9060: 
 9061: doc-assume-live
 9062: 
 9063: 
 9064: @noindent
 9065: E.g.,
 9066: @example
 9067: @{ x @}
 9068: AHEAD
 9069: ASSUME-LIVE
 9070: BEGIN
 9071:   x
 9072: [ 1 CS-ROLL ] THEN
 9073:   ...
 9074: UNTIL
 9075: @end example
 9076: 
 9077: Other cases where the locals are defined before the @code{BEGIN} can be
 9078: handled by inserting an appropriate @code{CS-ROLL} before the
 9079: @code{ASSUME-LIVE} (and changing the control-flow stack manipulation
 9080: behind the @code{ASSUME-LIVE}).
 9081: 
 9082: Cases where locals are defined after the @code{BEGIN} (but should be
 9083: visible immediately after the @code{BEGIN}) can only be handled by
 9084: rearranging the loop. E.g., the ``most insidious'' example above can be
 9085: arranged into:
 9086: @example
 9087: BEGIN
 9088:   @{ x @}
 9089:   ... 0=
 9090: WHILE
 9091:   x
 9092: REPEAT
 9093: @end example
 9094: 
 9095: @node How long do locals live?, Locals programming style, Where are locals visible by name?, Gforth locals
 9096: @subsubsection How long do locals live?
 9097: @cindex locals lifetime
 9098: @cindex lifetime of locals
 9099: 
 9100: The right answer for the lifetime question would be: A local lives at
 9101: least as long as it can be accessed. For a value-flavoured local this
 9102: means: until the end of its visibility. However, a variable-flavoured
 9103: local could be accessed through its address far beyond its visibility
 9104: scope. Ultimately, this would mean that such locals would have to be
 9105: garbage collected. Since this entails un-Forth-like implementation
 9106: complexities, I adopted the same cowardly solution as some other
 9107: languages (e.g., C): The local lives only as long as it is visible;
 9108: afterwards its address is invalid (and programs that access it
 9109: afterwards are erroneous).
 9110: 
 9111: @node Locals programming style, Locals implementation, How long do locals live?, Gforth locals
 9112: @subsubsection Locals programming style
 9113: @cindex locals programming style
 9114: @cindex programming style, locals
 9115: 
 9116: The freedom to define locals anywhere has the potential to change
 9117: programming styles dramatically. In particular, the need to use the
 9118: return stack for intermediate storage vanishes. Moreover, all stack
 9119: manipulations (except @code{PICK}s and @code{ROLL}s with run-time
 9120: determined arguments) can be eliminated: If the stack items are in the
 9121: wrong order, just write a locals definition for all of them; then
 9122: write the items in the order you want.
 9123: 
 9124: This seems a little far-fetched and eliminating stack manipulations is
 9125: unlikely to become a conscious programming objective. Still, the number
 9126: of stack manipulations will be reduced dramatically if local variables
 9127: are used liberally (e.g., compare @code{max} (@pxref{Gforth locals}) with
 9128: a traditional implementation of @code{max}).
 9129: 
 9130: This shows one potential benefit of locals: making Forth programs more
 9131: readable. Of course, this benefit will only be realized if the
 9132: programmers continue to honour the principle of factoring instead of
 9133: using the added latitude to make the words longer.
 9134: 
 9135: @cindex single-assignment style for locals
 9136: Using @code{TO} can and should be avoided.  Without @code{TO},
 9137: every value-flavoured local has only a single assignment and many
 9138: advantages of functional languages apply to Forth. I.e., programs are
 9139: easier to analyse, to optimize and to read: It is clear from the
 9140: definition what the local stands for, it does not turn into something
 9141: different later.
 9142: 
 9143: E.g., a definition using @code{TO} might look like this:
 9144: @example
 9145: : strcmp @{ addr1 u1 addr2 u2 -- n @}
 9146:  u1 u2 min 0
 9147:  ?do
 9148:    addr1 c@@ addr2 c@@ -
 9149:    ?dup-if
 9150:      unloop exit
 9151:    then
 9152:    addr1 char+ TO addr1
 9153:    addr2 char+ TO addr2
 9154:  loop
 9155:  u1 u2 - ;
 9156: @end example
 9157: Here, @code{TO} is used to update @code{addr1} and @code{addr2} at
 9158: every loop iteration. @code{strcmp} is a typical example of the
 9159: readability problems of using @code{TO}. When you start reading
 9160: @code{strcmp}, you think that @code{addr1} refers to the start of the
 9161: string. Only near the end of the loop you realize that it is something
 9162: else.
 9163: 
 9164: This can be avoided by defining two locals at the start of the loop that
 9165: are initialized with the right value for the current iteration.
 9166: @example
 9167: : strcmp @{ addr1 u1 addr2 u2 -- n @}
 9168:  addr1 addr2
 9169:  u1 u2 min 0 
 9170:  ?do @{ s1 s2 @}
 9171:    s1 c@@ s2 c@@ -
 9172:    ?dup-if
 9173:      unloop exit
 9174:    then
 9175:    s1 char+ s2 char+
 9176:  loop
 9177:  2drop
 9178:  u1 u2 - ;
 9179: @end example
 9180: Here it is clear from the start that @code{s1} has a different value
 9181: in every loop iteration.
 9182: 
 9183: @node Locals implementation,  , Locals programming style, Gforth locals
 9184: @subsubsection Locals implementation
 9185: @cindex locals implementation
 9186: @cindex implementation of locals
 9187: 
 9188: @cindex locals stack
 9189: Gforth uses an extra locals stack. The most compelling reason for
 9190: this is that the return stack is not float-aligned; using an extra stack
 9191: also eliminates the problems and restrictions of using the return stack
 9192: as locals stack. Like the other stacks, the locals stack grows toward
 9193: lower addresses. A few primitives allow an efficient implementation:
 9194: 
 9195: 
 9196: doc-@local#
 9197: doc-f@local#
 9198: doc-laddr#
 9199: doc-lp+!#
 9200: doc-lp!
 9201: doc->l
 9202: doc-f>l
 9203: 
 9204: 
 9205: In addition to these primitives, some specializations of these
 9206: primitives for commonly occurring inline arguments are provided for
 9207: efficiency reasons, e.g., @code{@@local0} as specialization of
 9208: @code{@@local#} for the inline argument 0. The following compiling words
 9209: compile the right specialized version, or the general version, as
 9210: appropriate:
 9211: 
 9212: 
 9213: @c doc-compile-@local
 9214: @c doc-compile-f@local
 9215: doc-compile-lp+!
 9216: 
 9217: 
 9218: Combinations of conditional branches and @code{lp+!#} like
 9219: @code{?branch-lp+!#} (the locals pointer is only changed if the branch
 9220: is taken) are provided for efficiency and correctness in loops.
 9221: 
 9222: A special area in the dictionary space is reserved for keeping the
 9223: local variable names. @code{@{} switches the dictionary pointer to this
 9224: area and @code{@}} switches it back and generates the locals
 9225: initializing code. @code{W:} etc.@ are normal defining words. This
 9226: special area is cleared at the start of every colon definition.
 9227: 
 9228: @cindex word list for defining locals
 9229: A special feature of Gforth's dictionary is used to implement the
 9230: definition of locals without type specifiers: every word list (aka
 9231: vocabulary) has its own methods for searching
 9232: etc. (@pxref{Word Lists}). For the present purpose we defined a word list
 9233: with a special search method: When it is searched for a word, it
 9234: actually creates that word using @code{W:}. @code{@{} changes the search
 9235: order to first search the word list containing @code{@}}, @code{W:} etc.,
 9236: and then the word list for defining locals without type specifiers.
 9237: 
 9238: The lifetime rules support a stack discipline within a colon
 9239: definition: The lifetime of a local is either nested with other locals
 9240: lifetimes or it does not overlap them.
 9241: 
 9242: At @code{BEGIN}, @code{IF}, and @code{AHEAD} no code for locals stack
 9243: pointer manipulation is generated. Between control structure words
 9244: locals definitions can push locals onto the locals stack. @code{AGAIN}
 9245: is the simplest of the other three control flow words. It has to
 9246: restore the locals stack depth of the corresponding @code{BEGIN}
 9247: before branching. The code looks like this:
 9248: @format
 9249: @code{lp+!#} current-locals-size @minus{} dest-locals-size
 9250: @code{branch} <begin>
 9251: @end format
 9252: 
 9253: @code{UNTIL} is a little more complicated: If it branches back, it
 9254: must adjust the stack just like @code{AGAIN}. But if it falls through,
 9255: the locals stack must not be changed. The compiler generates the
 9256: following code:
 9257: @format
 9258: @code{?branch-lp+!#} <begin> current-locals-size @minus{} dest-locals-size
 9259: @end format
 9260: The locals stack pointer is only adjusted if the branch is taken.
 9261: 
 9262: @code{THEN} can produce somewhat inefficient code:
 9263: @format
 9264: @code{lp+!#} current-locals-size @minus{} orig-locals-size
 9265: <orig target>:
 9266: @code{lp+!#} orig-locals-size @minus{} new-locals-size
 9267: @end format
 9268: The second @code{lp+!#} adjusts the locals stack pointer from the
 9269: level at the @i{orig} point to the level after the @code{THEN}. The
 9270: first @code{lp+!#} adjusts the locals stack pointer from the current
 9271: level to the level at the orig point, so the complete effect is an
 9272: adjustment from the current level to the right level after the
 9273: @code{THEN}.
 9274: 
 9275: @cindex locals information on the control-flow stack
 9276: @cindex control-flow stack items, locals information
 9277: In a conventional Forth implementation a dest control-flow stack entry
 9278: is just the target address and an orig entry is just the address to be
 9279: patched. Our locals implementation adds a word list to every orig or dest
 9280: item. It is the list of locals visible (or assumed visible) at the point
 9281: described by the entry. Our implementation also adds a tag to identify
 9282: the kind of entry, in particular to differentiate between live and dead
 9283: (reachable and unreachable) orig entries.
 9284: 
 9285: A few unusual operations have to be performed on locals word lists:
 9286: 
 9287: 
 9288: doc-common-list
 9289: doc-sub-list?
 9290: doc-list-size
 9291: 
 9292: 
 9293: Several features of our locals word list implementation make these
 9294: operations easy to implement: The locals word lists are organised as
 9295: linked lists; the tails of these lists are shared, if the lists
 9296: contain some of the same locals; and the address of a name is greater
 9297: than the address of the names behind it in the list.
 9298: 
 9299: Another important implementation detail is the variable
 9300: @code{dead-code}. It is used by @code{BEGIN} and @code{THEN} to
 9301: determine if they can be reached directly or only through the branch
 9302: that they resolve. @code{dead-code} is set by @code{UNREACHABLE},
 9303: @code{AHEAD}, @code{EXIT} etc., and cleared at the start of a colon
 9304: definition, by @code{BEGIN} and usually by @code{THEN}.
 9305: 
 9306: Counted loops are similar to other loops in most respects, but
 9307: @code{LEAVE} requires special attention: It performs basically the same
 9308: service as @code{AHEAD}, but it does not create a control-flow stack
 9309: entry. Therefore the information has to be stored elsewhere;
 9310: traditionally, the information was stored in the target fields of the
 9311: branches created by the @code{LEAVE}s, by organizing these fields into a
 9312: linked list. Unfortunately, this clever trick does not provide enough
 9313: space for storing our extended control flow information. Therefore, we
 9314: introduce another stack, the leave stack. It contains the control-flow
 9315: stack entries for all unresolved @code{LEAVE}s.
 9316: 
 9317: Local names are kept until the end of the colon definition, even if
 9318: they are no longer visible in any control-flow path. In a few cases
 9319: this may lead to increased space needs for the locals name area, but
 9320: usually less than reclaiming this space would cost in code size.
 9321: 
 9322: 
 9323: @node ANS Forth locals,  , Gforth locals, Locals
 9324: @subsection ANS Forth locals
 9325: @cindex locals, ANS Forth style
 9326: 
 9327: The ANS Forth locals wordset does not define a syntax for locals, but
 9328: words that make it possible to define various syntaxes. One of the
 9329: possible syntaxes is a subset of the syntax we used in the Gforth locals
 9330: wordset, i.e.:
 9331: 
 9332: @example
 9333: @{ local1 local2 ... -- comment @}
 9334: @end example
 9335: @noindent
 9336: or
 9337: @example
 9338: @{ local1 local2 ... @}
 9339: @end example
 9340: 
 9341: The order of the locals corresponds to the order in a stack comment. The
 9342: restrictions are:
 9343: 
 9344: @itemize @bullet
 9345: @item
 9346: Locals can only be cell-sized values (no type specifiers are allowed).
 9347: @item
 9348: Locals can be defined only outside control structures.
 9349: @item
 9350: Locals can interfere with explicit usage of the return stack. For the
 9351: exact (and long) rules, see the standard. If you don't use return stack
 9352: accessing words in a definition using locals, you will be all right. The
 9353: purpose of this rule is to make locals implementation on the return
 9354: stack easier.
 9355: @item
 9356: The whole definition must be in one line.
 9357: @end itemize
 9358: 
 9359: Locals defined in ANS Forth behave like @code{VALUE}s
 9360: (@pxref{Values}). I.e., they are initialized from the stack. Using their
 9361: name produces their value. Their value can be changed using @code{TO}.
 9362: 
 9363: Since the syntax above is supported by Gforth directly, you need not do
 9364: anything to use it. If you want to port a program using this syntax to
 9365: another ANS Forth system, use @file{compat/anslocal.fs} to implement the
 9366: syntax on the other system.
 9367: 
 9368: Note that a syntax shown in the standard, section A.13 looks
 9369: similar, but is quite different in having the order of locals
 9370: reversed. Beware!
 9371: 
 9372: The ANS Forth locals wordset itself consists of one word:
 9373: 
 9374: doc-(local)
 9375: 
 9376: The ANS Forth locals extension wordset defines a syntax using
 9377: @code{locals|}, but it is so awful that we strongly recommend not to use
 9378: it. We have implemented this syntax to make porting to Gforth easy, but
 9379: do not document it here. The problem with this syntax is that the locals
 9380: are defined in an order reversed with respect to the standard stack
 9381: comment notation, making programs harder to read, and easier to misread
 9382: and miswrite. The only merit of this syntax is that it is easy to
 9383: implement using the ANS Forth locals wordset.
 9384: 
 9385: 
 9386: @c ----------------------------------------------------------
 9387: @node Structures, Object-oriented Forth, Locals, Words
 9388: @section  Structures
 9389: @cindex structures
 9390: @cindex records
 9391: 
 9392: This section presents the structure package that comes with Gforth. A
 9393: version of the package implemented in ANS Forth is available in
 9394: @file{compat/struct.fs}. This package was inspired by a posting on
 9395: comp.lang.forth in 1989 (unfortunately I don't remember, by whom;
 9396: possibly John Hayes). A version of this section has been published in
 9397: M. Anton Ertl,
 9398: @uref{http://www.complang.tuwien.ac.at/forth/objects/structs.html, Yet
 9399: Another Forth Structures Package}, Forth Dimensions 19(3), pages
 9400: 13--16. Marcel Hendrix provided helpful comments.
 9401: 
 9402: @menu
 9403: * Why explicit structure support?::  
 9404: * Structure Usage::             
 9405: * Structure Naming Convention::  
 9406: * Structure Implementation::    
 9407: * Structure Glossary::          
 9408: @end menu
 9409: 
 9410: @node Why explicit structure support?, Structure Usage, Structures, Structures
 9411: @subsection Why explicit structure support?
 9412: 
 9413: @cindex address arithmetic for structures
 9414: @cindex structures using address arithmetic
 9415: If we want to use a structure containing several fields, we could simply
 9416: reserve memory for it, and access the fields using address arithmetic
 9417: (@pxref{Address arithmetic}). As an example, consider a structure with
 9418: the following fields
 9419: 
 9420: @table @code
 9421: @item a
 9422: is a float
 9423: @item b
 9424: is a cell
 9425: @item c
 9426: is a float
 9427: @end table
 9428: 
 9429: Given the (float-aligned) base address of the structure we get the
 9430: address of the field
 9431: 
 9432: @table @code
 9433: @item a
 9434: without doing anything further.
 9435: @item b
 9436: with @code{float+}
 9437: @item c
 9438: with @code{float+ cell+ faligned}
 9439: @end table
 9440: 
 9441: It is easy to see that this can become quite tiring. 
 9442: 
 9443: Moreover, it is not very readable, because seeing a
 9444: @code{cell+} tells us neither which kind of structure is
 9445: accessed nor what field is accessed; we have to somehow infer the kind
 9446: of structure, and then look up in the documentation, which field of
 9447: that structure corresponds to that offset.
 9448: 
 9449: Finally, this kind of address arithmetic also causes maintenance
 9450: troubles: If you add or delete a field somewhere in the middle of the
 9451: structure, you have to find and change all computations for the fields
 9452: afterwards.
 9453: 
 9454: So, instead of using @code{cell+} and friends directly, how
 9455: about storing the offsets in constants:
 9456: 
 9457: @example
 9458: 0 constant a-offset
 9459: 0 float+ constant b-offset
 9460: 0 float+ cell+ faligned c-offset
 9461: @end example
 9462: 
 9463: Now we can get the address of field @code{x} with @code{x-offset
 9464: +}. This is much better in all respects. Of course, you still
 9465: have to change all later offset definitions if you add a field. You can
 9466: fix this by declaring the offsets in the following way:
 9467: 
 9468: @example
 9469: 0 constant a-offset
 9470: a-offset float+ constant b-offset
 9471: b-offset cell+ faligned constant c-offset
 9472: @end example
 9473: 
 9474: Since we always use the offsets with @code{+}, we could use a defining
 9475: word @code{cfield} that includes the @code{+} in the action of the
 9476: defined word:
 9477: 
 9478: @example
 9479: : cfield ( n "name" -- )
 9480:     create ,
 9481: does> ( name execution: addr1 -- addr2 )
 9482:     @@ + ;
 9483: 
 9484: 0 cfield a
 9485: 0 a float+ cfield b
 9486: 0 b cell+ faligned cfield c
 9487: @end example
 9488: 
 9489: Instead of @code{x-offset +}, we now simply write @code{x}.
 9490: 
 9491: The structure field words now can be used quite nicely. However,
 9492: their definition is still a bit cumbersome: We have to repeat the
 9493: name, the information about size and alignment is distributed before
 9494: and after the field definitions etc.  The structure package presented
 9495: here addresses these problems.
 9496: 
 9497: @node Structure Usage, Structure Naming Convention, Why explicit structure support?, Structures
 9498: @subsection Structure Usage
 9499: @cindex structure usage
 9500: 
 9501: @cindex @code{field} usage
 9502: @cindex @code{struct} usage
 9503: @cindex @code{end-struct} usage
 9504: You can define a structure for a (data-less) linked list with:
 9505: @example
 9506: struct
 9507:     cell% field list-next
 9508: end-struct list%
 9509: @end example
 9510: 
 9511: With the address of the list node on the stack, you can compute the
 9512: address of the field that contains the address of the next node with
 9513: @code{list-next}. E.g., you can determine the length of a list
 9514: with:
 9515: 
 9516: @example
 9517: : list-length ( list -- n )
 9518: \ "list" is a pointer to the first element of a linked list
 9519: \ "n" is the length of the list
 9520:     0 BEGIN ( list1 n1 )
 9521:         over
 9522:     WHILE ( list1 n1 )
 9523:         1+ swap list-next @@ swap
 9524:     REPEAT
 9525:     nip ;
 9526: @end example
 9527: 
 9528: You can reserve memory for a list node in the dictionary with
 9529: @code{list% %allot}, which leaves the address of the list node on the
 9530: stack. For the equivalent allocation on the heap you can use @code{list%
 9531: %alloc} (or, for an @code{allocate}-like stack effect (i.e., with ior),
 9532: use @code{list% %allocate}). You can get the the size of a list
 9533: node with @code{list% %size} and its alignment with @code{list%
 9534: %alignment}.
 9535: 
 9536: Note that in ANS Forth the body of a @code{create}d word is
 9537: @code{aligned} but not necessarily @code{faligned};
 9538: therefore, if you do a:
 9539: 
 9540: @example
 9541: create @emph{name} foo% %allot drop
 9542: @end example
 9543: 
 9544: @noindent
 9545: then the memory alloted for @code{foo%} is guaranteed to start at the
 9546: body of @code{@emph{name}} only if @code{foo%} contains only character,
 9547: cell and double fields.  Therefore, if your structure contains floats,
 9548: better use
 9549: 
 9550: @example
 9551: foo% %allot constant @emph{name}
 9552: @end example
 9553: 
 9554: @cindex structures containing structures
 9555: You can include a structure @code{foo%} as a field of
 9556: another structure, like this:
 9557: @example
 9558: struct
 9559: ...
 9560:     foo% field ...
 9561: ...
 9562: end-struct ...
 9563: @end example
 9564: 
 9565: @cindex structure extension
 9566: @cindex extended records
 9567: Instead of starting with an empty structure, you can extend an
 9568: existing structure. E.g., a plain linked list without data, as defined
 9569: above, is hardly useful; You can extend it to a linked list of integers,
 9570: like this:@footnote{This feature is also known as @emph{extended
 9571: records}. It is the main innovation in the Oberon language; in other
 9572: words, adding this feature to Modula-2 led Wirth to create a new
 9573: language, write a new compiler etc.  Adding this feature to Forth just
 9574: required a few lines of code.}
 9575: 
 9576: @example
 9577: list%
 9578:     cell% field intlist-int
 9579: end-struct intlist%
 9580: @end example
 9581: 
 9582: @code{intlist%} is a structure with two fields:
 9583: @code{list-next} and @code{intlist-int}.
 9584: 
 9585: @cindex structures containing arrays
 9586: You can specify an array type containing @emph{n} elements of
 9587: type @code{foo%} like this:
 9588: 
 9589: @example
 9590: foo% @emph{n} *
 9591: @end example
 9592: 
 9593: You can use this array type in any place where you can use a normal
 9594: type, e.g., when defining a @code{field}, or with
 9595: @code{%allot}.
 9596: 
 9597: @cindex first field optimization
 9598: The first field is at the base address of a structure and the word for
 9599: this field (e.g., @code{list-next}) actually does not change the address
 9600: on the stack. You may be tempted to leave it away in the interest of
 9601: run-time and space efficiency. This is not necessary, because the
 9602: structure package optimizes this case: If you compile a first-field
 9603: words, no code is generated. So, in the interest of readability and
 9604: maintainability you should include the word for the field when accessing
 9605: the field.
 9606: 
 9607: 
 9608: @node Structure Naming Convention, Structure Implementation, Structure Usage, Structures
 9609: @subsection Structure Naming Convention
 9610: @cindex structure naming convention
 9611: 
 9612: The field names that come to (my) mind are often quite generic, and,
 9613: if used, would cause frequent name clashes. E.g., many structures
 9614: probably contain a @code{counter} field. The structure names
 9615: that come to (my) mind are often also the logical choice for the names
 9616: of words that create such a structure.
 9617: 
 9618: Therefore, I have adopted the following naming conventions: 
 9619: 
 9620: @itemize @bullet
 9621: @cindex field naming convention
 9622: @item
 9623: The names of fields are of the form
 9624: @code{@emph{struct}-@emph{field}}, where
 9625: @code{@emph{struct}} is the basic name of the structure, and
 9626: @code{@emph{field}} is the basic name of the field. You can
 9627: think of field words as converting the (address of the)
 9628: structure into the (address of the) field.
 9629: 
 9630: @cindex structure naming convention
 9631: @item
 9632: The names of structures are of the form
 9633: @code{@emph{struct}%}, where
 9634: @code{@emph{struct}} is the basic name of the structure.
 9635: @end itemize
 9636: 
 9637: This naming convention does not work that well for fields of extended
 9638: structures; e.g., the integer list structure has a field
 9639: @code{intlist-int}, but has @code{list-next}, not
 9640: @code{intlist-next}.
 9641: 
 9642: @node Structure Implementation, Structure Glossary, Structure Naming Convention, Structures
 9643: @subsection Structure Implementation
 9644: @cindex structure implementation
 9645: @cindex implementation of structures
 9646: 
 9647: The central idea in the implementation is to pass the data about the
 9648: structure being built on the stack, not in some global
 9649: variable. Everything else falls into place naturally once this design
 9650: decision is made.
 9651: 
 9652: The type description on the stack is of the form @emph{align
 9653: size}. Keeping the size on the top-of-stack makes dealing with arrays
 9654: very simple.
 9655: 
 9656: @code{field} is a defining word that uses @code{Create}
 9657: and @code{DOES>}. The body of the field contains the offset
 9658: of the field, and the normal @code{DOES>} action is simply:
 9659: 
 9660: @example
 9661: @@ +
 9662: @end example
 9663: 
 9664: @noindent
 9665: i.e., add the offset to the address, giving the stack effect
 9666: @i{addr1 -- addr2} for a field.
 9667: 
 9668: @cindex first field optimization, implementation
 9669: This simple structure is slightly complicated by the optimization
 9670: for fields with offset 0, which requires a different
 9671: @code{DOES>}-part (because we cannot rely on there being
 9672: something on the stack if such a field is invoked during
 9673: compilation). Therefore, we put the different @code{DOES>}-parts
 9674: in separate words, and decide which one to invoke based on the
 9675: offset. For a zero offset, the field is basically a noop; it is
 9676: immediate, and therefore no code is generated when it is compiled.
 9677: 
 9678: @node Structure Glossary,  , Structure Implementation, Structures
 9679: @subsection Structure Glossary
 9680: @cindex structure glossary
 9681: 
 9682: 
 9683: doc-%align
 9684: doc-%alignment
 9685: doc-%alloc
 9686: doc-%allocate
 9687: doc-%allot
 9688: doc-cell%
 9689: doc-char%
 9690: doc-dfloat%
 9691: doc-double%
 9692: doc-end-struct
 9693: doc-field
 9694: doc-float%
 9695: doc-naligned
 9696: doc-sfloat%
 9697: doc-%size
 9698: doc-struct
 9699: 
 9700: 
 9701: @c -------------------------------------------------------------
 9702: @node Object-oriented Forth, Programming Tools, Structures, Words
 9703: @section Object-oriented Forth
 9704: 
 9705: Gforth comes with three packages for object-oriented programming:
 9706: @file{objects.fs}, @file{oof.fs}, and @file{mini-oof.fs}; none of them
 9707: is preloaded, so you have to @code{include} them before use. The most
 9708: important differences between these packages (and others) are discussed
 9709: in @ref{Comparison with other object models}. All packages are written
 9710: in ANS Forth and can be used with any other ANS Forth.
 9711: 
 9712: @menu
 9713: * Why object-oriented programming?::  
 9714: * Object-Oriented Terminology::  
 9715: * Objects::                     
 9716: * OOF::                         
 9717: * Mini-OOF::                    
 9718: * Comparison with other object models::  
 9719: @end menu
 9720: 
 9721: @c ----------------------------------------------------------------
 9722: @node Why object-oriented programming?, Object-Oriented Terminology, Object-oriented Forth, Object-oriented Forth
 9723: @subsection Why object-oriented programming?
 9724: @cindex object-oriented programming motivation
 9725: @cindex motivation for object-oriented programming
 9726: 
 9727: Often we have to deal with several data structures (@emph{objects}),
 9728: that have to be treated similarly in some respects, but differently in
 9729: others. Graphical objects are the textbook example: circles, triangles,
 9730: dinosaurs, icons, and others, and we may want to add more during program
 9731: development. We want to apply some operations to any graphical object,
 9732: e.g., @code{draw} for displaying it on the screen. However, @code{draw}
 9733: has to do something different for every kind of object.
 9734: @comment TODO add some other operations eg perimeter, area
 9735: @comment and tie in to concrete examples later..
 9736: 
 9737: We could implement @code{draw} as a big @code{CASE}
 9738: control structure that executes the appropriate code depending on the
 9739: kind of object to be drawn. This would be not be very elegant, and,
 9740: moreover, we would have to change @code{draw} every time we add
 9741: a new kind of graphical object (say, a spaceship).
 9742: 
 9743: What we would rather do is: When defining spaceships, we would tell
 9744: the system: ``Here's how you @code{draw} a spaceship; you figure
 9745: out the rest''.
 9746: 
 9747: This is the problem that all systems solve that (rightfully) call
 9748: themselves object-oriented; the object-oriented packages presented here
 9749: solve this problem (and not much else).
 9750: @comment TODO ?list properties of oo systems.. oo vs o-based?
 9751: 
 9752: @c ------------------------------------------------------------------------
 9753: @node Object-Oriented Terminology, Objects, Why object-oriented programming?, Object-oriented Forth
 9754: @subsection Object-Oriented Terminology
 9755: @cindex object-oriented terminology
 9756: @cindex terminology for object-oriented programming
 9757: 
 9758: This section is mainly for reference, so you don't have to understand
 9759: all of it right away.  The terminology is mainly Smalltalk-inspired.  In
 9760: short:
 9761: 
 9762: @table @emph
 9763: @cindex class
 9764: @item class
 9765: a data structure definition with some extras.
 9766: 
 9767: @cindex object
 9768: @item object
 9769: an instance of the data structure described by the class definition.
 9770: 
 9771: @cindex instance variables
 9772: @item instance variables
 9773: fields of the data structure.
 9774: 
 9775: @cindex selector
 9776: @cindex method selector
 9777: @cindex virtual function
 9778: @item selector
 9779: (or @emph{method selector}) a word (e.g.,
 9780: @code{draw}) that performs an operation on a variety of data
 9781: structures (classes). A selector describes @emph{what} operation to
 9782: perform. In C++ terminology: a (pure) virtual function.
 9783: 
 9784: @cindex method
 9785: @item method
 9786: the concrete definition that performs the operation
 9787: described by the selector for a specific class. A method specifies
 9788: @emph{how} the operation is performed for a specific class.
 9789: 
 9790: @cindex selector invocation
 9791: @cindex message send
 9792: @cindex invoking a selector
 9793: @item selector invocation
 9794: a call of a selector. One argument of the call (the TOS (top-of-stack))
 9795: is used for determining which method is used. In Smalltalk terminology:
 9796: a message (consisting of the selector and the other arguments) is sent
 9797: to the object.
 9798: 
 9799: @cindex receiving object
 9800: @item receiving object
 9801: the object used for determining the method executed by a selector
 9802: invocation. In the @file{objects.fs} model, it is the object that is on
 9803: the TOS when the selector is invoked. (@emph{Receiving} comes from
 9804: the Smalltalk @emph{message} terminology.)
 9805: 
 9806: @cindex child class
 9807: @cindex parent class
 9808: @cindex inheritance
 9809: @item child class
 9810: a class that has (@emph{inherits}) all properties (instance variables,
 9811: selectors, methods) from a @emph{parent class}. In Smalltalk
 9812: terminology: The subclass inherits from the superclass. In C++
 9813: terminology: The derived class inherits from the base class.
 9814: 
 9815: @end table
 9816: 
 9817: @c If you wonder about the message sending terminology, it comes from
 9818: @c a time when each object had it's own task and objects communicated via
 9819: @c message passing; eventually the Smalltalk developers realized that
 9820: @c they can do most things through simple (indirect) calls. They kept the
 9821: @c terminology.
 9822: 
 9823: @c --------------------------------------------------------------
 9824: @node Objects, OOF, Object-Oriented Terminology, Object-oriented Forth
 9825: @subsection The @file{objects.fs} model
 9826: @cindex objects
 9827: @cindex object-oriented programming
 9828: 
 9829: @cindex @file{objects.fs}
 9830: @cindex @file{oof.fs}
 9831: 
 9832: This section describes the @file{objects.fs} package. This material also
 9833: has been published in M. Anton Ertl,
 9834: @cite{@uref{http://www.complang.tuwien.ac.at/forth/objects/objects.html,
 9835: Yet Another Forth Objects Package}}, Forth Dimensions 19(2), pages
 9836: 37--43.
 9837: @c McKewan's and Zsoter's packages
 9838: 
 9839: This section assumes that you have read @ref{Structures}.
 9840: 
 9841: The techniques on which this model is based have been used to implement
 9842: the parser generator, Gray, and have also been used in Gforth for
 9843: implementing the various flavours of word lists (hashed or not,
 9844: case-sensitive or not, special-purpose word lists for locals etc.).
 9845: 
 9846: 
 9847: @menu
 9848: * Properties of the Objects model::  
 9849: * Basic Objects Usage::         
 9850: * The Objects base class::      
 9851: * Creating objects::            
 9852: * Object-Oriented Programming Style::  
 9853: * Class Binding::               
 9854: * Method conveniences::         
 9855: * Classes and Scoping::         
 9856: * Dividing classes::            
 9857: * Object Interfaces::           
 9858: * Objects Implementation::      
 9859: * Objects Glossary::            
 9860: @end menu
 9861: 
 9862: Marcel Hendrix provided helpful comments on this section.
 9863: 
 9864: @node Properties of the Objects model, Basic Objects Usage, Objects, Objects
 9865: @subsubsection Properties of the @file{objects.fs} model
 9866: @cindex @file{objects.fs} properties
 9867: 
 9868: @itemize @bullet
 9869: @item
 9870: It is straightforward to pass objects on the stack. Passing
 9871: selectors on the stack is a little less convenient, but possible.
 9872: 
 9873: @item
 9874: Objects are just data structures in memory, and are referenced by their
 9875: address. You can create words for objects with normal defining words
 9876: like @code{constant}. Likewise, there is no difference between instance
 9877: variables that contain objects and those that contain other data.
 9878: 
 9879: @item
 9880: Late binding is efficient and easy to use.
 9881: 
 9882: @item
 9883: It avoids parsing, and thus avoids problems with state-smartness
 9884: and reduced extensibility; for convenience there are a few parsing
 9885: words, but they have non-parsing counterparts. There are also a few
 9886: defining words that parse. This is hard to avoid, because all standard
 9887: defining words parse (except @code{:noname}); however, such
 9888: words are not as bad as many other parsing words, because they are not
 9889: state-smart.
 9890: 
 9891: @item
 9892: It does not try to incorporate everything. It does a few things and does
 9893: them well (IMO). In particular, this model was not designed to support
 9894: information hiding (although it has features that may help); you can use
 9895: a separate package for achieving this.
 9896: 
 9897: @item
 9898: It is layered; you don't have to learn and use all features to use this
 9899: model. Only a few features are necessary (@pxref{Basic Objects Usage},
 9900: @pxref{The Objects base class}, @pxref{Creating objects}.), the others
 9901: are optional and independent of each other.
 9902: 
 9903: @item
 9904: An implementation in ANS Forth is available.
 9905: 
 9906: @end itemize
 9907: 
 9908: 
 9909: @node Basic Objects Usage, The Objects base class, Properties of the Objects model, Objects
 9910: @subsubsection Basic @file{objects.fs} Usage
 9911: @cindex basic objects usage
 9912: @cindex objects, basic usage
 9913: 
 9914: You can define a class for graphical objects like this:
 9915: 
 9916: @cindex @code{class} usage
 9917: @cindex @code{end-class} usage
 9918: @cindex @code{selector} usage
 9919: @example
 9920: object class \ "object" is the parent class
 9921:   selector draw ( x y graphical -- )
 9922: end-class graphical
 9923: @end example
 9924: 
 9925: This code defines a class @code{graphical} with an
 9926: operation @code{draw}.  We can perform the operation
 9927: @code{draw} on any @code{graphical} object, e.g.:
 9928: 
 9929: @example
 9930: 100 100 t-rex draw
 9931: @end example
 9932: 
 9933: @noindent
 9934: where @code{t-rex} is a word (say, a constant) that produces a
 9935: graphical object.
 9936: 
 9937: @comment TODO add a 2nd operation eg perimeter.. and use for
 9938: @comment a concrete example
 9939: 
 9940: @cindex abstract class
 9941: How do we create a graphical object? With the present definitions,
 9942: we cannot create a useful graphical object. The class
 9943: @code{graphical} describes graphical objects in general, but not
 9944: any concrete graphical object type (C++ users would call it an
 9945: @emph{abstract class}); e.g., there is no method for the selector
 9946: @code{draw} in the class @code{graphical}.
 9947: 
 9948: For concrete graphical objects, we define child classes of the
 9949: class @code{graphical}, e.g.:
 9950: 
 9951: @cindex @code{overrides} usage
 9952: @cindex @code{field} usage in class definition
 9953: @example
 9954: graphical class \ "graphical" is the parent class
 9955:   cell% field circle-radius
 9956: 
 9957: :noname ( x y circle -- )
 9958:   circle-radius @@ draw-circle ;
 9959: overrides draw
 9960: 
 9961: :noname ( n-radius circle -- )
 9962:   circle-radius ! ;
 9963: overrides construct
 9964: 
 9965: end-class circle
 9966: @end example
 9967: 
 9968: Here we define a class @code{circle} as a child of @code{graphical},
 9969: with field @code{circle-radius} (which behaves just like a field
 9970: (@pxref{Structures}); it defines (using @code{overrides}) new methods
 9971: for the selectors @code{draw} and @code{construct} (@code{construct} is
 9972: defined in @code{object}, the parent class of @code{graphical}).
 9973: 
 9974: Now we can create a circle on the heap (i.e.,
 9975: @code{allocate}d memory) with:
 9976: 
 9977: @cindex @code{heap-new} usage
 9978: @example
 9979: 50 circle heap-new constant my-circle
 9980: @end example
 9981: 
 9982: @noindent
 9983: @code{heap-new} invokes @code{construct}, thus
 9984: initializing the field @code{circle-radius} with 50. We can draw
 9985: this new circle at (100,100) with:
 9986: 
 9987: @example
 9988: 100 100 my-circle draw
 9989: @end example
 9990: 
 9991: @cindex selector invocation, restrictions
 9992: @cindex class definition, restrictions
 9993: Note: You can only invoke a selector if the object on the TOS
 9994: (the receiving object) belongs to the class where the selector was
 9995: defined or one of its descendents; e.g., you can invoke
 9996: @code{draw} only for objects belonging to @code{graphical}
 9997: or its descendents (e.g., @code{circle}).  Immediately before
 9998: @code{end-class}, the search order has to be the same as
 9999: immediately after @code{class}.
10000: 
10001: @node The Objects base class, Creating objects, Basic Objects Usage, Objects
10002: @subsubsection The @file{object.fs} base class
10003: @cindex @code{object} class
10004: 
10005: When you define a class, you have to specify a parent class.  So how do
10006: you start defining classes? There is one class available from the start:
10007: @code{object}. It is ancestor for all classes and so is the
10008: only class that has no parent. It has two selectors: @code{construct}
10009: and @code{print}.
10010: 
10011: @node Creating objects, Object-Oriented Programming Style, The Objects base class, Objects
10012: @subsubsection Creating objects
10013: @cindex creating objects
10014: @cindex object creation
10015: @cindex object allocation options
10016: 
10017: @cindex @code{heap-new} discussion
10018: @cindex @code{dict-new} discussion
10019: @cindex @code{construct} discussion
10020: You can create and initialize an object of a class on the heap with
10021: @code{heap-new} ( ... class -- object ) and in the dictionary
10022: (allocation with @code{allot}) with @code{dict-new} (
10023: ... class -- object ). Both words invoke @code{construct}, which
10024: consumes the stack items indicated by "..." above.
10025: 
10026: @cindex @code{init-object} discussion
10027: @cindex @code{class-inst-size} discussion
10028: If you want to allocate memory for an object yourself, you can get its
10029: alignment and size with @code{class-inst-size 2@@} ( class --
10030: align size ). Once you have memory for an object, you can initialize
10031: it with @code{init-object} ( ... class object -- );
10032: @code{construct} does only a part of the necessary work.
10033: 
10034: @node Object-Oriented Programming Style, Class Binding, Creating objects, Objects
10035: @subsubsection Object-Oriented Programming Style
10036: @cindex object-oriented programming style
10037: @cindex programming style, object-oriented
10038: 
10039: This section is not exhaustive.
10040: 
10041: @cindex stack effects of selectors
10042: @cindex selectors and stack effects
10043: In general, it is a good idea to ensure that all methods for the
10044: same selector have the same stack effect: when you invoke a selector,
10045: you often have no idea which method will be invoked, so, unless all
10046: methods have the same stack effect, you will not know the stack effect
10047: of the selector invocation.
10048: 
10049: One exception to this rule is methods for the selector
10050: @code{construct}. We know which method is invoked, because we
10051: specify the class to be constructed at the same place. Actually, I
10052: defined @code{construct} as a selector only to give the users a
10053: convenient way to specify initialization. The way it is used, a
10054: mechanism different from selector invocation would be more natural
10055: (but probably would take more code and more space to explain).
10056: 
10057: @node Class Binding, Method conveniences, Object-Oriented Programming Style, Objects
10058: @subsubsection Class Binding
10059: @cindex class binding
10060: @cindex early binding
10061: 
10062: @cindex late binding
10063: Normal selector invocations determine the method at run-time depending
10064: on the class of the receiving object. This run-time selection is called
10065: @i{late binding}.
10066: 
10067: Sometimes it's preferable to invoke a different method. For example,
10068: you might want to use the simple method for @code{print}ing
10069: @code{object}s instead of the possibly long-winded @code{print} method
10070: of the receiver class. You can achieve this by replacing the invocation
10071: of @code{print} with:
10072: 
10073: @cindex @code{[bind]} usage
10074: @example
10075: [bind] object print
10076: @end example
10077: 
10078: @noindent
10079: in compiled code or:
10080: 
10081: @cindex @code{bind} usage
10082: @example
10083: bind object print
10084: @end example
10085: 
10086: @cindex class binding, alternative to
10087: @noindent
10088: in interpreted code. Alternatively, you can define the method with a
10089: name (e.g., @code{print-object}), and then invoke it through the
10090: name. Class binding is just a (often more convenient) way to achieve
10091: the same effect; it avoids name clutter and allows you to invoke
10092: methods directly without naming them first.
10093: 
10094: @cindex superclass binding
10095: @cindex parent class binding
10096: A frequent use of class binding is this: When we define a method
10097: for a selector, we often want the method to do what the selector does
10098: in the parent class, and a little more. There is a special word for
10099: this purpose: @code{[parent]}; @code{[parent]
10100: @emph{selector}} is equivalent to @code{[bind] @emph{parent
10101: selector}}, where @code{@emph{parent}} is the parent
10102: class of the current class. E.g., a method definition might look like:
10103: 
10104: @cindex @code{[parent]} usage
10105: @example
10106: :noname
10107:   dup [parent] foo \ do parent's foo on the receiving object
10108:   ... \ do some more
10109: ; overrides foo
10110: @end example
10111: 
10112: @cindex class binding as optimization
10113: In @cite{Object-oriented programming in ANS Forth} (Forth Dimensions,
10114: March 1997), Andrew McKewan presents class binding as an optimization
10115: technique. I recommend not using it for this purpose unless you are in
10116: an emergency. Late binding is pretty fast with this model anyway, so the
10117: benefit of using class binding is small; the cost of using class binding
10118: where it is not appropriate is reduced maintainability.
10119: 
10120: While we are at programming style questions: You should bind
10121: selectors only to ancestor classes of the receiving object. E.g., say,
10122: you know that the receiving object is of class @code{foo} or its
10123: descendents; then you should bind only to @code{foo} and its
10124: ancestors.
10125: 
10126: @node Method conveniences, Classes and Scoping, Class Binding, Objects
10127: @subsubsection Method conveniences
10128: @cindex method conveniences
10129: 
10130: In a method you usually access the receiving object pretty often.  If
10131: you define the method as a plain colon definition (e.g., with
10132: @code{:noname}), you may have to do a lot of stack
10133: gymnastics. To avoid this, you can define the method with @code{m:
10134: ... ;m}. E.g., you could define the method for
10135: @code{draw}ing a @code{circle} with
10136: 
10137: @cindex @code{this} usage
10138: @cindex @code{m:} usage
10139: @cindex @code{;m} usage
10140: @example
10141: m: ( x y circle -- )
10142:   ( x y ) this circle-radius @@ draw-circle ;m
10143: @end example
10144: 
10145: @cindex @code{exit} in @code{m: ... ;m}
10146: @cindex @code{exitm} discussion
10147: @cindex @code{catch} in @code{m: ... ;m}
10148: When this method is executed, the receiver object is removed from the
10149: stack; you can access it with @code{this} (admittedly, in this
10150: example the use of @code{m: ... ;m} offers no advantage). Note
10151: that I specify the stack effect for the whole method (i.e. including
10152: the receiver object), not just for the code between @code{m:}
10153: and @code{;m}. You cannot use @code{exit} in
10154: @code{m:...;m}; instead, use
10155: @code{exitm}.@footnote{Moreover, for any word that calls
10156: @code{catch} and was defined before loading
10157: @code{objects.fs}, you have to redefine it like I redefined
10158: @code{catch}: @code{: catch this >r catch r> to-this ;}}
10159: 
10160: @cindex @code{inst-var} usage
10161: You will frequently use sequences of the form @code{this
10162: @emph{field}} (in the example above: @code{this
10163: circle-radius}). If you use the field only in this way, you can
10164: define it with @code{inst-var} and eliminate the
10165: @code{this} before the field name. E.g., the @code{circle}
10166: class above could also be defined with:
10167: 
10168: @example
10169: graphical class
10170:   cell% inst-var radius
10171: 
10172: m: ( x y circle -- )
10173:   radius @@ draw-circle ;m
10174: overrides draw
10175: 
10176: m: ( n-radius circle -- )
10177:   radius ! ;m
10178: overrides construct
10179: 
10180: end-class circle
10181: @end example
10182: 
10183: @code{radius} can only be used in @code{circle} and its
10184: descendent classes and inside @code{m:...;m}.
10185: 
10186: @cindex @code{inst-value} usage
10187: You can also define fields with @code{inst-value}, which is
10188: to @code{inst-var} what @code{value} is to
10189: @code{variable}.  You can change the value of such a field with
10190: @code{[to-inst]}.  E.g., we could also define the class
10191: @code{circle} like this:
10192: 
10193: @example
10194: graphical class
10195:   inst-value radius
10196: 
10197: m: ( x y circle -- )
10198:   radius draw-circle ;m
10199: overrides draw
10200: 
10201: m: ( n-radius circle -- )
10202:   [to-inst] radius ;m
10203: overrides construct
10204: 
10205: end-class circle
10206: @end example
10207: 
10208: @c !! :m is easy to confuse with m:.  Another name would be better.
10209: 
10210: @c Finally, you can define named methods with @code{:m}.  One use of this
10211: @c feature is the definition of words that occur only in one class and are
10212: @c not intended to be overridden, but which still need method context
10213: @c (e.g., for accessing @code{inst-var}s).  Another use is for methods that
10214: @c would be bound frequently, if defined anonymously.
10215: 
10216: 
10217: @node Classes and Scoping, Dividing classes, Method conveniences, Objects
10218: @subsubsection Classes and Scoping
10219: @cindex classes and scoping
10220: @cindex scoping and classes
10221: 
10222: Inheritance is frequent, unlike structure extension. This exacerbates
10223: the problem with the field name convention (@pxref{Structure Naming
10224: Convention}): One always has to remember in which class the field was
10225: originally defined; changing a part of the class structure would require
10226: changes for renaming in otherwise unaffected code.
10227: 
10228: @cindex @code{inst-var} visibility
10229: @cindex @code{inst-value} visibility
10230: To solve this problem, I added a scoping mechanism (which was not in my
10231: original charter): A field defined with @code{inst-var} (or
10232: @code{inst-value}) is visible only in the class where it is defined and in
10233: the descendent classes of this class.  Using such fields only makes
10234: sense in @code{m:}-defined methods in these classes anyway.
10235: 
10236: This scoping mechanism allows us to use the unadorned field name,
10237: because name clashes with unrelated words become much less likely.
10238: 
10239: @cindex @code{protected} discussion
10240: @cindex @code{private} discussion
10241: Once we have this mechanism, we can also use it for controlling the
10242: visibility of other words: All words defined after
10243: @code{protected} are visible only in the current class and its
10244: descendents. @code{public} restores the compilation
10245: (i.e. @code{current}) word list that was in effect before. If you
10246: have several @code{protected}s without an intervening
10247: @code{public} or @code{set-current}, @code{public}
10248: will restore the compilation word list in effect before the first of
10249: these @code{protected}s.
10250: 
10251: @node Dividing classes, Object Interfaces, Classes and Scoping, Objects
10252: @subsubsection Dividing classes
10253: @cindex Dividing classes
10254: @cindex @code{methods}...@code{end-methods}
10255: 
10256: You may want to do the definition of methods separate from the
10257: definition of the class, its selectors, fields, and instance variables,
10258: i.e., separate the implementation from the definition.  You can do this
10259: in the following way:
10260: 
10261: @example
10262: graphical class
10263:   inst-value radius
10264: end-class circle
10265: 
10266: ... \ do some other stuff
10267: 
10268: circle methods \ now we are ready
10269: 
10270: m: ( x y circle -- )
10271:   radius draw-circle ;m
10272: overrides draw
10273: 
10274: m: ( n-radius circle -- )
10275:   [to-inst] radius ;m
10276: overrides construct
10277: 
10278: end-methods
10279: @end example
10280: 
10281: You can use several @code{methods}...@code{end-methods} sections.  The
10282: only things you can do to the class in these sections are: defining
10283: methods, and overriding the class's selectors.  You must not define new
10284: selectors or fields.
10285: 
10286: Note that you often have to override a selector before using it.  In
10287: particular, you usually have to override @code{construct} with a new
10288: method before you can invoke @code{heap-new} and friends.  E.g., you
10289: must not create a circle before the @code{overrides construct} sequence
10290: in the example above.
10291: 
10292: @node Object Interfaces, Objects Implementation, Dividing classes, Objects
10293: @subsubsection Object Interfaces
10294: @cindex object interfaces
10295: @cindex interfaces for objects
10296: 
10297: In this model you can only call selectors defined in the class of the
10298: receiving objects or in one of its ancestors. If you call a selector
10299: with a receiving object that is not in one of these classes, the
10300: result is undefined; if you are lucky, the program crashes
10301: immediately.
10302: 
10303: @cindex selectors common to hardly-related classes
10304: Now consider the case when you want to have a selector (or several)
10305: available in two classes: You would have to add the selector to a
10306: common ancestor class, in the worst case to @code{object}. You
10307: may not want to do this, e.g., because someone else is responsible for
10308: this ancestor class.
10309: 
10310: The solution for this problem is interfaces. An interface is a
10311: collection of selectors. If a class implements an interface, the
10312: selectors become available to the class and its descendents. A class
10313: can implement an unlimited number of interfaces. For the problem
10314: discussed above, we would define an interface for the selector(s), and
10315: both classes would implement the interface.
10316: 
10317: As an example, consider an interface @code{storage} for
10318: writing objects to disk and getting them back, and a class
10319: @code{foo} that implements it. The code would look like this:
10320: 
10321: @cindex @code{interface} usage
10322: @cindex @code{end-interface} usage
10323: @cindex @code{implementation} usage
10324: @example
10325: interface
10326:   selector write ( file object -- )
10327:   selector read1 ( file object -- )
10328: end-interface storage
10329: 
10330: bar class
10331:   storage implementation
10332: 
10333: ... overrides write
10334: ... overrides read1
10335: ...
10336: end-class foo
10337: @end example
10338: 
10339: @noindent
10340: (I would add a word @code{read} @i{( file -- object )} that uses
10341: @code{read1} internally, but that's beyond the point illustrated
10342: here.)
10343: 
10344: Note that you cannot use @code{protected} in an interface; and
10345: of course you cannot define fields.
10346: 
10347: In the Neon model, all selectors are available for all classes;
10348: therefore it does not need interfaces. The price you pay in this model
10349: is slower late binding, and therefore, added complexity to avoid late
10350: binding.
10351: 
10352: @node Objects Implementation, Objects Glossary, Object Interfaces, Objects
10353: @subsubsection @file{objects.fs} Implementation
10354: @cindex @file{objects.fs} implementation
10355: 
10356: @cindex @code{object-map} discussion
10357: An object is a piece of memory, like one of the data structures
10358: described with @code{struct...end-struct}. It has a field
10359: @code{object-map} that points to the method map for the object's
10360: class.
10361: 
10362: @cindex method map
10363: @cindex virtual function table
10364: The @emph{method map}@footnote{This is Self terminology; in C++
10365: terminology: virtual function table.} is an array that contains the
10366: execution tokens (@i{xt}s) of the methods for the object's class. Each
10367: selector contains an offset into a method map.
10368: 
10369: @cindex @code{selector} implementation, class
10370: @code{selector} is a defining word that uses
10371: @code{CREATE} and @code{DOES>}. The body of the
10372: selector contains the offset; the @code{DOES>} action for a
10373: class selector is, basically:
10374: 
10375: @example
10376: ( object addr ) @@ over object-map @@ + @@ execute
10377: @end example
10378: 
10379: Since @code{object-map} is the first field of the object, it
10380: does not generate any code. As you can see, calling a selector has a
10381: small, constant cost.
10382: 
10383: @cindex @code{current-interface} discussion
10384: @cindex class implementation and representation
10385: A class is basically a @code{struct} combined with a method
10386: map. During the class definition the alignment and size of the class
10387: are passed on the stack, just as with @code{struct}s, so
10388: @code{field} can also be used for defining class
10389: fields. However, passing more items on the stack would be
10390: inconvenient, so @code{class} builds a data structure in memory,
10391: which is accessed through the variable
10392: @code{current-interface}. After its definition is complete, the
10393: class is represented on the stack by a pointer (e.g., as parameter for
10394: a child class definition).
10395: 
10396: A new class starts off with the alignment and size of its parent,
10397: and a copy of the parent's method map. Defining new fields extends the
10398: size and alignment; likewise, defining new selectors extends the
10399: method map. @code{overrides} just stores a new @i{xt} in the method
10400: map at the offset given by the selector.
10401: 
10402: @cindex class binding, implementation
10403: Class binding just gets the @i{xt} at the offset given by the selector
10404: from the class's method map and @code{compile,}s (in the case of
10405: @code{[bind]}) it.
10406: 
10407: @cindex @code{this} implementation
10408: @cindex @code{catch} and @code{this}
10409: @cindex @code{this} and @code{catch}
10410: I implemented @code{this} as a @code{value}. At the
10411: start of an @code{m:...;m} method the old @code{this} is
10412: stored to the return stack and restored at the end; and the object on
10413: the TOS is stored @code{TO this}. This technique has one
10414: disadvantage: If the user does not leave the method via
10415: @code{;m}, but via @code{throw} or @code{exit},
10416: @code{this} is not restored (and @code{exit} may
10417: crash). To deal with the @code{throw} problem, I have redefined
10418: @code{catch} to save and restore @code{this}; the same
10419: should be done with any word that can catch an exception. As for
10420: @code{exit}, I simply forbid it (as a replacement, there is
10421: @code{exitm}).
10422: 
10423: @cindex @code{inst-var} implementation
10424: @code{inst-var} is just the same as @code{field}, with
10425: a different @code{DOES>} action:
10426: @example
10427: @@ this +
10428: @end example
10429: Similar for @code{inst-value}.
10430: 
10431: @cindex class scoping implementation
10432: Each class also has a word list that contains the words defined with
10433: @code{inst-var} and @code{inst-value}, and its protected
10434: words. It also has a pointer to its parent. @code{class} pushes
10435: the word lists of the class and all its ancestors onto the search order stack,
10436: and @code{end-class} drops them.
10437: 
10438: @cindex interface implementation
10439: An interface is like a class without fields, parent and protected
10440: words; i.e., it just has a method map. If a class implements an
10441: interface, its method map contains a pointer to the method map of the
10442: interface. The positive offsets in the map are reserved for class
10443: methods, therefore interface map pointers have negative
10444: offsets. Interfaces have offsets that are unique throughout the
10445: system, unlike class selectors, whose offsets are only unique for the
10446: classes where the selector is available (invokable).
10447: 
10448: This structure means that interface selectors have to perform one
10449: indirection more than class selectors to find their method. Their body
10450: contains the interface map pointer offset in the class method map, and
10451: the method offset in the interface method map. The
10452: @code{does>} action for an interface selector is, basically:
10453: 
10454: @example
10455: ( object selector-body )
10456: 2dup selector-interface @@ ( object selector-body object interface-offset )
10457: swap object-map @@ + @@ ( object selector-body map )
10458: swap selector-offset @@ + @@ execute
10459: @end example
10460: 
10461: where @code{object-map} and @code{selector-offset} are
10462: first fields and generate no code.
10463: 
10464: As a concrete example, consider the following code:
10465: 
10466: @example
10467: interface
10468:   selector if1sel1
10469:   selector if1sel2
10470: end-interface if1
10471: 
10472: object class
10473:   if1 implementation
10474:   selector cl1sel1
10475:   cell% inst-var cl1iv1
10476: 
10477: ' m1 overrides construct
10478: ' m2 overrides if1sel1
10479: ' m3 overrides if1sel2
10480: ' m4 overrides cl1sel2
10481: end-class cl1
10482: 
10483: create obj1 object dict-new drop
10484: create obj2 cl1    dict-new drop
10485: @end example
10486: 
10487: The data structure created by this code (including the data structure
10488: for @code{object}) is shown in the
10489: @uref{objects-implementation.eps,figure}, assuming a cell size of 4.
10490: @comment TODO add this diagram..
10491: 
10492: @node Objects Glossary,  , Objects Implementation, Objects
10493: @subsubsection @file{objects.fs} Glossary
10494: @cindex @file{objects.fs} Glossary
10495: 
10496: 
10497: doc---objects-bind
10498: doc---objects-<bind>
10499: doc---objects-bind'
10500: doc---objects-[bind]
10501: doc---objects-class
10502: doc---objects-class->map
10503: doc---objects-class-inst-size
10504: doc---objects-class-override!
10505: doc---objects-class-previous
10506: doc---objects-class>order
10507: doc---objects-construct
10508: doc---objects-current'
10509: doc---objects-[current]
10510: doc---objects-current-interface
10511: doc---objects-dict-new
10512: doc---objects-end-class
10513: doc---objects-end-class-noname
10514: doc---objects-end-interface
10515: doc---objects-end-interface-noname
10516: doc---objects-end-methods
10517: doc---objects-exitm
10518: doc---objects-heap-new
10519: doc---objects-implementation
10520: doc---objects-init-object
10521: doc---objects-inst-value
10522: doc---objects-inst-var
10523: doc---objects-interface
10524: doc---objects-m:
10525: doc---objects-:m
10526: doc---objects-;m
10527: doc---objects-method
10528: doc---objects-methods
10529: doc---objects-object
10530: doc---objects-overrides
10531: doc---objects-[parent]
10532: doc---objects-print
10533: doc---objects-protected
10534: doc---objects-public
10535: doc---objects-selector
10536: doc---objects-this
10537: doc---objects-<to-inst>
10538: doc---objects-[to-inst]
10539: doc---objects-to-this
10540: doc---objects-xt-new
10541: 
10542: 
10543: @c -------------------------------------------------------------
10544: @node OOF, Mini-OOF, Objects, Object-oriented Forth
10545: @subsection The @file{oof.fs} model
10546: @cindex oof
10547: @cindex object-oriented programming
10548: 
10549: @cindex @file{objects.fs}
10550: @cindex @file{oof.fs}
10551: 
10552: This section describes the @file{oof.fs} package.
10553: 
10554: The package described in this section has been used in bigFORTH since 1991, and
10555: used for two large applications: a chromatographic system used to
10556: create new medicaments, and a graphic user interface library (MINOS).
10557: 
10558: You can find a description (in German) of @file{oof.fs} in @cite{Object
10559: oriented bigFORTH} by Bernd Paysan, published in @cite{Vierte Dimension}
10560: 10(2), 1994.
10561: 
10562: @menu
10563: * Properties of the OOF model::  
10564: * Basic OOF Usage::             
10565: * The OOF base class::          
10566: * Class Declaration::           
10567: * Class Implementation::        
10568: @end menu
10569: 
10570: @node Properties of the OOF model, Basic OOF Usage, OOF, OOF
10571: @subsubsection Properties of the @file{oof.fs} model
10572: @cindex @file{oof.fs} properties
10573: 
10574: @itemize @bullet
10575: @item
10576: This model combines object oriented programming with information
10577: hiding. It helps you writing large application, where scoping is
10578: necessary, because it provides class-oriented scoping.
10579: 
10580: @item
10581: Named objects, object pointers, and object arrays can be created,
10582: selector invocation uses the ``object selector'' syntax. Selector invocation
10583: to objects and/or selectors on the stack is a bit less convenient, but
10584: possible.
10585: 
10586: @item
10587: Selector invocation and instance variable usage of the active object is
10588: straightforward, since both make use of the active object.
10589: 
10590: @item
10591: Late binding is efficient and easy to use.
10592: 
10593: @item
10594: State-smart objects parse selectors. However, extensibility is provided
10595: using a (parsing) selector @code{postpone} and a selector @code{'}.
10596: 
10597: @item
10598: An implementation in ANS Forth is available.
10599: 
10600: @end itemize
10601: 
10602: 
10603: @node Basic OOF Usage, The OOF base class, Properties of the OOF model, OOF
10604: @subsubsection Basic @file{oof.fs} Usage
10605: @cindex @file{oof.fs} usage
10606: 
10607: This section uses the same example as for @code{objects} (@pxref{Basic Objects Usage}).
10608: 
10609: You can define a class for graphical objects like this:
10610: 
10611: @cindex @code{class} usage
10612: @cindex @code{class;} usage
10613: @cindex @code{method} usage
10614: @example
10615: object class graphical \ "object" is the parent class
10616:   method draw ( x y graphical -- )
10617: class;
10618: @end example
10619: 
10620: This code defines a class @code{graphical} with an
10621: operation @code{draw}.  We can perform the operation
10622: @code{draw} on any @code{graphical} object, e.g.:
10623: 
10624: @example
10625: 100 100 t-rex draw
10626: @end example
10627: 
10628: @noindent
10629: where @code{t-rex} is an object or object pointer, created with e.g.
10630: @code{graphical : t-rex}.
10631: 
10632: @cindex abstract class
10633: How do we create a graphical object? With the present definitions,
10634: we cannot create a useful graphical object. The class
10635: @code{graphical} describes graphical objects in general, but not
10636: any concrete graphical object type (C++ users would call it an
10637: @emph{abstract class}); e.g., there is no method for the selector
10638: @code{draw} in the class @code{graphical}.
10639: 
10640: For concrete graphical objects, we define child classes of the
10641: class @code{graphical}, e.g.:
10642: 
10643: @example
10644: graphical class circle \ "graphical" is the parent class
10645:   cell var circle-radius
10646: how:
10647:   : draw ( x y -- )
10648:     circle-radius @@ draw-circle ;
10649: 
10650:   : init ( n-radius -- (
10651:     circle-radius ! ;
10652: class;
10653: @end example
10654: 
10655: Here we define a class @code{circle} as a child of @code{graphical},
10656: with a field @code{circle-radius}; it defines new methods for the
10657: selectors @code{draw} and @code{init} (@code{init} is defined in
10658: @code{object}, the parent class of @code{graphical}).
10659: 
10660: Now we can create a circle in the dictionary with:
10661: 
10662: @example
10663: 50 circle : my-circle
10664: @end example
10665: 
10666: @noindent
10667: @code{:} invokes @code{init}, thus initializing the field
10668: @code{circle-radius} with 50. We can draw this new circle at (100,100)
10669: with:
10670: 
10671: @example
10672: 100 100 my-circle draw
10673: @end example
10674: 
10675: @cindex selector invocation, restrictions
10676: @cindex class definition, restrictions
10677: Note: You can only invoke a selector if the receiving object belongs to
10678: the class where the selector was defined or one of its descendents;
10679: e.g., you can invoke @code{draw} only for objects belonging to
10680: @code{graphical} or its descendents (e.g., @code{circle}). The scoping
10681: mechanism will check if you try to invoke a selector that is not
10682: defined in this class hierarchy, so you'll get an error at compilation
10683: time.
10684: 
10685: 
10686: @node The OOF base class, Class Declaration, Basic OOF Usage, OOF
10687: @subsubsection The @file{oof.fs} base class
10688: @cindex @file{oof.fs} base class
10689: 
10690: When you define a class, you have to specify a parent class.  So how do
10691: you start defining classes? There is one class available from the start:
10692: @code{object}. You have to use it as ancestor for all classes. It is the
10693: only class that has no parent. Classes are also objects, except that
10694: they don't have instance variables; class manipulation such as
10695: inheritance or changing definitions of a class is handled through
10696: selectors of the class @code{object}.
10697: 
10698: @code{object} provides a number of selectors:
10699: 
10700: @itemize @bullet
10701: @item
10702: @code{class} for subclassing, @code{definitions} to add definitions
10703: later on, and @code{class?} to get type informations (is the class a
10704: subclass of the class passed on the stack?).
10705: 
10706: doc---object-class
10707: doc---object-definitions
10708: doc---object-class?
10709: 
10710: 
10711: @item
10712: @code{init} and @code{dispose} as constructor and destructor of the
10713: object. @code{init} is invocated after the object's memory is allocated,
10714: while @code{dispose} also handles deallocation. Thus if you redefine
10715: @code{dispose}, you have to call the parent's dispose with @code{super
10716: dispose}, too.
10717: 
10718: doc---object-init
10719: doc---object-dispose
10720: 
10721: 
10722: @item
10723: @code{new}, @code{new[]}, @code{:}, @code{ptr}, @code{asptr}, and
10724: @code{[]} to create named and unnamed objects and object arrays or
10725: object pointers.
10726: 
10727: doc---object-new
10728: doc---object-new[]
10729: doc---object-:
10730: doc---object-ptr
10731: doc---object-asptr
10732: doc---object-[]
10733: 
10734: 
10735: @item
10736: @code{::} and @code{super} for explicit scoping. You should use explicit
10737: scoping only for super classes or classes with the same set of instance
10738: variables. Explicitly-scoped selectors use early binding.
10739: 
10740: doc---object-::
10741: doc---object-super
10742: 
10743: 
10744: @item
10745: @code{self} to get the address of the object
10746: 
10747: doc---object-self
10748: 
10749: 
10750: @item
10751: @code{bind}, @code{bound}, @code{link}, and @code{is} to assign object
10752: pointers and instance defers.
10753: 
10754: doc---object-bind
10755: doc---object-bound
10756: doc---object-link
10757: doc---object-is
10758: 
10759: 
10760: @item
10761: @code{'} to obtain selector tokens, @code{send} to invocate selectors
10762: form the stack, and @code{postpone} to generate selector invocation code.
10763: 
10764: doc---object-'
10765: doc---object-postpone
10766: 
10767: 
10768: @item
10769: @code{with} and @code{endwith} to select the active object from the
10770: stack, and enable its scope. Using @code{with} and @code{endwith}
10771: also allows you to create code using selector @code{postpone} without being
10772: trapped by the state-smart objects.
10773: 
10774: doc---object-with
10775: doc---object-endwith
10776: 
10777: 
10778: @end itemize
10779: 
10780: @node Class Declaration, Class Implementation, The OOF base class, OOF
10781: @subsubsection Class Declaration
10782: @cindex class declaration
10783: 
10784: @itemize @bullet
10785: @item
10786: Instance variables
10787: 
10788: doc---oof-var
10789: 
10790: 
10791: @item
10792: Object pointers
10793: 
10794: doc---oof-ptr
10795: doc---oof-asptr
10796: 
10797: 
10798: @item
10799: Instance defers
10800: 
10801: doc---oof-defer
10802: 
10803: 
10804: @item
10805: Method selectors
10806: 
10807: doc---oof-early
10808: doc---oof-method
10809: 
10810: 
10811: @item
10812: Class-wide variables
10813: 
10814: doc---oof-static
10815: 
10816: 
10817: @item
10818: End declaration
10819: 
10820: doc---oof-how:
10821: doc---oof-class;
10822: 
10823: 
10824: @end itemize
10825: 
10826: @c -------------------------------------------------------------
10827: @node Class Implementation,  , Class Declaration, OOF
10828: @subsubsection Class Implementation
10829: @cindex class implementation
10830: 
10831: @c -------------------------------------------------------------
10832: @node Mini-OOF, Comparison with other object models, OOF, Object-oriented Forth
10833: @subsection The @file{mini-oof.fs} model
10834: @cindex mini-oof
10835: 
10836: Gforth's third object oriented Forth package is a 12-liner. It uses a
10837: mixture of the @file{objects.fs} and the @file{oof.fs} syntax,
10838: and reduces to the bare minimum of features. This is based on a posting
10839: of Bernd Paysan in comp.lang.forth.
10840: 
10841: @menu
10842: * Basic Mini-OOF Usage::        
10843: * Mini-OOF Example::            
10844: * Mini-OOF Implementation::     
10845: @end menu
10846: 
10847: @c -------------------------------------------------------------
10848: @node Basic Mini-OOF Usage, Mini-OOF Example, Mini-OOF, Mini-OOF
10849: @subsubsection Basic @file{mini-oof.fs} Usage
10850: @cindex mini-oof usage
10851: 
10852: There is a base class (@code{class}, which allocates one cell for the
10853: object pointer) plus seven other words: to define a method, a variable,
10854: a class; to end a class, to resolve binding, to allocate an object and
10855: to compile a class method.
10856: @comment TODO better description of the last one
10857: 
10858: 
10859: doc-object
10860: doc-method
10861: doc-var
10862: doc-class
10863: doc-end-class
10864: doc-defines
10865: doc-new
10866: doc-::
10867: 
10868: 
10869: 
10870: @c -------------------------------------------------------------
10871: @node Mini-OOF Example, Mini-OOF Implementation, Basic Mini-OOF Usage, Mini-OOF
10872: @subsubsection Mini-OOF Example
10873: @cindex mini-oof example
10874: 
10875: A short example shows how to use this package. This example, in slightly
10876: extended form, is supplied as @file{moof-exm.fs}
10877: @comment TODO could flesh this out with some comments from the Forthwrite article
10878: 
10879: @example
10880: object class
10881:   method init
10882:   method draw
10883: end-class graphical
10884: @end example
10885: 
10886: This code defines a class @code{graphical} with an
10887: operation @code{draw}.  We can perform the operation
10888: @code{draw} on any @code{graphical} object, e.g.:
10889: 
10890: @example
10891: 100 100 t-rex draw
10892: @end example
10893: 
10894: where @code{t-rex} is an object or object pointer, created with e.g.
10895: @code{graphical new Constant t-rex}.
10896: 
10897: For concrete graphical objects, we define child classes of the
10898: class @code{graphical}, e.g.:
10899: 
10900: @example
10901: graphical class
10902:   cell var circle-radius
10903: end-class circle \ "graphical" is the parent class
10904: 
10905: :noname ( x y -- )
10906:   circle-radius @@ draw-circle ; circle defines draw
10907: :noname ( r -- )
10908:   circle-radius ! ; circle defines init
10909: @end example
10910: 
10911: There is no implicit init method, so we have to define one. The creation
10912: code of the object now has to call init explicitely.
10913: 
10914: @example
10915: circle new Constant my-circle
10916: 50 my-circle init
10917: @end example
10918: 
10919: It is also possible to add a function to create named objects with
10920: automatic call of @code{init}, given that all objects have @code{init}
10921: on the same place:
10922: 
10923: @example
10924: : new: ( .. o "name" -- )
10925:     new dup Constant init ;
10926: 80 circle new: large-circle
10927: @end example
10928: 
10929: We can draw this new circle at (100,100) with:
10930: 
10931: @example
10932: 100 100 my-circle draw
10933: @end example
10934: 
10935: @node Mini-OOF Implementation,  , Mini-OOF Example, Mini-OOF
10936: @subsubsection @file{mini-oof.fs} Implementation
10937: 
10938: Object-oriented systems with late binding typically use a
10939: ``vtable''-approach: the first variable in each object is a pointer to a
10940: table, which contains the methods as function pointers. The vtable
10941: may also contain other information.
10942: 
10943: So first, let's declare selectors:
10944: 
10945: @example
10946: : method ( m v "name" -- m' v ) Create  over , swap cell+ swap
10947:   DOES> ( ... o -- ... ) @@ over @@ + @@ execute ;
10948: @end example
10949: 
10950: During selector declaration, the number of selectors and instance
10951: variables is on the stack (in address units). @code{method} creates one
10952: selector and increments the selector number. To execute a selector, it
10953: takes the object, fetches the vtable pointer, adds the offset, and
10954: executes the method @i{xt} stored there. Each selector takes the object
10955: it is invoked with as top of stack parameter; it passes the parameters
10956: (including the object) unchanged to the appropriate method which should
10957: consume that object.
10958: 
10959: Now, we also have to declare instance variables
10960: 
10961: @example
10962: : var ( m v size "name" -- m v' ) Create  over , +
10963:   DOES> ( o -- addr ) @@ + ;
10964: @end example
10965: 
10966: As before, a word is created with the current offset. Instance
10967: variables can have different sizes (cells, floats, doubles, chars), so
10968: all we do is take the size and add it to the offset. If your machine
10969: has alignment restrictions, put the proper @code{aligned} or
10970: @code{faligned} before the variable, to adjust the variable
10971: offset. That's why it is on the top of stack.
10972: 
10973: We need a starting point (the base object) and some syntactic sugar:
10974: 
10975: @example
10976: Create object  1 cells , 2 cells ,
10977: : class ( class -- class selectors vars ) dup 2@@ ;
10978: @end example
10979: 
10980: For inheritance, the vtable of the parent object has to be
10981: copied when a new, derived class is declared. This gives all the
10982: methods of the parent class, which can be overridden, though.
10983: 
10984: @example
10985: : end-class  ( class selectors vars "name" -- )
10986:   Create  here >r , dup , 2 cells ?DO ['] noop , 1 cells +LOOP
10987:   cell+ dup cell+ r> rot @@ 2 cells /string move ;
10988: @end example
10989: 
10990: The first line creates the vtable, initialized with
10991: @code{noop}s. The second line is the inheritance mechanism, it
10992: copies the xts from the parent vtable.
10993: 
10994: We still have no way to define new methods, let's do that now:
10995: 
10996: @example
10997: : defines ( xt class "name" -- ) ' >body @@ + ! ;
10998: @end example
10999: 
11000: To allocate a new object, we need a word, too:
11001: 
11002: @example
11003: : new ( class -- o )  here over @@ allot swap over ! ;
11004: @end example
11005: 
11006: Sometimes derived classes want to access the method of the
11007: parent object. There are two ways to achieve this with Mini-OOF:
11008: first, you could use named words, and second, you could look up the
11009: vtable of the parent object.
11010: 
11011: @example
11012: : :: ( class "name" -- ) ' >body @@ + @@ compile, ;
11013: @end example
11014: 
11015: 
11016: Nothing can be more confusing than a good example, so here is
11017: one. First let's declare a text object (called
11018: @code{button}), that stores text and position:
11019: 
11020: @example
11021: object class
11022:   cell var text
11023:   cell var len
11024:   cell var x
11025:   cell var y
11026:   method init
11027:   method draw
11028: end-class button
11029: @end example
11030: 
11031: @noindent
11032: Now, implement the two methods, @code{draw} and @code{init}:
11033: 
11034: @example
11035: :noname ( o -- )
11036:  >r r@@ x @@ r@@ y @@ at-xy  r@@ text @@ r> len @@ type ;
11037:  button defines draw
11038: :noname ( addr u o -- )
11039:  >r 0 r@@ x ! 0 r@@ y ! r@@ len ! r> text ! ;
11040:  button defines init
11041: @end example
11042: 
11043: @noindent
11044: To demonstrate inheritance, we define a class @code{bold-button}, with no
11045: new data and no new selectors:
11046: 
11047: @example
11048: button class
11049: end-class bold-button
11050: 
11051: : bold   27 emit ." [1m" ;
11052: : normal 27 emit ." [0m" ;
11053: @end example
11054: 
11055: @noindent
11056: The class @code{bold-button} has a different draw method to
11057: @code{button}, but the new method is defined in terms of the draw method
11058: for @code{button}:
11059: 
11060: @example
11061: :noname bold [ button :: draw ] normal ; bold-button defines draw
11062: @end example
11063: 
11064: @noindent
11065: Finally, create two objects and apply selectors:
11066: 
11067: @example
11068: button new Constant foo
11069: s" thin foo" foo init
11070: page
11071: foo draw
11072: bold-button new Constant bar
11073: s" fat bar" bar init
11074: 1 bar y !
11075: bar draw
11076: @end example
11077: 
11078: 
11079: @node Comparison with other object models,  , Mini-OOF, Object-oriented Forth
11080: @subsection Comparison with other object models
11081: @cindex comparison of object models
11082: @cindex object models, comparison
11083: 
11084: Many object-oriented Forth extensions have been proposed (@cite{A survey
11085: of object-oriented Forths} (SIGPLAN Notices, April 1996) by Bradford
11086: J. Rodriguez and W. F. S. Poehlman lists 17). This section discusses the
11087: relation of the object models described here to two well-known and two
11088: closely-related (by the use of method maps) models.  Andras Zsoter
11089: helped us with this section.
11090: 
11091: @cindex Neon model
11092: The most popular model currently seems to be the Neon model (see
11093: @cite{Object-oriented programming in ANS Forth} (Forth Dimensions, March
11094: 1997) by Andrew McKewan) but this model has a number of limitations
11095: @footnote{A longer version of this critique can be
11096: found in @cite{On Standardizing Object-Oriented Forth Extensions} (Forth
11097: Dimensions, May 1997) by Anton Ertl.}:
11098: 
11099: @itemize @bullet
11100: @item
11101: It uses a @code{@emph{selector object}} syntax, which makes it unnatural
11102: to pass objects on the stack.
11103: 
11104: @item
11105: It requires that the selector parses the input stream (at
11106: compile time); this leads to reduced extensibility and to bugs that are
11107: hard to find.
11108: 
11109: @item
11110: It allows using every selector on every object; this eliminates the
11111: need for interfaces, but makes it harder to create efficient
11112: implementations.
11113: @end itemize
11114: 
11115: @cindex Pountain's object-oriented model
11116: Another well-known publication is @cite{Object-Oriented Forth} (Academic
11117: Press, London, 1987) by Dick Pountain. However, it is not really about
11118: object-oriented programming, because it hardly deals with late
11119: binding. Instead, it focuses on features like information hiding and
11120: overloading that are characteristic of modular languages like Ada (83).
11121: 
11122: @cindex Zsoter's object-oriented model
11123: In @uref{http://www.forth.org/oopf.html, Does late binding have to be
11124: slow?} (Forth Dimensions 18(1) 1996, pages 31-35) Andras Zsoter
11125: describes a model that makes heavy use of an active object (like
11126: @code{this} in @file{objects.fs}): The active object is not only used
11127: for accessing all fields, but also specifies the receiving object of
11128: every selector invocation; you have to change the active object
11129: explicitly with @code{@{ ... @}}, whereas in @file{objects.fs} it
11130: changes more or less implicitly at @code{m: ... ;m}. Such a change at
11131: the method entry point is unnecessary with Zsoter's model, because the
11132: receiving object is the active object already. On the other hand, the
11133: explicit change is absolutely necessary in that model, because otherwise
11134: no one could ever change the active object. An ANS Forth implementation
11135: of this model is available through
11136: @uref{http://www.forth.org/oopf.html}.
11137: 
11138: @cindex @file{oof.fs}, differences to other models
11139: The @file{oof.fs} model combines information hiding and overloading
11140: resolution (by keeping names in various word lists) with object-oriented
11141: programming. It sets the active object implicitly on method entry, but
11142: also allows explicit changing (with @code{>o...o>} or with
11143: @code{with...endwith}). It uses parsing and state-smart objects and
11144: classes for resolving overloading and for early binding: the object or
11145: class parses the selector and determines the method from this. If the
11146: selector is not parsed by an object or class, it performs a call to the
11147: selector for the active object (late binding), like Zsoter's model.
11148: Fields are always accessed through the active object. The big
11149: disadvantage of this model is the parsing and the state-smartness, which
11150: reduces extensibility and increases the opportunities for subtle bugs;
11151: essentially, you are only safe if you never tick or @code{postpone} an
11152: object or class (Bernd disagrees, but I (Anton) am not convinced).
11153: 
11154: @cindex @file{mini-oof.fs}, differences to other models
11155: The @file{mini-oof.fs} model is quite similar to a very stripped-down
11156: version of the @file{objects.fs} model, but syntactically it is a
11157: mixture of the @file{objects.fs} and @file{oof.fs} models.
11158: 
11159: 
11160: @c -------------------------------------------------------------
11161: @node Programming Tools, Assembler and Code Words, Object-oriented Forth, Words
11162: @section Programming Tools
11163: @cindex programming tools
11164: 
11165: @c !! move this and assembler down below OO stuff.
11166: 
11167: @menu
11168: * Examining::                   
11169: * Forgetting words::            
11170: * Debugging::                   Simple and quick.
11171: * Assertions::                  Making your programs self-checking.
11172: * Singlestep Debugger::         Executing your program word by word.
11173: @end menu
11174: 
11175: @node Examining, Forgetting words, Programming Tools, Programming Tools
11176: @subsection Examining data and code
11177: @cindex examining data and code
11178: @cindex data examination
11179: @cindex code examination
11180: 
11181: The following words inspect the stack non-destructively:
11182: 
11183: doc-.s
11184: doc-f.s
11185: 
11186: There is a word @code{.r} but it does @i{not} display the return stack!
11187: It is used for formatted numeric output (@pxref{Simple numeric output}).
11188: 
11189: doc-depth
11190: doc-fdepth
11191: doc-clearstack
11192: 
11193: The following words inspect memory.
11194: 
11195: doc-?
11196: doc-dump
11197: 
11198: And finally, @code{see} allows to inspect code:
11199: 
11200: doc-see
11201: doc-xt-see
11202: doc-simple-see
11203: doc-simple-see-range
11204: 
11205: @node Forgetting words, Debugging, Examining, Programming Tools
11206: @subsection Forgetting words
11207: @cindex words, forgetting
11208: @cindex forgeting words
11209: 
11210: @c  anton: other, maybe better places for this subsection: Defining Words;
11211: @c  Dictionary allocation.  At least a reference should be there.
11212: 
11213: Forth allows you to forget words (and everything that was alloted in the
11214: dictonary after them) in a LIFO manner.
11215: 
11216: doc-marker
11217: 
11218: The most common use of this feature is during progam development: when
11219: you change a source file, forget all the words it defined and load it
11220: again (since you also forget everything defined after the source file
11221: was loaded, you have to reload that, too).  Note that effects like
11222: storing to variables and destroyed system words are not undone when you
11223: forget words.  With a system like Gforth, that is fast enough at
11224: starting up and compiling, I find it more convenient to exit and restart
11225: Gforth, as this gives me a clean slate.
11226: 
11227: Here's an example of using @code{marker} at the start of a source file
11228: that you are debugging; it ensures that you only ever have one copy of
11229: the file's definitions compiled at any time:
11230: 
11231: @example
11232: [IFDEF] my-code
11233:     my-code
11234: [ENDIF]
11235: 
11236: marker my-code
11237: init-included-files
11238: 
11239: \ .. definitions start here
11240: \ .
11241: \ .
11242: \ end
11243: @end example
11244: 
11245: 
11246: @node Debugging, Assertions, Forgetting words, Programming Tools
11247: @subsection Debugging
11248: @cindex debugging
11249: 
11250: Languages with a slow edit/compile/link/test development loop tend to
11251: require sophisticated tracing/stepping debuggers to facilate debugging.
11252: 
11253: A much better (faster) way in fast-compiling languages is to add
11254: printing code at well-selected places, let the program run, look at
11255: the output, see where things went wrong, add more printing code, etc.,
11256: until the bug is found.
11257: 
11258: The simple debugging aids provided in @file{debugs.fs}
11259: are meant to support this style of debugging.
11260: 
11261: The word @code{~~} prints debugging information (by default the source
11262: location and the stack contents). It is easy to insert. If you use Emacs
11263: it is also easy to remove (@kbd{C-x ~} in the Emacs Forth mode to
11264: query-replace them with nothing). The deferred words
11265: @code{printdebugdata} and @code{.debugline} control the output of
11266: @code{~~}. The default source location output format works well with
11267: Emacs' compilation mode, so you can step through the program at the
11268: source level using @kbd{C-x `} (the advantage over a stepping debugger
11269: is that you can step in any direction and you know where the crash has
11270: happened or where the strange data has occurred).
11271: 
11272: doc-~~
11273: doc-printdebugdata
11274: doc-.debugline
11275: 
11276: @cindex filenames in @code{~~} output
11277: @code{~~} (and assertions) will usually print the wrong file name if a
11278: marker is executed in the same file after their occurance.  They will
11279: print @samp{*somewhere*} as file name if a marker is executed in the
11280: same file before their occurance.
11281: 
11282: 
11283: @node Assertions, Singlestep Debugger, Debugging, Programming Tools
11284: @subsection Assertions
11285: @cindex assertions
11286: 
11287: It is a good idea to make your programs self-checking, especially if you
11288: make an assumption that may become invalid during maintenance (for
11289: example, that a certain field of a data structure is never zero). Gforth
11290: supports @dfn{assertions} for this purpose. They are used like this:
11291: 
11292: @example
11293: assert( @i{flag} )
11294: @end example
11295: 
11296: The code between @code{assert(} and @code{)} should compute a flag, that
11297: should be true if everything is alright and false otherwise. It should
11298: not change anything else on the stack. The overall stack effect of the
11299: assertion is @code{( -- )}. E.g.
11300: 
11301: @example
11302: assert( 1 1 + 2 = ) \ what we learn in school
11303: assert( dup 0<> ) \ assert that the top of stack is not zero
11304: assert( false ) \ this code should not be reached
11305: @end example
11306: 
11307: The need for assertions is different at different times. During
11308: debugging, we want more checking, in production we sometimes care more
11309: for speed. Therefore, assertions can be turned off, i.e., the assertion
11310: becomes a comment. Depending on the importance of an assertion and the
11311: time it takes to check it, you may want to turn off some assertions and
11312: keep others turned on. Gforth provides several levels of assertions for
11313: this purpose:
11314: 
11315: 
11316: doc-assert0(
11317: doc-assert1(
11318: doc-assert2(
11319: doc-assert3(
11320: doc-assert(
11321: doc-)
11322: 
11323: 
11324: The variable @code{assert-level} specifies the highest assertions that
11325: are turned on. I.e., at the default @code{assert-level} of one,
11326: @code{assert0(} and @code{assert1(} assertions perform checking, while
11327: @code{assert2(} and @code{assert3(} assertions are treated as comments.
11328: 
11329: The value of @code{assert-level} is evaluated at compile-time, not at
11330: run-time. Therefore you cannot turn assertions on or off at run-time;
11331: you have to set the @code{assert-level} appropriately before compiling a
11332: piece of code. You can compile different pieces of code at different
11333: @code{assert-level}s (e.g., a trusted library at level 1 and
11334: newly-written code at level 3).
11335: 
11336: 
11337: doc-assert-level
11338: 
11339: 
11340: If an assertion fails, a message compatible with Emacs' compilation mode
11341: is produced and the execution is aborted (currently with @code{ABORT"}.
11342: If there is interest, we will introduce a special throw code. But if you
11343: intend to @code{catch} a specific condition, using @code{throw} is
11344: probably more appropriate than an assertion).
11345: 
11346: @cindex filenames in assertion output
11347: Assertions (and @code{~~}) will usually print the wrong file name if a
11348: marker is executed in the same file after their occurance.  They will
11349: print @samp{*somewhere*} as file name if a marker is executed in the
11350: same file before their occurance.
11351: 
11352: Definitions in ANS Forth for these assertion words are provided
11353: in @file{compat/assert.fs}.
11354: 
11355: 
11356: @node Singlestep Debugger,  , Assertions, Programming Tools
11357: @subsection Singlestep Debugger
11358: @cindex singlestep Debugger
11359: @cindex debugging Singlestep
11360: 
11361: The singlestep debugger does not work in this release.
11362: 
11363: When you create a new word there's often the need to check whether it
11364: behaves correctly or not. You can do this by typing @code{dbg
11365: badword}. A debug session might look like this:
11366: 
11367: @example
11368: : badword 0 DO i . LOOP ;  ok
11369: 2 dbg badword 
11370: : badword  
11371: Scanning code...
11372: 
11373: Nesting debugger ready!
11374: 
11375: 400D4738  8049BC4 0              -> [ 2 ] 00002 00000 
11376: 400D4740  8049F68 DO             -> [ 0 ] 
11377: 400D4744  804A0C8 i              -> [ 1 ] 00000 
11378: 400D4748 400C5E60 .              -> 0 [ 0 ] 
11379: 400D474C  8049D0C LOOP           -> [ 0 ] 
11380: 400D4744  804A0C8 i              -> [ 1 ] 00001 
11381: 400D4748 400C5E60 .              -> 1 [ 0 ] 
11382: 400D474C  8049D0C LOOP           -> [ 0 ] 
11383: 400D4758  804B384 ;              ->  ok
11384: @end example
11385: 
11386: Each line displayed is one step. You always have to hit return to
11387: execute the next word that is displayed. If you don't want to execute
11388: the next word in a whole, you have to type @kbd{n} for @code{nest}. Here is
11389: an overview what keys are available:
11390: 
11391: @table @i
11392: 
11393: @item @key{RET}
11394: Next; Execute the next word.
11395: 
11396: @item n
11397: Nest; Single step through next word.
11398: 
11399: @item u
11400: Unnest; Stop debugging and execute rest of word. If we got to this word
11401: with nest, continue debugging with the calling word.
11402: 
11403: @item d
11404: Done; Stop debugging and execute rest.
11405: 
11406: @item s
11407: Stop; Abort immediately.
11408: 
11409: @end table
11410: 
11411: Debugging large application with this mechanism is very difficult, because
11412: you have to nest very deeply into the program before the interesting part
11413: begins. This takes a lot of time. 
11414: 
11415: To do it more directly put a @code{BREAK:} command into your source code.
11416: When program execution reaches @code{BREAK:} the single step debugger is
11417: invoked and you have all the features described above.
11418: 
11419: If you have more than one part to debug it is useful to know where the
11420: program has stopped at the moment. You can do this by the 
11421: @code{BREAK" string"} command. This behaves like @code{BREAK:} except that
11422: string is typed out when the ``breakpoint'' is reached.
11423: 
11424: 
11425: doc-dbg
11426: doc-break:
11427: doc-break"
11428: 
11429: 
11430: 
11431: @c -------------------------------------------------------------
11432: @node Assembler and Code Words, Threading Words, Programming Tools, Words
11433: @section Assembler and Code Words
11434: @cindex assembler
11435: @cindex code words
11436: 
11437: @menu
11438: * Code and ;code::              
11439: * Common Assembler::            Assembler Syntax
11440: * Common Disassembler::         
11441: * 386 Assembler::               Deviations and special cases
11442: * Alpha Assembler::             Deviations and special cases
11443: * MIPS assembler::              Deviations and special cases
11444: * Other assemblers::            How to write them
11445: @end menu
11446: 
11447: @node Code and ;code, Common Assembler, Assembler and Code Words, Assembler and Code Words
11448: @subsection @code{Code} and @code{;code}
11449: 
11450: Gforth provides some words for defining primitives (words written in
11451: machine code), and for defining the machine-code equivalent of
11452: @code{DOES>}-based defining words. However, the machine-independent
11453: nature of Gforth poses a few problems: First of all, Gforth runs on
11454: several architectures, so it can provide no standard assembler. What's
11455: worse is that the register allocation not only depends on the processor,
11456: but also on the @code{gcc} version and options used.
11457: 
11458: The words that Gforth offers encapsulate some system dependences (e.g.,
11459: the header structure), so a system-independent assembler may be used in
11460: Gforth. If you do not have an assembler, you can compile machine code
11461: directly with @code{,} and @code{c,}@footnote{This isn't portable,
11462: because these words emit stuff in @i{data} space; it works because
11463: Gforth has unified code/data spaces. Assembler isn't likely to be
11464: portable anyway.}.
11465: 
11466: 
11467: doc-assembler
11468: doc-init-asm
11469: doc-code
11470: doc-end-code
11471: doc-;code
11472: doc-flush-icache
11473: 
11474: 
11475: If @code{flush-icache} does not work correctly, @code{code} words
11476: etc. will not work (reliably), either.
11477: 
11478: The typical usage of these @code{code} words can be shown most easily by
11479: analogy to the equivalent high-level defining words:
11480: 
11481: @example
11482: : foo                              code foo
11483:    <high-level Forth words>              <assembler>
11484: ;                                  end-code
11485:                                 
11486: : bar                              : bar
11487:    <high-level Forth words>           <high-level Forth words>
11488:    CREATE                             CREATE
11489:       <high-level Forth words>           <high-level Forth words>
11490:    DOES>                              ;code
11491:       <high-level Forth words>           <assembler>
11492: ;                                  end-code
11493: @end example
11494: 
11495: @c anton: the following stuff is also in "Common Assembler", in less detail.
11496: 
11497: @cindex registers of the inner interpreter
11498: In the assembly code you will want to refer to the inner interpreter's
11499: registers (e.g., the data stack pointer) and you may want to use other
11500: registers for temporary storage. Unfortunately, the register allocation
11501: is installation-dependent.
11502: 
11503: In particular, @code{ip} (Forth instruction pointer) and @code{rp}
11504: (return stack pointer) may be in different places in @code{gforth} and
11505: @code{gforth-fast}, or different installations.  This means that you
11506: cannot write a @code{NEXT} routine that works reliably on both versions
11507: or different installations; so for doing @code{NEXT}, I recommend
11508: jumping to @code{' noop >code-address}, which contains nothing but a
11509: @code{NEXT}.
11510: 
11511: For general accesses to the inner interpreter's registers, the easiest
11512: solution is to use explicit register declarations (@pxref{Explicit Reg
11513: Vars, , Variables in Specified Registers, gcc.info, GNU C Manual}) for
11514: all of the inner interpreter's registers: You have to compile Gforth
11515: with @code{-DFORCE_REG} (configure option @code{--enable-force-reg}) and
11516: the appropriate declarations must be present in the @code{machine.h}
11517: file (see @code{mips.h} for an example; you can find a full list of all
11518: declarable register symbols with @code{grep register engine.c}). If you
11519: give explicit registers to all variables that are declared at the
11520: beginning of @code{engine()}, you should be able to use the other
11521: caller-saved registers for temporary storage. Alternatively, you can use
11522: the @code{gcc} option @code{-ffixed-REG} (@pxref{Code Gen Options, ,
11523: Options for Code Generation Conventions, gcc.info, GNU C Manual}) to
11524: reserve a register (however, this restriction on register allocation may
11525: slow Gforth significantly).
11526: 
11527: If this solution is not viable (e.g., because @code{gcc} does not allow
11528: you to explicitly declare all the registers you need), you have to find
11529: out by looking at the code where the inner interpreter's registers
11530: reside and which registers can be used for temporary storage. You can
11531: get an assembly listing of the engine's code with @code{make engine.s}.
11532: 
11533: In any case, it is good practice to abstract your assembly code from the
11534: actual register allocation. E.g., if the data stack pointer resides in
11535: register @code{$17}, create an alias for this register called @code{sp},
11536: and use that in your assembly code.
11537: 
11538: @cindex code words, portable
11539: Another option for implementing normal and defining words efficiently
11540: is to add the desired functionality to the source of Gforth. For normal
11541: words you just have to edit @file{primitives} (@pxref{Automatic
11542: Generation}). Defining words (equivalent to @code{;CODE} words, for fast
11543: defined words) may require changes in @file{engine.c}, @file{kernel.fs},
11544: @file{prims2x.fs}, and possibly @file{cross.fs}.
11545: 
11546: @node Common Assembler, Common Disassembler, Code and ;code, Assembler and Code Words
11547: @subsection Common Assembler
11548: 
11549: The assemblers in Gforth generally use a postfix syntax, i.e., the
11550: instruction name follows the operands.
11551: 
11552: The operands are passed in the usual order (the same that is used in the
11553: manual of the architecture).  Since they all are Forth words, they have
11554: to be separated by spaces; you can also use Forth words to compute the
11555: operands.
11556: 
11557: The instruction names usually end with a @code{,}.  This makes it easier
11558: to visually separate instructions if you put several of them on one
11559: line; it also avoids shadowing other Forth words (e.g., @code{and}).
11560: 
11561: Registers are usually specified by number; e.g., (decimal) @code{11}
11562: specifies registers R11 and F11 on the Alpha architecture (which one,
11563: depends on the instruction).  The usual names are also available, e.g.,
11564: @code{s2} for R11 on Alpha.
11565: 
11566: Control flow is specified similar to normal Forth code (@pxref{Arbitrary
11567: control structures}), with @code{if,}, @code{ahead,}, @code{then,},
11568: @code{begin,}, @code{until,}, @code{again,}, @code{cs-roll},
11569: @code{cs-pick}, @code{else,}, @code{while,}, and @code{repeat,}.  The
11570: conditions are specified in a way specific to each assembler.
11571: 
11572: Note that the register assignments of the Gforth engine can change
11573: between Gforth versions, or even between different compilations of the
11574: same Gforth version (e.g., if you use a different GCC version).  So if
11575: you want to refer to Gforth's registers (e.g., the stack pointer or
11576: TOS), I recommend defining your own words for refering to these
11577: registers, and using them later on; then you can easily adapt to a
11578: changed register assignment.  The stability of the register assignment
11579: is usually better if you build Gforth with @code{--enable-force-reg}.
11580: 
11581: The most common use of these registers is to dispatch to the next word
11582: (the @code{next} routine).  A portable way to do this is to jump to
11583: @code{' noop >code-address} (of course, this is less efficient than
11584: integrating the @code{next} code and scheduling it well).
11585: 
11586: Another difference between Gforth version is that the top of stack is
11587: kept in memory in @code{gforth} and, on most platforms, in a register in
11588: @code{gforth-fast}.
11589: 
11590: @node  Common Disassembler, 386 Assembler, Common Assembler, Assembler and Code Words
11591: @subsection Common Disassembler
11592: 
11593: You can disassemble a @code{code} word with @code{see}
11594: (@pxref{Debugging}).  You can disassemble a section of memory with
11595: 
11596: doc-disasm
11597: 
11598: The disassembler generally produces output that can be fed into the
11599: assembler (i.e., same syntax, etc.).  It also includes additional
11600: information in comments.  In particular, the address of the instruction
11601: is given in a comment before the instruction.
11602: 
11603: @code{See} may display more or less than the actual code of the word,
11604: because the recognition of the end of the code is unreliable.  You can
11605: use @code{disasm} if it did not display enough.  It may display more, if
11606: the code word is not immediately followed by a named word.  If you have
11607: something else there, you can follow the word with @code{align last @ ,}
11608: to ensure that the end is recognized.
11609: 
11610: @node 386 Assembler, Alpha Assembler, Common Disassembler, Assembler and Code Words
11611: @subsection 386 Assembler
11612: 
11613: The 386 assembler included in Gforth was written by Bernd Paysan, it's
11614: available under GPL, and originally part of bigFORTH.
11615: 
11616: The 386 disassembler included in Gforth was written by Andrew McKewan
11617: and is in the public domain.
11618: 
11619: The disassembler displays code in an Intel-like prefix syntax.
11620: 
11621: The assembler uses a postfix syntax with reversed parameters.
11622: 
11623: The assembler includes all instruction of the Athlon, i.e. 486 core
11624: instructions, Pentium and PPro extensions, floating point, MMX, 3Dnow!,
11625: but not ISSE. It's an integrated 16- and 32-bit assembler. Default is 32
11626: bit, you can switch to 16 bit with .86 and back to 32 bit with .386.
11627: 
11628: There are several prefixes to switch between different operation sizes,
11629: @code{.b} for byte accesses, @code{.w} for word accesses, @code{.d} for
11630: double-word accesses. Addressing modes can be switched with @code{.wa}
11631: for 16 bit addresses, and @code{.da} for 32 bit addresses. You don't
11632: need a prefix for byte register names (@code{AL} et al).
11633: 
11634: For floating point operations, the prefixes are @code{.fs} (IEEE
11635: single), @code{.fl} (IEEE double), @code{.fx} (extended), @code{.fw}
11636: (word), @code{.fd} (double-word), and @code{.fq} (quad-word).
11637: 
11638: The MMX opcodes don't have size prefixes, they are spelled out like in
11639: the Intel assembler. Instead of move from and to memory, there are
11640: PLDQ/PLDD and PSTQ/PSTD.
11641: 
11642: The registers lack the 'e' prefix; even in 32 bit mode, eax is called
11643: ax.  Immediate values are indicated by postfixing them with @code{#},
11644: e.g., @code{3 #}.  Here are some examples of addressing modes in various
11645: syntaxes:
11646: 
11647: @example
11648: Gforth          Intel (NASM)   AT&T (gas)      Name
11649: .w ax           ax             %ax             register (16 bit)
11650: ax              eax            %eax            register (32 bit)
11651: 3 #             offset 3       $3              immediate
11652: 1000 #)         byte ptr 1000  1000            displacement
11653: bx )            [ebx]          (%ebx)          base
11654: 100 di d)       100[edi]       100(%edi)       base+displacement
11655: 20 ax *4 i#)    20[eax*4]      20(,%eax,4)     (index*scale)+displacement
11656: di ax *4 i)     [edi][eax*4]   (%edi,%eax,4)   base+(index*scale)
11657: 4 bx cx di)     4[ebx][ecx]    4(%ebx,%ecx)    base+index+displacement
11658: 12 sp ax *2 di) 12[esp][eax*2] 12(%esp,%eax,2) base+(index*scale)+displacement
11659: @end example
11660: 
11661: You can use @code{L)} and @code{LI)} instead of @code{D)} and
11662: @code{DI)} to enforce 32-bit displacement fields (useful for
11663: later patching).
11664: 
11665: Some example of instructions are:
11666: 
11667: @example
11668: ax bx mov             \ move ebx,eax
11669: 3 # ax mov            \ mov eax,3
11670: 100 di ) ax mov       \ mov eax,100[edi]
11671: 4 bx cx di) ax mov    \ mov eax,4[ebx][ecx]
11672: .w ax bx mov          \ mov bx,ax
11673: @end example
11674: 
11675: The following forms are supported for binary instructions:
11676: 
11677: @example
11678: <reg> <reg> <inst>
11679: <n> # <reg> <inst>
11680: <mem> <reg> <inst>
11681: <reg> <mem> <inst>
11682: @end example
11683: 
11684: Immediate to memory is not supported.  The shift/rotate syntax is:
11685: 
11686: @example
11687: <reg/mem> 1 # shl \ shortens to shift without immediate
11688: <reg/mem> 4 # shl
11689: <reg/mem> cl shl
11690: @end example
11691: 
11692: Precede string instructions (@code{movs} etc.) with @code{.b} to get
11693: the byte version.
11694: 
11695: The control structure words @code{IF} @code{UNTIL} etc. must be preceded
11696: by one of these conditions: @code{vs vc u< u>= 0= 0<> u<= u> 0< 0>= ps
11697: pc < >= <= >}. (Note that most of these words shadow some Forth words
11698: when @code{assembler} is in front of @code{forth} in the search path,
11699: e.g., in @code{code} words).  Currently the control structure words use
11700: one stack item, so you have to use @code{roll} instead of @code{cs-roll}
11701: to shuffle them (you can also use @code{swap} etc.).
11702: 
11703: Here is an example of a @code{code} word (assumes that the stack pointer
11704: is in esi and the TOS is in ebx):
11705: 
11706: @example
11707: code my+ ( n1 n2 -- n )
11708:     4 si D) bx add
11709:     4 # si add
11710:     Next
11711: end-code
11712: @end example
11713: 
11714: @node Alpha Assembler, MIPS assembler, 386 Assembler, Assembler and Code Words
11715: @subsection Alpha Assembler
11716: 
11717: The Alpha assembler and disassembler were originally written by Bernd
11718: Thallner.
11719: 
11720: The register names @code{a0}--@code{a5} are not available to avoid
11721: shadowing hex numbers.
11722: 
11723: Immediate forms of arithmetic instructions are distinguished by a
11724: @code{#} just before the @code{,}, e.g., @code{and#,} (note: @code{lda,}
11725: does not count as arithmetic instruction).
11726: 
11727: You have to specify all operands to an instruction, even those that
11728: other assemblers consider optional, e.g., the destination register for
11729: @code{br,}, or the destination register and hint for @code{jmp,}.
11730: 
11731: You can specify conditions for @code{if,} by removing the first @code{b}
11732: and the trailing @code{,} from a branch with a corresponding name; e.g.,
11733: 
11734: @example
11735: 11 fgt if, \ if F11>0e
11736:   ...
11737: endif,
11738: @end example
11739: 
11740: @code{fbgt,} gives @code{fgt}.  
11741: 
11742: @node MIPS assembler, Other assemblers, Alpha Assembler, Assembler and Code Words
11743: @subsection MIPS assembler
11744: 
11745: The MIPS assembler was originally written by Christian Pirker.
11746: 
11747: Currently the assembler and disassembler only cover the MIPS-I
11748: architecture (R3000), and don't support FP instructions.
11749: 
11750: The register names @code{$a0}--@code{$a3} are not available to avoid
11751: shadowing hex numbers.
11752: 
11753: Because there is no way to distinguish registers from immediate values,
11754: you have to explicitly use the immediate forms of instructions, i.e.,
11755: @code{addiu,}, not just @code{addu,} (@command{as} does this
11756: implicitly).
11757: 
11758: If the architecture manual specifies several formats for the instruction
11759: (e.g., for @code{jalr,}), you usually have to use the one with more
11760: arguments (i.e., two for @code{jalr,}).  When in doubt, see
11761: @code{arch/mips/testasm.fs} for an example of correct use.
11762: 
11763: Branches and jumps in the MIPS architecture have a delay slot.  You have
11764: to fill it yourself (the simplest way is to use @code{nop,}), the
11765: assembler does not do it for you (unlike @command{as}).  Even
11766: @code{if,}, @code{ahead,}, @code{until,}, @code{again,}, @code{while,},
11767: @code{else,} and @code{repeat,} need a delay slot.  Since @code{begin,}
11768: and @code{then,} just specify branch targets, they are not affected.
11769: 
11770: Note that you must not put branches, jumps, or @code{li,} into the delay
11771: slot: @code{li,} may expand to several instructions, and control flow
11772: instructions may not be put into the branch delay slot in any case.
11773: 
11774: For branches the argument specifying the target is a relative address;
11775: You have to add the address of the delay slot to get the absolute
11776: address.
11777: 
11778: The MIPS architecture also has load delay slots and restrictions on
11779: using @code{mfhi,} and @code{mflo,}; you have to order the instructions
11780: yourself to satisfy these restrictions, the assembler does not do it for
11781: you.
11782: 
11783: You can specify the conditions for @code{if,} etc. by taking a
11784: conditional branch and leaving away the @code{b} at the start and the
11785: @code{,} at the end.  E.g.,
11786: 
11787: @example
11788: 4 5 eq if,
11789:   ... \ do something if $4 equals $5
11790: then,
11791: @end example
11792: 
11793: @node Other assemblers,  , MIPS assembler, Assembler and Code Words
11794: @subsection Other assemblers
11795: 
11796: If you want to contribute another assembler/disassembler, please contact
11797: us (@email{anton@@mips.complang.tuwien.ac.at}) to check if we have such
11798: an assembler already.  If you are writing them from scratch, please use
11799: a similar syntax style as the one we use (i.e., postfix, commas at the
11800: end of the instruction names, @pxref{Common Assembler}); make the output
11801: of the disassembler be valid input for the assembler, and keep the style
11802: similar to the style we used.
11803: 
11804: Hints on implementation: The most important part is to have a good test
11805: suite that contains all instructions.  Once you have that, the rest is
11806: easy.  For actual coding you can take a look at
11807: @file{arch/mips/disasm.fs} to get some ideas on how to use data for both
11808: the assembler and disassembler, avoiding redundancy and some potential
11809: bugs.  You can also look at that file (and @pxref{Advanced does> usage
11810: example}) to get ideas how to factor a disassembler.
11811: 
11812: Start with the disassembler, because it's easier to reuse data from the
11813: disassembler for the assembler than the other way round.
11814: 
11815: For the assembler, take a look at @file{arch/alpha/asm.fs}, which shows
11816: how simple it can be.
11817: 
11818: @c -------------------------------------------------------------
11819: @node Threading Words, Passing Commands to the OS, Assembler and Code Words, Words
11820: @section Threading Words
11821: @cindex threading words
11822: 
11823: @cindex code address
11824: These words provide access to code addresses and other threading stuff
11825: in Gforth (and, possibly, other interpretive Forths). It more or less
11826: abstracts away the differences between direct and indirect threading
11827: (and, for direct threading, the machine dependences). However, at
11828: present this wordset is still incomplete. It is also pretty low-level;
11829: some day it will hopefully be made unnecessary by an internals wordset
11830: that abstracts implementation details away completely.
11831: 
11832: The terminology used here stems from indirect threaded Forth systems; in
11833: such a system, the XT of a word is represented by the CFA (code field
11834: address) of a word; the CFA points to a cell that contains the code
11835: address.  The code address is the address of some machine code that
11836: performs the run-time action of invoking the word (e.g., the
11837: @code{dovar:} routine pushes the address of the body of the word (a
11838: variable) on the stack
11839: ).
11840: 
11841: @cindex code address
11842: @cindex code field address
11843: In an indirect threaded Forth, you can get the code address of @i{name}
11844: with @code{' @i{name} @@}; in Gforth you can get it with @code{' @i{name}
11845: >code-address}, independent of the threading method.
11846: 
11847: doc-threading-method
11848: doc->code-address
11849: doc-code-address!
11850: 
11851: @cindex @code{does>}-handler
11852: @cindex @code{does>}-code
11853: For a word defined with @code{DOES>}, the code address usually points to
11854: a jump instruction (the @dfn{does-handler}) that jumps to the dodoes
11855: routine (in Gforth on some platforms, it can also point to the dodoes
11856: routine itself).  What you are typically interested in, though, is
11857: whether a word is a @code{DOES>}-defined word, and what Forth code it
11858: executes; @code{>does-code} tells you that.
11859: 
11860: doc->does-code
11861: 
11862: To create a @code{DOES>}-defined word with the following basic words,
11863: you have to set up a @code{DOES>}-handler with @code{does-handler!};
11864: @code{/does-handler} aus behind you have to place your executable Forth
11865: code.  Finally you have to create a word and modify its behaviour with
11866: @code{does-handler!}.
11867: 
11868: doc-does-code!
11869: doc-does-handler!
11870: doc-/does-handler
11871: 
11872: The code addresses produced by various defining words are produced by
11873: the following words:
11874: 
11875: doc-docol:
11876: doc-docon:
11877: doc-dovar:
11878: doc-douser:
11879: doc-dodefer:
11880: doc-dofield:
11881: 
11882: @cindex definer
11883: The following two words generalize @code{>code-address},
11884: @code{>does-code}, @code{code-address!}, and @code{does-code!}:
11885: 
11886: doc->definer
11887: doc-definer!
11888: 
11889: @c -------------------------------------------------------------
11890: @node Passing Commands to the OS, Keeping track of Time, Threading Words, Words
11891: @section Passing Commands to the Operating System
11892: @cindex operating system - passing commands
11893: @cindex shell commands
11894: 
11895: Gforth allows you to pass an arbitrary string to the host operating
11896: system shell (if such a thing exists) for execution.
11897: 
11898: 
11899: doc-sh
11900: doc-system
11901: doc-$?
11902: doc-getenv
11903: 
11904: 
11905: @c -------------------------------------------------------------
11906: @node Keeping track of Time, Miscellaneous Words, Passing Commands to the OS, Words
11907: @section Keeping track of Time
11908: @cindex time-related words
11909: 
11910: doc-ms
11911: doc-time&date
11912: doc-utime
11913: doc-cputime
11914: 
11915: 
11916: @c -------------------------------------------------------------
11917: @node Miscellaneous Words,  , Keeping track of Time, Words
11918: @section Miscellaneous Words
11919: @cindex miscellaneous words
11920: 
11921: @comment TODO find homes for these
11922: 
11923: These section lists the ANS Forth words that are not documented
11924: elsewhere in this manual. Ultimately, they all need proper homes.
11925: 
11926: doc-quit
11927: 
11928: The following ANS Forth words are not currently supported by Gforth 
11929: (@pxref{ANS conformance}):
11930: 
11931: @code{EDITOR} 
11932: @code{EMIT?} 
11933: @code{FORGET} 
11934: 
11935: @c ******************************************************************
11936: @node Error messages, Tools, Words, Top
11937: @chapter Error messages
11938: @cindex error messages
11939: @cindex backtrace
11940: 
11941: A typical Gforth error message looks like this:
11942: 
11943: @example
11944: in file included from \evaluated string/:-1
11945: in file included from ./yyy.fs:1
11946: ./xxx.fs:4: Invalid memory address
11947: bar
11948: ^^^
11949: Backtrace:
11950: $400E664C @@
11951: $400E6664 foo
11952: @end example
11953: 
11954: The message identifying the error is @code{Invalid memory address}.  The
11955: error happened when text-interpreting line 4 of the file
11956: @file{./xxx.fs}. This line is given (it contains @code{bar}), and the
11957: word on the line where the error happened, is pointed out (with
11958: @code{^^^}).
11959: 
11960: The file containing the error was included in line 1 of @file{./yyy.fs},
11961: and @file{yyy.fs} was included from a non-file (in this case, by giving
11962: @file{yyy.fs} as command-line parameter to Gforth).
11963: 
11964: At the end of the error message you find a return stack dump that can be
11965: interpreted as a backtrace (possibly empty). On top you find the top of
11966: the return stack when the @code{throw} happened, and at the bottom you
11967: find the return stack entry just above the return stack of the topmost
11968: text interpreter.
11969: 
11970: To the right of most return stack entries you see a guess for the word
11971: that pushed that return stack entry as its return address. This gives a
11972: backtrace. In our case we see that @code{bar} called @code{foo}, and
11973: @code{foo} called @code{@@} (and @code{@@} had an @emph{Invalid memory
11974: address} exception).
11975: 
11976: Note that the backtrace is not perfect: We don't know which return stack
11977: entries are return addresses (so we may get false positives); and in
11978: some cases (e.g., for @code{abort"}) we cannot determine from the return
11979: address the word that pushed the return address, so for some return
11980: addresses you see no names in the return stack dump.
11981: 
11982: @cindex @code{catch} and backtraces
11983: The return stack dump represents the return stack at the time when a
11984: specific @code{throw} was executed.  In programs that make use of
11985: @code{catch}, it is not necessarily clear which @code{throw} should be
11986: used for the return stack dump (e.g., consider one @code{throw} that
11987: indicates an error, which is caught, and during recovery another error
11988: happens; which @code{throw} should be used for the stack dump?).  Gforth
11989: presents the return stack dump for the first @code{throw} after the last
11990: executed (not returned-to) @code{catch}; this works well in the usual
11991: case.
11992: 
11993: @cindex @code{gforth-fast} and backtraces
11994: @cindex @code{gforth-fast}, difference from @code{gforth}
11995: @cindex backtraces with @code{gforth-fast}
11996: @cindex return stack dump with @code{gforth-fast}
11997: @code{Gforth} is able to do a return stack dump for throws generated
11998: from primitives (e.g., invalid memory address, stack empty etc.);
11999: @code{gforth-fast} is only able to do a return stack dump from a
12000: directly called @code{throw} (including @code{abort} etc.).  Given an
12001: exception caused by a primitive in @code{gforth-fast}, you will
12002: typically see no return stack dump at all; however, if the exception is
12003: caught by @code{catch} (e.g., for restoring some state), and then
12004: @code{throw}n again, the return stack dump will be for the first such
12005: @code{throw}.
12006: 
12007: @c ******************************************************************
12008: @node Tools, ANS conformance, Error messages, Top
12009: @chapter Tools
12010: 
12011: @menu
12012: * ANS Report::                  Report the words used, sorted by wordset.
12013: @end menu
12014: 
12015: See also @ref{Emacs and Gforth}.
12016: 
12017: @node ANS Report,  , Tools, Tools
12018: @section @file{ans-report.fs}: Report the words used, sorted by wordset
12019: @cindex @file{ans-report.fs}
12020: @cindex report the words used in your program
12021: @cindex words used in your program
12022: 
12023: If you want to label a Forth program as ANS Forth Program, you must
12024: document which wordsets the program uses; for extension wordsets, it is
12025: helpful to list the words the program requires from these wordsets
12026: (because Forth systems are allowed to provide only some words of them).
12027: 
12028: The @file{ans-report.fs} tool makes it easy for you to determine which
12029: words from which wordset and which non-ANS words your application
12030: uses. You simply have to include @file{ans-report.fs} before loading the
12031: program you want to check. After loading your program, you can get the
12032: report with @code{print-ans-report}. A typical use is to run this as
12033: batch job like this:
12034: @example
12035: gforth ans-report.fs myprog.fs -e "print-ans-report bye"
12036: @end example
12037: 
12038: The output looks like this (for @file{compat/control.fs}):
12039: @example
12040: The program uses the following words
12041: from CORE :
12042: : POSTPONE THEN ; immediate ?dup IF 0= 
12043: from BLOCK-EXT :
12044: \ 
12045: from FILE :
12046: ( 
12047: @end example
12048: 
12049: @subsection Caveats
12050: 
12051: Note that @file{ans-report.fs} just checks which words are used, not whether
12052: they are used in an ANS Forth conforming way!
12053: 
12054: Some words are defined in several wordsets in the
12055: standard. @file{ans-report.fs} reports them for only one of the
12056: wordsets, and not necessarily the one you expect. It depends on usage
12057: which wordset is the right one to specify. E.g., if you only use the
12058: compilation semantics of @code{S"}, it is a Core word; if you also use
12059: its interpretation semantics, it is a File word.
12060: 
12061: @c ******************************************************************
12062: @node ANS conformance, Standard vs Extensions, Tools, Top
12063: @chapter ANS conformance
12064: @cindex ANS conformance of Gforth
12065: 
12066: To the best of our knowledge, Gforth is an
12067: 
12068: ANS Forth System
12069: @itemize @bullet
12070: @item providing the Core Extensions word set
12071: @item providing the Block word set
12072: @item providing the Block Extensions word set
12073: @item providing the Double-Number word set
12074: @item providing the Double-Number Extensions word set
12075: @item providing the Exception word set
12076: @item providing the Exception Extensions word set
12077: @item providing the Facility word set
12078: @item providing @code{EKEY}, @code{EKEY>CHAR}, @code{EKEY?}, @code{MS} and @code{TIME&DATE} from the Facility Extensions word set
12079: @item providing the File Access word set
12080: @item providing the File Access Extensions word set
12081: @item providing the Floating-Point word set
12082: @item providing the Floating-Point Extensions word set
12083: @item providing the Locals word set
12084: @item providing the Locals Extensions word set
12085: @item providing the Memory-Allocation word set
12086: @item providing the Memory-Allocation Extensions word set (that one's easy)
12087: @item providing the Programming-Tools word set
12088: @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
12089: @item providing the Search-Order word set
12090: @item providing the Search-Order Extensions word set
12091: @item providing the String word set
12092: @item providing the String Extensions word set (another easy one)
12093: @end itemize
12094: 
12095: @cindex system documentation
12096: In addition, ANS Forth systems are required to document certain
12097: implementation choices. This chapter tries to meet these
12098: requirements. In many cases it gives a way to ask the system for the
12099: information instead of providing the information directly, in
12100: particular, if the information depends on the processor, the operating
12101: system or the installation options chosen, or if they are likely to
12102: change during the maintenance of Gforth.
12103: 
12104: @comment The framework for the rest has been taken from pfe.
12105: 
12106: @menu
12107: * The Core Words::              
12108: * The optional Block word set::  
12109: * The optional Double Number word set::  
12110: * The optional Exception word set::  
12111: * The optional Facility word set::  
12112: * The optional File-Access word set::  
12113: * The optional Floating-Point word set::  
12114: * The optional Locals word set::  
12115: * The optional Memory-Allocation word set::  
12116: * The optional Programming-Tools word set::  
12117: * The optional Search-Order word set::  
12118: @end menu
12119: 
12120: 
12121: @c =====================================================================
12122: @node The Core Words, The optional Block word set, ANS conformance, ANS conformance
12123: @comment  node-name,  next,  previous,  up
12124: @section The Core Words
12125: @c =====================================================================
12126: @cindex core words, system documentation
12127: @cindex system documentation, core words
12128: 
12129: @menu
12130: * core-idef::                   Implementation Defined Options                   
12131: * core-ambcond::                Ambiguous Conditions                
12132: * core-other::                  Other System Documentation                  
12133: @end menu
12134: 
12135: @c ---------------------------------------------------------------------
12136: @node core-idef, core-ambcond, The Core Words, The Core Words
12137: @subsection Implementation Defined Options
12138: @c ---------------------------------------------------------------------
12139: @cindex core words, implementation-defined options
12140: @cindex implementation-defined options, core words
12141: 
12142: 
12143: @table @i
12144: @item (Cell) aligned addresses:
12145: @cindex cell-aligned addresses
12146: @cindex aligned addresses
12147: processor-dependent. Gforth's alignment words perform natural alignment
12148: (e.g., an address aligned for a datum of size 8 is divisible by
12149: 8). Unaligned accesses usually result in a @code{-23 THROW}.
12150: 
12151: @item @code{EMIT} and non-graphic characters:
12152: @cindex @code{EMIT} and non-graphic characters
12153: @cindex non-graphic characters and @code{EMIT}
12154: The character is output using the C library function (actually, macro)
12155: @code{putc}.
12156: 
12157: @item character editing of @code{ACCEPT} and @code{EXPECT}:
12158: @cindex character editing of @code{ACCEPT} and @code{EXPECT}
12159: @cindex editing in @code{ACCEPT} and @code{EXPECT}
12160: @cindex @code{ACCEPT}, editing
12161: @cindex @code{EXPECT}, editing
12162: This is modeled on the GNU readline library (@pxref{Readline
12163: Interaction, , Command Line Editing, readline, The GNU Readline
12164: Library}) with Emacs-like key bindings. @kbd{Tab} deviates a little by
12165: producing a full word completion every time you type it (instead of
12166: producing the common prefix of all completions). @xref{Command-line editing}.
12167: 
12168: @item character set:
12169: @cindex character set
12170: The character set of your computer and display device. Gforth is
12171: 8-bit-clean (but some other component in your system may make trouble).
12172: 
12173: @item Character-aligned address requirements:
12174: @cindex character-aligned address requirements
12175: installation-dependent. Currently a character is represented by a C
12176: @code{unsigned char}; in the future we might switch to @code{wchar_t}
12177: (Comments on that requested).
12178: 
12179: @item character-set extensions and matching of names:
12180: @cindex character-set extensions and matching of names
12181: @cindex case-sensitivity for name lookup
12182: @cindex name lookup, case-sensitivity
12183: @cindex locale and case-sensitivity
12184: Any character except the ASCII NUL character can be used in a
12185: name. Matching is case-insensitive (except in @code{TABLE}s). The
12186: matching is performed using the C library function @code{strncasecmp}, whose
12187: function is probably influenced by the locale. E.g., the @code{C} locale
12188: does not know about accents and umlauts, so they are matched
12189: case-sensitively in that locale. For portability reasons it is best to
12190: write programs such that they work in the @code{C} locale. Then one can
12191: use libraries written by a Polish programmer (who might use words
12192: containing ISO Latin-2 encoded characters) and by a French programmer
12193: (ISO Latin-1) in the same program (of course, @code{WORDS} will produce
12194: funny results for some of the words (which ones, depends on the font you
12195: are using)). Also, the locale you prefer may not be available in other
12196: operating systems. Hopefully, Unicode will solve these problems one day.
12197: 
12198: @item conditions under which control characters match a space delimiter:
12199: @cindex space delimiters
12200: @cindex control characters as delimiters
12201: If @code{WORD} is called with the space character as a delimiter, all
12202: white-space characters (as identified by the C macro @code{isspace()})
12203: are delimiters. @code{PARSE}, on the other hand, treats space like other
12204: delimiters. @code{SWORD} treats space like @code{WORD}, but behaves
12205: like @code{PARSE} otherwise. @code{Name}, which is used by the outer
12206: interpreter (aka text interpreter) by default, treats all white-space
12207: characters as delimiters.
12208: 
12209: @item format of the control-flow stack:
12210: @cindex control-flow stack, format
12211: The data stack is used as control-flow stack. The size of a control-flow
12212: stack item in cells is given by the constant @code{cs-item-size}. At the
12213: time of this writing, an item consists of a (pointer to a) locals list
12214: (third), an address in the code (second), and a tag for identifying the
12215: item (TOS). The following tags are used: @code{defstart},
12216: @code{live-orig}, @code{dead-orig}, @code{dest}, @code{do-dest},
12217: @code{scopestart}.
12218: 
12219: @item conversion of digits > 35
12220: @cindex digits > 35
12221: The characters @code{[\]^_'} are the digits with the decimal value
12222: 36@minus{}41. There is no way to input many of the larger digits.
12223: 
12224: @item display after input terminates in @code{ACCEPT} and @code{EXPECT}:
12225: @cindex @code{EXPECT}, display after end of input
12226: @cindex @code{ACCEPT}, display after end of input
12227: The cursor is moved to the end of the entered string. If the input is
12228: terminated using the @kbd{Return} key, a space is typed.
12229: 
12230: @item exception abort sequence of @code{ABORT"}:
12231: @cindex exception abort sequence of @code{ABORT"}
12232: @cindex @code{ABORT"}, exception abort sequence
12233: The error string is stored into the variable @code{"error} and a
12234: @code{-2 throw} is performed.
12235: 
12236: @item input line terminator:
12237: @cindex input line terminator
12238: @cindex line terminator on input
12239: @cindex newline character on input
12240: For interactive input, @kbd{C-m} (CR) and @kbd{C-j} (LF) terminate
12241: lines. One of these characters is typically produced when you type the
12242: @kbd{Enter} or @kbd{Return} key.
12243: 
12244: @item maximum size of a counted string:
12245: @cindex maximum size of a counted string
12246: @cindex counted string, maximum size
12247: @code{s" /counted-string" environment? drop .}. Currently 255 characters
12248: on all platforms, but this may change.
12249: 
12250: @item maximum size of a parsed string:
12251: @cindex maximum size of a parsed string
12252: @cindex parsed string, maximum size
12253: Given by the constant @code{/line}. Currently 255 characters.
12254: 
12255: @item maximum size of a definition name, in characters:
12256: @cindex maximum size of a definition name, in characters
12257: @cindex name, maximum length
12258: MAXU/8
12259: 
12260: @item maximum string length for @code{ENVIRONMENT?}, in characters:
12261: @cindex maximum string length for @code{ENVIRONMENT?}, in characters
12262: @cindex @code{ENVIRONMENT?} string length, maximum
12263: MAXU/8
12264: 
12265: @item method of selecting the user input device:
12266: @cindex user input device, method of selecting
12267: The user input device is the standard input. There is currently no way to
12268: change it from within Gforth. However, the input can typically be
12269: redirected in the command line that starts Gforth.
12270: 
12271: @item method of selecting the user output device:
12272: @cindex user output device, method of selecting
12273: @code{EMIT} and @code{TYPE} output to the file-id stored in the value
12274: @code{outfile-id} (@code{stdout} by default). Gforth uses unbuffered
12275: output when the user output device is a terminal, otherwise the output
12276: is buffered.
12277: 
12278: @item methods of dictionary compilation:
12279: What are we expected to document here?
12280: 
12281: @item number of bits in one address unit:
12282: @cindex number of bits in one address unit
12283: @cindex address unit, size in bits
12284: @code{s" address-units-bits" environment? drop .}. 8 in all current
12285: platforms.
12286: 
12287: @item number representation and arithmetic:
12288: @cindex number representation and arithmetic
12289: Processor-dependent. Binary two's complement on all current platforms.
12290: 
12291: @item ranges for integer types:
12292: @cindex ranges for integer types
12293: @cindex integer types, ranges
12294: Installation-dependent. Make environmental queries for @code{MAX-N},
12295: @code{MAX-U}, @code{MAX-D} and @code{MAX-UD}. The lower bounds for
12296: unsigned (and positive) types is 0. The lower bound for signed types on
12297: two's complement and one's complement machines machines can be computed
12298: by adding 1 to the upper bound.
12299: 
12300: @item read-only data space regions:
12301: @cindex read-only data space regions
12302: @cindex data-space, read-only regions
12303: The whole Forth data space is writable.
12304: 
12305: @item size of buffer at @code{WORD}:
12306: @cindex size of buffer at @code{WORD}
12307: @cindex @code{WORD} buffer size
12308: @code{PAD HERE - .}. 104 characters on 32-bit machines. The buffer is
12309: shared with the pictured numeric output string. If overwriting
12310: @code{PAD} is acceptable, it is as large as the remaining dictionary
12311: space, although only as much can be sensibly used as fits in a counted
12312: string.
12313: 
12314: @item size of one cell in address units:
12315: @cindex cell size
12316: @code{1 cells .}.
12317: 
12318: @item size of one character in address units:
12319: @cindex char size
12320: @code{1 chars .}. 1 on all current platforms.
12321: 
12322: @item size of the keyboard terminal buffer:
12323: @cindex size of the keyboard terminal buffer
12324: @cindex terminal buffer, size
12325: Varies. You can determine the size at a specific time using @code{lp@@
12326: tib - .}. It is shared with the locals stack and TIBs of files that
12327: include the current file. You can change the amount of space for TIBs
12328: and locals stack at Gforth startup with the command line option
12329: @code{-l}.
12330: 
12331: @item size of the pictured numeric output buffer:
12332: @cindex size of the pictured numeric output buffer
12333: @cindex pictured numeric output buffer, size
12334: @code{PAD HERE - .}. 104 characters on 32-bit machines. The buffer is
12335: shared with @code{WORD}.
12336: 
12337: @item size of the scratch area returned by @code{PAD}:
12338: @cindex size of the scratch area returned by @code{PAD}
12339: @cindex @code{PAD} size
12340: The remainder of dictionary space. @code{unused pad here - - .}.
12341: 
12342: @item system case-sensitivity characteristics:
12343: @cindex case-sensitivity characteristics
12344: Dictionary searches are case-insensitive (except in
12345: @code{TABLE}s). However, as explained above under @i{character-set
12346: extensions}, the matching for non-ASCII characters is determined by the
12347: locale you are using. In the default @code{C} locale all non-ASCII
12348: characters are matched case-sensitively.
12349: 
12350: @item system prompt:
12351: @cindex system prompt
12352: @cindex prompt
12353: @code{ ok} in interpret state, @code{ compiled} in compile state.
12354: 
12355: @item division rounding:
12356: @cindex division rounding
12357: installation dependent. @code{s" floored" environment? drop .}. We leave
12358: the choice to @code{gcc} (what to use for @code{/}) and to you (whether
12359: to use @code{fm/mod}, @code{sm/rem} or simply @code{/}).
12360: 
12361: @item values of @code{STATE} when true:
12362: @cindex @code{STATE} values
12363: -1.
12364: 
12365: @item values returned after arithmetic overflow:
12366: On two's complement machines, arithmetic is performed modulo
12367: 2**bits-per-cell for single arithmetic and 4**bits-per-cell for double
12368: arithmetic (with appropriate mapping for signed types). Division by zero
12369: typically results in a @code{-55 throw} (Floating-point unidentified
12370: fault) or @code{-10 throw} (divide by zero).
12371: 
12372: @item whether the current definition can be found after @t{DOES>}:
12373: @cindex @t{DOES>}, visibility of current definition
12374: No.
12375: 
12376: @end table
12377: 
12378: @c ---------------------------------------------------------------------
12379: @node core-ambcond, core-other, core-idef, The Core Words
12380: @subsection Ambiguous conditions
12381: @c ---------------------------------------------------------------------
12382: @cindex core words, ambiguous conditions
12383: @cindex ambiguous conditions, core words
12384: 
12385: @table @i
12386: 
12387: @item a name is neither a word nor a number:
12388: @cindex name not found
12389: @cindex undefined word
12390: @code{-13 throw} (Undefined word).
12391: 
12392: @item a definition name exceeds the maximum length allowed:
12393: @cindex word name too long
12394: @code{-19 throw} (Word name too long)
12395: 
12396: @item addressing a region not inside the various data spaces of the forth system:
12397: @cindex Invalid memory address
12398: The stacks, code space and header space are accessible. Machine code space is
12399: typically readable. Accessing other addresses gives results dependent on
12400: the operating system. On decent systems: @code{-9 throw} (Invalid memory
12401: address).
12402: 
12403: @item argument type incompatible with parameter:
12404: @cindex argument type mismatch
12405: This is usually not caught. Some words perform checks, e.g., the control
12406: flow words, and issue a @code{ABORT"} or @code{-12 THROW} (Argument type
12407: mismatch).
12408: 
12409: @item attempting to obtain the execution token of a word with undefined execution semantics:
12410: @cindex Interpreting a compile-only word, for @code{'} etc.
12411: @cindex execution token of words with undefined execution semantics
12412: @code{-14 throw} (Interpreting a compile-only word). In some cases, you
12413: get an execution token for @code{compile-only-error} (which performs a
12414: @code{-14 throw} when executed).
12415: 
12416: @item dividing by zero:
12417: @cindex dividing by zero
12418: @cindex floating point unidentified fault, integer division
12419: On some platforms, this produces a @code{-10 throw} (Division by
12420: zero); on other systems, this typically results in a @code{-55 throw}
12421: (Floating-point unidentified fault).
12422: 
12423: @item insufficient data stack or return stack space:
12424: @cindex insufficient data stack or return stack space
12425: @cindex stack overflow
12426: @cindex address alignment exception, stack overflow
12427: @cindex Invalid memory address, stack overflow
12428: Depending on the operating system, the installation, and the invocation
12429: of Gforth, this is either checked by the memory management hardware, or
12430: it is not checked. If it is checked, you typically get a @code{-3 throw}
12431: (Stack overflow), @code{-5 throw} (Return stack overflow), or @code{-9
12432: throw} (Invalid memory address) (depending on the platform and how you
12433: achieved the overflow) as soon as the overflow happens. If it is not
12434: checked, overflows typically result in mysterious illegal memory
12435: accesses, producing @code{-9 throw} (Invalid memory address) or
12436: @code{-23 throw} (Address alignment exception); they might also destroy
12437: the internal data structure of @code{ALLOCATE} and friends, resulting in
12438: various errors in these words.
12439: 
12440: @item insufficient space for loop control parameters:
12441: @cindex insufficient space for loop control parameters
12442: Like other return stack overflows.
12443: 
12444: @item insufficient space in the dictionary:
12445: @cindex insufficient space in the dictionary
12446: @cindex dictionary overflow
12447: If you try to allot (either directly with @code{allot}, or indirectly
12448: with @code{,}, @code{create} etc.) more memory than available in the
12449: dictionary, you get a @code{-8 throw} (Dictionary overflow). If you try
12450: to access memory beyond the end of the dictionary, the results are
12451: similar to stack overflows.
12452: 
12453: @item interpreting a word with undefined interpretation semantics:
12454: @cindex interpreting a word with undefined interpretation semantics
12455: @cindex Interpreting a compile-only word
12456: For some words, we have defined interpretation semantics. For the
12457: others: @code{-14 throw} (Interpreting a compile-only word).
12458: 
12459: @item modifying the contents of the input buffer or a string literal:
12460: @cindex modifying the contents of the input buffer or a string literal
12461: These are located in writable memory and can be modified.
12462: 
12463: @item overflow of the pictured numeric output string:
12464: @cindex overflow of the pictured numeric output string
12465: @cindex pictured numeric output string, overflow
12466: @code{-17 throw} (Pictured numeric ouput string overflow).
12467: 
12468: @item parsed string overflow:
12469: @cindex parsed string overflow
12470: @code{PARSE} cannot overflow. @code{WORD} does not check for overflow.
12471: 
12472: @item producing a result out of range:
12473: @cindex result out of range
12474: On two's complement machines, arithmetic is performed modulo
12475: 2**bits-per-cell for single arithmetic and 4**bits-per-cell for double
12476: arithmetic (with appropriate mapping for signed types). Division by zero
12477: typically results in a @code{-10 throw} (divide by zero) or @code{-55
12478: throw} (floating point unidentified fault). @code{convert} and
12479: @code{>number} currently overflow silently.
12480: 
12481: @item reading from an empty data or return stack:
12482: @cindex stack empty
12483: @cindex stack underflow
12484: @cindex return stack underflow
12485: The data stack is checked by the outer (aka text) interpreter after
12486: every word executed. If it has underflowed, a @code{-4 throw} (Stack
12487: underflow) is performed. Apart from that, stacks may be checked or not,
12488: depending on operating system, installation, and invocation. If they are
12489: caught by a check, they typically result in @code{-4 throw} (Stack
12490: underflow), @code{-6 throw} (Return stack underflow) or @code{-9 throw}
12491: (Invalid memory address), depending on the platform and which stack
12492: underflows and by how much. Note that even if the system uses checking
12493: (through the MMU), your program may have to underflow by a significant
12494: number of stack items to trigger the reaction (the reason for this is
12495: that the MMU, and therefore the checking, works with a page-size
12496: granularity).  If there is no checking, the symptoms resulting from an
12497: underflow are similar to those from an overflow.  Unbalanced return
12498: stack errors can result in a variety of symptoms, including @code{-9 throw}
12499: (Invalid memory address) and Illegal Instruction (typically @code{-260
12500: throw}).
12501: 
12502: @item unexpected end of the input buffer, resulting in an attempt to use a zero-length string as a name:
12503: @cindex unexpected end of the input buffer
12504: @cindex zero-length string as a name
12505: @cindex Attempt to use zero-length string as a name
12506: @code{Create} and its descendants perform a @code{-16 throw} (Attempt to
12507: use zero-length string as a name). Words like @code{'} probably will not
12508: find what they search. Note that it is possible to create zero-length
12509: names with @code{nextname} (should it not?).
12510: 
12511: @item @code{>IN} greater than input buffer:
12512: @cindex @code{>IN} greater than input buffer
12513: The next invocation of a parsing word returns a string with length 0.
12514: 
12515: @item @code{RECURSE} appears after @code{DOES>}:
12516: @cindex @code{RECURSE} appears after @code{DOES>}
12517: Compiles a recursive call to the defining word, not to the defined word.
12518: 
12519: @item argument input source different than current input source for @code{RESTORE-INPUT}:
12520: @cindex argument input source different than current input source for @code{RESTORE-INPUT}
12521: @cindex argument type mismatch, @code{RESTORE-INPUT}
12522: @cindex @code{RESTORE-INPUT}, Argument type mismatch
12523: @code{-12 THROW}. Note that, once an input file is closed (e.g., because
12524: the end of the file was reached), its source-id may be
12525: reused. Therefore, restoring an input source specification referencing a
12526: closed file may lead to unpredictable results instead of a @code{-12
12527: THROW}.
12528: 
12529: In the future, Gforth may be able to restore input source specifications
12530: from other than the current input source.
12531: 
12532: @item data space containing definitions gets de-allocated:
12533: @cindex data space containing definitions gets de-allocated
12534: Deallocation with @code{allot} is not checked. This typically results in
12535: memory access faults or execution of illegal instructions.
12536: 
12537: @item data space read/write with incorrect alignment:
12538: @cindex data space read/write with incorrect alignment
12539: @cindex alignment faults
12540: @cindex address alignment exception
12541: Processor-dependent. Typically results in a @code{-23 throw} (Address
12542: alignment exception). Under Linux-Intel on a 486 or later processor with
12543: alignment turned on, incorrect alignment results in a @code{-9 throw}
12544: (Invalid memory address). There are reportedly some processors with
12545: alignment restrictions that do not report violations.
12546: 
12547: @item data space pointer not properly aligned, @code{,}, @code{C,}:
12548: @cindex data space pointer not properly aligned, @code{,}, @code{C,}
12549: Like other alignment errors.
12550: 
12551: @item less than u+2 stack items (@code{PICK} and @code{ROLL}):
12552: Like other stack underflows.
12553: 
12554: @item loop control parameters not available:
12555: @cindex loop control parameters not available
12556: Not checked. The counted loop words simply assume that the top of return
12557: stack items are loop control parameters and behave accordingly.
12558: 
12559: @item most recent definition does not have a name (@code{IMMEDIATE}):
12560: @cindex most recent definition does not have a name (@code{IMMEDIATE})
12561: @cindex last word was headerless
12562: @code{abort" last word was headerless"}.
12563: 
12564: @item name not defined by @code{VALUE} used by @code{TO}:
12565: @cindex name not defined by @code{VALUE} used by @code{TO}
12566: @cindex @code{TO} on non-@code{VALUE}s
12567: @cindex Invalid name argument, @code{TO}
12568: @code{-32 throw} (Invalid name argument) (unless name is a local or was
12569: defined by @code{CONSTANT}; in the latter case it just changes the constant).
12570: 
12571: @item name not found (@code{'}, @code{POSTPONE}, @code{[']}, @code{[COMPILE]}):
12572: @cindex name not found (@code{'}, @code{POSTPONE}, @code{[']}, @code{[COMPILE]})
12573: @cindex undefined word, @code{'}, @code{POSTPONE}, @code{[']}, @code{[COMPILE]}
12574: @code{-13 throw} (Undefined word)
12575: 
12576: @item parameters are not of the same type (@code{DO}, @code{?DO}, @code{WITHIN}):
12577: @cindex parameters are not of the same type (@code{DO}, @code{?DO}, @code{WITHIN})
12578: Gforth behaves as if they were of the same type. I.e., you can predict
12579: the behaviour by interpreting all parameters as, e.g., signed.
12580: 
12581: @item @code{POSTPONE} or @code{[COMPILE]} applied to @code{TO}:
12582: @cindex @code{POSTPONE} or @code{[COMPILE]} applied to @code{TO}
12583: Assume @code{: X POSTPONE TO ; IMMEDIATE}. @code{X} performs the
12584: compilation semantics of @code{TO}.
12585: 
12586: @item String longer than a counted string returned by @code{WORD}:
12587: @cindex string longer than a counted string returned by @code{WORD}
12588: @cindex @code{WORD}, string overflow
12589: Not checked. The string will be ok, but the count will, of course,
12590: contain only the least significant bits of the length.
12591: 
12592: @item u greater than or equal to the number of bits in a cell (@code{LSHIFT}, @code{RSHIFT}):
12593: @cindex @code{LSHIFT}, large shift counts
12594: @cindex @code{RSHIFT}, large shift counts
12595: Processor-dependent. Typical behaviours are returning 0 and using only
12596: the low bits of the shift count.
12597: 
12598: @item word not defined via @code{CREATE}:
12599: @cindex @code{>BODY} of non-@code{CREATE}d words
12600: @code{>BODY} produces the PFA of the word no matter how it was defined.
12601: 
12602: @cindex @code{DOES>} of non-@code{CREATE}d words
12603: @code{DOES>} changes the execution semantics of the last defined word no
12604: matter how it was defined. E.g., @code{CONSTANT DOES>} is equivalent to
12605: @code{CREATE , DOES>}.
12606: 
12607: @item words improperly used outside @code{<#} and @code{#>}:
12608: Not checked. As usual, you can expect memory faults.
12609: 
12610: @end table
12611: 
12612: 
12613: @c ---------------------------------------------------------------------
12614: @node core-other,  , core-ambcond, The Core Words
12615: @subsection Other system documentation
12616: @c ---------------------------------------------------------------------
12617: @cindex other system documentation, core words
12618: @cindex core words, other system documentation
12619: 
12620: @table @i
12621: @item nonstandard words using @code{PAD}:
12622: @cindex @code{PAD} use by nonstandard words
12623: None.
12624: 
12625: @item operator's terminal facilities available:
12626: @cindex operator's terminal facilities available
12627: After processing the OS's command line, Gforth goes into interactive mode,
12628: and you can give commands to Gforth interactively. The actual facilities
12629: available depend on how you invoke Gforth.
12630: 
12631: @item program data space available:
12632: @cindex program data space available
12633: @cindex data space available
12634: @code{UNUSED .} gives the remaining dictionary space. The total
12635: dictionary space can be specified with the @code{-m} switch
12636: (@pxref{Invoking Gforth}) when Gforth starts up.
12637: 
12638: @item return stack space available:
12639: @cindex return stack space available
12640: You can compute the total return stack space in cells with
12641: @code{s" RETURN-STACK-CELLS" environment? drop .}. You can specify it at
12642: startup time with the @code{-r} switch (@pxref{Invoking Gforth}).
12643: 
12644: @item stack space available:
12645: @cindex stack space available
12646: You can compute the total data stack space in cells with
12647: @code{s" STACK-CELLS" environment? drop .}. You can specify it at
12648: startup time with the @code{-d} switch (@pxref{Invoking Gforth}).
12649: 
12650: @item system dictionary space required, in address units:
12651: @cindex system dictionary space required, in address units
12652: Type @code{here forthstart - .} after startup. At the time of this
12653: writing, this gives 80080 (bytes) on a 32-bit system.
12654: @end table
12655: 
12656: 
12657: @c =====================================================================
12658: @node The optional Block word set, The optional Double Number word set, The Core Words, ANS conformance
12659: @section The optional Block word set
12660: @c =====================================================================
12661: @cindex system documentation, block words
12662: @cindex block words, system documentation
12663: 
12664: @menu
12665: * block-idef::                  Implementation Defined Options
12666: * block-ambcond::               Ambiguous Conditions               
12667: * block-other::                 Other System Documentation                 
12668: @end menu
12669: 
12670: 
12671: @c ---------------------------------------------------------------------
12672: @node block-idef, block-ambcond, The optional Block word set, The optional Block word set
12673: @subsection Implementation Defined Options
12674: @c ---------------------------------------------------------------------
12675: @cindex implementation-defined options, block words
12676: @cindex block words, implementation-defined options
12677: 
12678: @table @i
12679: @item the format for display by @code{LIST}:
12680: @cindex @code{LIST} display format
12681: First the screen number is displayed, then 16 lines of 64 characters,
12682: each line preceded by the line number.
12683: 
12684: @item the length of a line affected by @code{\}:
12685: @cindex length of a line affected by @code{\}
12686: @cindex @code{\}, line length in blocks
12687: 64 characters.
12688: @end table
12689: 
12690: 
12691: @c ---------------------------------------------------------------------
12692: @node block-ambcond, block-other, block-idef, The optional Block word set
12693: @subsection Ambiguous conditions
12694: @c ---------------------------------------------------------------------
12695: @cindex block words, ambiguous conditions
12696: @cindex ambiguous conditions, block words
12697: 
12698: @table @i
12699: @item correct block read was not possible:
12700: @cindex block read not possible
12701: Typically results in a @code{throw} of some OS-derived value (between
12702: -512 and -2048). If the blocks file was just not long enough, blanks are
12703: supplied for the missing portion.
12704: 
12705: @item I/O exception in block transfer:
12706: @cindex I/O exception in block transfer
12707: @cindex block transfer, I/O exception
12708: Typically results in a @code{throw} of some OS-derived value (between
12709: -512 and -2048).
12710: 
12711: @item invalid block number:
12712: @cindex invalid block number
12713: @cindex block number invalid
12714: @code{-35 throw} (Invalid block number)
12715: 
12716: @item a program directly alters the contents of @code{BLK}:
12717: @cindex @code{BLK}, altering @code{BLK}
12718: The input stream is switched to that other block, at the same
12719: position. If the storing to @code{BLK} happens when interpreting
12720: non-block input, the system will get quite confused when the block ends.
12721: 
12722: @item no current block buffer for @code{UPDATE}:
12723: @cindex @code{UPDATE}, no current block buffer
12724: @code{UPDATE} has no effect.
12725: 
12726: @end table
12727: 
12728: @c ---------------------------------------------------------------------
12729: @node block-other,  , block-ambcond, The optional Block word set
12730: @subsection Other system documentation
12731: @c ---------------------------------------------------------------------
12732: @cindex other system documentation, block words
12733: @cindex block words, other system documentation
12734: 
12735: @table @i
12736: @item any restrictions a multiprogramming system places on the use of buffer addresses:
12737: No restrictions (yet).
12738: 
12739: @item the number of blocks available for source and data:
12740: depends on your disk space.
12741: 
12742: @end table
12743: 
12744: 
12745: @c =====================================================================
12746: @node The optional Double Number word set, The optional Exception word set, The optional Block word set, ANS conformance
12747: @section The optional Double Number word set
12748: @c =====================================================================
12749: @cindex system documentation, double words
12750: @cindex double words, system documentation
12751: 
12752: @menu
12753: * double-ambcond::              Ambiguous Conditions              
12754: @end menu
12755: 
12756: 
12757: @c ---------------------------------------------------------------------
12758: @node double-ambcond,  , The optional Double Number word set, The optional Double Number word set
12759: @subsection Ambiguous conditions
12760: @c ---------------------------------------------------------------------
12761: @cindex double words, ambiguous conditions
12762: @cindex ambiguous conditions, double words
12763: 
12764: @table @i
12765: @item @i{d} outside of range of @i{n} in @code{D>S}:
12766: @cindex @code{D>S}, @i{d} out of range of @i{n} 
12767: The least significant cell of @i{d} is produced.
12768: 
12769: @end table
12770: 
12771: 
12772: @c =====================================================================
12773: @node The optional Exception word set, The optional Facility word set, The optional Double Number word set, ANS conformance
12774: @section The optional Exception word set
12775: @c =====================================================================
12776: @cindex system documentation, exception words
12777: @cindex exception words, system documentation
12778: 
12779: @menu
12780: * exception-idef::              Implementation Defined Options              
12781: @end menu
12782: 
12783: 
12784: @c ---------------------------------------------------------------------
12785: @node exception-idef,  , The optional Exception word set, The optional Exception word set
12786: @subsection Implementation Defined Options
12787: @c ---------------------------------------------------------------------
12788: @cindex implementation-defined options, exception words
12789: @cindex exception words, implementation-defined options
12790: 
12791: @table @i
12792: @item @code{THROW}-codes used in the system:
12793: @cindex @code{THROW}-codes used in the system
12794: The codes -256@minus{}-511 are used for reporting signals. The mapping
12795: from OS signal numbers to throw codes is -256@minus{}@i{signal}. The
12796: codes -512@minus{}-2047 are used for OS errors (for file and memory
12797: allocation operations). The mapping from OS error numbers to throw codes
12798: is -512@minus{}@code{errno}. One side effect of this mapping is that
12799: undefined OS errors produce a message with a strange number; e.g.,
12800: @code{-1000 THROW} results in @code{Unknown error 488} on my system.
12801: @end table
12802: 
12803: @c =====================================================================
12804: @node The optional Facility word set, The optional File-Access word set, The optional Exception word set, ANS conformance
12805: @section The optional Facility word set
12806: @c =====================================================================
12807: @cindex system documentation, facility words
12808: @cindex facility words, system documentation
12809: 
12810: @menu
12811: * facility-idef::               Implementation Defined Options               
12812: * facility-ambcond::            Ambiguous Conditions            
12813: @end menu
12814: 
12815: 
12816: @c ---------------------------------------------------------------------
12817: @node facility-idef, facility-ambcond, The optional Facility word set, The optional Facility word set
12818: @subsection Implementation Defined Options
12819: @c ---------------------------------------------------------------------
12820: @cindex implementation-defined options, facility words
12821: @cindex facility words, implementation-defined options
12822: 
12823: @table @i
12824: @item encoding of keyboard events (@code{EKEY}):
12825: @cindex keyboard events, encoding in @code{EKEY}
12826: @cindex @code{EKEY}, encoding of keyboard events
12827: Keys corresponding to ASCII characters are encoded as ASCII characters.
12828: Other keys are encoded with the constants @code{k-left}, @code{k-right},
12829: @code{k-up}, @code{k-down}, @code{k-home}, @code{k-end}, @code{k1},
12830: @code{k2}, @code{k3}, @code{k4}, @code{k5}, @code{k6}, @code{k7},
12831: @code{k8}, @code{k9}, @code{k10}, @code{k11}, @code{k12}.
12832: 
12833: 
12834: @item duration of a system clock tick:
12835: @cindex duration of a system clock tick
12836: @cindex clock tick duration
12837: System dependent. With respect to @code{MS}, the time is specified in
12838: microseconds. How well the OS and the hardware implement this, is
12839: another question.
12840: 
12841: @item repeatability to be expected from the execution of @code{MS}:
12842: @cindex repeatability to be expected from the execution of @code{MS}
12843: @cindex @code{MS}, repeatability to be expected
12844: System dependent. On Unix, a lot depends on load. If the system is
12845: lightly loaded, and the delay is short enough that Gforth does not get
12846: swapped out, the performance should be acceptable. Under MS-DOS and
12847: other single-tasking systems, it should be good.
12848: 
12849: @end table
12850: 
12851: 
12852: @c ---------------------------------------------------------------------
12853: @node facility-ambcond,  , facility-idef, The optional Facility word set
12854: @subsection Ambiguous conditions
12855: @c ---------------------------------------------------------------------
12856: @cindex facility words, ambiguous conditions
12857: @cindex ambiguous conditions, facility words
12858: 
12859: @table @i
12860: @item @code{AT-XY} can't be performed on user output device:
12861: @cindex @code{AT-XY} can't be performed on user output device
12862: Largely terminal dependent. No range checks are done on the arguments.
12863: No errors are reported. You may see some garbage appearing, you may see
12864: simply nothing happen.
12865: 
12866: @end table
12867: 
12868: 
12869: @c =====================================================================
12870: @node The optional File-Access word set, The optional Floating-Point word set, The optional Facility word set, ANS conformance
12871: @section The optional File-Access word set
12872: @c =====================================================================
12873: @cindex system documentation, file words
12874: @cindex file words, system documentation
12875: 
12876: @menu
12877: * file-idef::                   Implementation Defined Options
12878: * file-ambcond::                Ambiguous Conditions                
12879: @end menu
12880: 
12881: @c ---------------------------------------------------------------------
12882: @node file-idef, file-ambcond, The optional File-Access word set, The optional File-Access word set
12883: @subsection Implementation Defined Options
12884: @c ---------------------------------------------------------------------
12885: @cindex implementation-defined options, file words
12886: @cindex file words, implementation-defined options
12887: 
12888: @table @i
12889: @item file access methods used:
12890: @cindex file access methods used
12891: @code{R/O}, @code{R/W} and @code{BIN} work as you would
12892: expect. @code{W/O} translates into the C file opening mode @code{w} (or
12893: @code{wb}): The file is cleared, if it exists, and created, if it does
12894: not (with both @code{open-file} and @code{create-file}).  Under Unix
12895: @code{create-file} creates a file with 666 permissions modified by your
12896: umask.
12897: 
12898: @item file exceptions:
12899: @cindex file exceptions
12900: The file words do not raise exceptions (except, perhaps, memory access
12901: faults when you pass illegal addresses or file-ids).
12902: 
12903: @item file line terminator:
12904: @cindex file line terminator
12905: System-dependent. Gforth uses C's newline character as line
12906: terminator. What the actual character code(s) of this are is
12907: system-dependent.
12908: 
12909: @item file name format:
12910: @cindex file name format
12911: System dependent. Gforth just uses the file name format of your OS.
12912: 
12913: @item information returned by @code{FILE-STATUS}:
12914: @cindex @code{FILE-STATUS}, returned information
12915: @code{FILE-STATUS} returns the most powerful file access mode allowed
12916: for the file: Either @code{R/O}, @code{W/O} or @code{R/W}. If the file
12917: cannot be accessed, @code{R/O BIN} is returned. @code{BIN} is applicable
12918: along with the returned mode.
12919: 
12920: @item input file state after an exception when including source:
12921: @cindex exception when including source
12922: All files that are left via the exception are closed.
12923: 
12924: @item @i{ior} values and meaning:
12925: @cindex @i{ior} values and meaning
12926: @cindex @i{wior} values and meaning
12927: The @i{ior}s returned by the file and memory allocation words are
12928: intended as throw codes. They typically are in the range
12929: -512@minus{}-2047 of OS errors.  The mapping from OS error numbers to
12930: @i{ior}s is -512@minus{}@i{errno}.
12931: 
12932: @item maximum depth of file input nesting:
12933: @cindex maximum depth of file input nesting
12934: @cindex file input nesting, maximum depth
12935: limited by the amount of return stack, locals/TIB stack, and the number
12936: of open files available. This should not give you troubles.
12937: 
12938: @item maximum size of input line:
12939: @cindex maximum size of input line
12940: @cindex input line size, maximum
12941: @code{/line}. Currently 255.
12942: 
12943: @item methods of mapping block ranges to files:
12944: @cindex mapping block ranges to files
12945: @cindex files containing blocks
12946: @cindex blocks in files
12947: By default, blocks are accessed in the file @file{blocks.fb} in the
12948: current working directory. The file can be switched with @code{USE}.
12949: 
12950: @item number of string buffers provided by @code{S"}:
12951: @cindex @code{S"}, number of string buffers
12952: 1
12953: 
12954: @item size of string buffer used by @code{S"}:
12955: @cindex @code{S"}, size of string buffer
12956: @code{/line}. currently 255.
12957: 
12958: @end table
12959: 
12960: @c ---------------------------------------------------------------------
12961: @node file-ambcond,  , file-idef, The optional File-Access word set
12962: @subsection Ambiguous conditions
12963: @c ---------------------------------------------------------------------
12964: @cindex file words, ambiguous conditions
12965: @cindex ambiguous conditions, file words
12966: 
12967: @table @i
12968: @item attempting to position a file outside its boundaries:
12969: @cindex @code{REPOSITION-FILE}, outside the file's boundaries
12970: @code{REPOSITION-FILE} is performed as usual: Afterwards,
12971: @code{FILE-POSITION} returns the value given to @code{REPOSITION-FILE}.
12972: 
12973: @item attempting to read from file positions not yet written:
12974: @cindex reading from file positions not yet written
12975: End-of-file, i.e., zero characters are read and no error is reported.
12976: 
12977: @item @i{file-id} is invalid (@code{INCLUDE-FILE}):
12978: @cindex @code{INCLUDE-FILE}, @i{file-id} is invalid 
12979: An appropriate exception may be thrown, but a memory fault or other
12980: problem is more probable.
12981: 
12982: @item I/O exception reading or closing @i{file-id} (@code{INCLUDE-FILE}, @code{INCLUDED}):
12983: @cindex @code{INCLUDE-FILE}, I/O exception reading or closing @i{file-id}
12984: @cindex @code{INCLUDED}, I/O exception reading or closing @i{file-id}
12985: The @i{ior} produced by the operation, that discovered the problem, is
12986: thrown.
12987: 
12988: @item named file cannot be opened (@code{INCLUDED}):
12989: @cindex @code{INCLUDED}, named file cannot be opened
12990: The @i{ior} produced by @code{open-file} is thrown.
12991: 
12992: @item requesting an unmapped block number:
12993: @cindex unmapped block numbers
12994: There are no unmapped legal block numbers. On some operating systems,
12995: writing a block with a large number may overflow the file system and
12996: have an error message as consequence.
12997: 
12998: @item using @code{source-id} when @code{blk} is non-zero:
12999: @cindex @code{SOURCE-ID}, behaviour when @code{BLK} is non-zero
13000: @code{source-id} performs its function. Typically it will give the id of
13001: the source which loaded the block. (Better ideas?)
13002: 
13003: @end table
13004: 
13005: 
13006: @c =====================================================================
13007: @node  The optional Floating-Point word set, The optional Locals word set, The optional File-Access word set, ANS conformance
13008: @section The optional Floating-Point word set
13009: @c =====================================================================
13010: @cindex system documentation, floating-point words
13011: @cindex floating-point words, system documentation
13012: 
13013: @menu
13014: * floating-idef::               Implementation Defined Options
13015: * floating-ambcond::            Ambiguous Conditions            
13016: @end menu
13017: 
13018: 
13019: @c ---------------------------------------------------------------------
13020: @node floating-idef, floating-ambcond, The optional Floating-Point word set, The optional Floating-Point word set
13021: @subsection Implementation Defined Options
13022: @c ---------------------------------------------------------------------
13023: @cindex implementation-defined options, floating-point words
13024: @cindex floating-point words, implementation-defined options
13025: 
13026: @table @i
13027: @item format and range of floating point numbers:
13028: @cindex format and range of floating point numbers
13029: @cindex floating point numbers, format and range
13030: System-dependent; the @code{double} type of C.
13031: 
13032: @item results of @code{REPRESENT} when @i{float} is out of range:
13033: @cindex  @code{REPRESENT}, results when @i{float} is out of range
13034: System dependent; @code{REPRESENT} is implemented using the C library
13035: function @code{ecvt()} and inherits its behaviour in this respect.
13036: 
13037: @item rounding or truncation of floating-point numbers:
13038: @cindex rounding of floating-point numbers
13039: @cindex truncation of floating-point numbers
13040: @cindex floating-point numbers, rounding or truncation
13041: System dependent; the rounding behaviour is inherited from the hosting C
13042: compiler. IEEE-FP-based (i.e., most) systems by default round to
13043: nearest, and break ties by rounding to even (i.e., such that the last
13044: bit of the mantissa is 0).
13045: 
13046: @item size of floating-point stack:
13047: @cindex floating-point stack size
13048: @code{s" FLOATING-STACK" environment? drop .} gives the total size of
13049: the floating-point stack (in floats). You can specify this on startup
13050: with the command-line option @code{-f} (@pxref{Invoking Gforth}).
13051: 
13052: @item width of floating-point stack:
13053: @cindex floating-point stack width 
13054: @code{1 floats}.
13055: 
13056: @end table
13057: 
13058: 
13059: @c ---------------------------------------------------------------------
13060: @node floating-ambcond,  , floating-idef, The optional Floating-Point word set
13061: @subsection Ambiguous conditions
13062: @c ---------------------------------------------------------------------
13063: @cindex floating-point words, ambiguous conditions
13064: @cindex ambiguous conditions, floating-point words
13065: 
13066: @table @i
13067: @item @code{df@@} or @code{df!} used with an address that is not double-float  aligned:
13068: @cindex @code{df@@} or @code{df!} used with an address that is not double-float  aligned
13069: System-dependent. Typically results in a @code{-23 THROW} like other
13070: alignment violations.
13071: 
13072: @item @code{f@@} or @code{f!} used with an address that is not float  aligned:
13073: @cindex @code{f@@} used with an address that is not float aligned
13074: @cindex @code{f!} used with an address that is not float aligned
13075: System-dependent. Typically results in a @code{-23 THROW} like other
13076: alignment violations.
13077: 
13078: @item floating-point result out of range:
13079: @cindex floating-point result out of range
13080: System-dependent. Can result in a @code{-43 throw} (floating point
13081: overflow), @code{-54 throw} (floating point underflow), @code{-41 throw}
13082: (floating point inexact result), @code{-55 THROW} (Floating-point
13083: unidentified fault), or can produce a special value representing, e.g.,
13084: Infinity.
13085: 
13086: @item @code{sf@@} or @code{sf!} used with an address that is not single-float  aligned:
13087: @cindex @code{sf@@} or @code{sf!} used with an address that is not single-float  aligned
13088: System-dependent. Typically results in an alignment fault like other
13089: alignment violations.
13090: 
13091: @item @code{base} is not decimal (@code{REPRESENT}, @code{F.}, @code{FE.}, @code{FS.}):
13092: @cindex @code{base} is not decimal (@code{REPRESENT}, @code{F.}, @code{FE.}, @code{FS.})
13093: The floating-point number is converted into decimal nonetheless.
13094: 
13095: @item Both arguments are equal to zero (@code{FATAN2}):
13096: @cindex @code{FATAN2}, both arguments are equal to zero
13097: System-dependent. @code{FATAN2} is implemented using the C library
13098: function @code{atan2()}.
13099: 
13100: @item Using @code{FTAN} on an argument @i{r1} where cos(@i{r1}) is zero:
13101: @cindex @code{FTAN} on an argument @i{r1} where cos(@i{r1}) is zero
13102: System-dependent. Anyway, typically the cos of @i{r1} will not be zero
13103: because of small errors and the tan will be a very large (or very small)
13104: but finite number.
13105: 
13106: @item @i{d} cannot be presented precisely as a float in @code{D>F}:
13107: @cindex @code{D>F}, @i{d} cannot be presented precisely as a float
13108: The result is rounded to the nearest float.
13109: 
13110: @item dividing by zero:
13111: @cindex dividing by zero, floating-point
13112: @cindex floating-point dividing by zero
13113: @cindex floating-point unidentified fault, FP divide-by-zero
13114: Platform-dependent; can produce an Infinity, NaN, @code{-42 throw}
13115: (floating point divide by zero) or @code{-55 throw} (Floating-point
13116: unidentified fault).
13117: 
13118: @item exponent too big for conversion (@code{DF!}, @code{DF@@}, @code{SF!}, @code{SF@@}):
13119: @cindex exponent too big for conversion (@code{DF!}, @code{DF@@}, @code{SF!}, @code{SF@@})
13120: System dependent. On IEEE-FP based systems the number is converted into
13121: an infinity.
13122: 
13123: @item @i{float}<1 (@code{FACOSH}):
13124: @cindex @code{FACOSH}, @i{float}<1
13125: @cindex floating-point unidentified fault, @code{FACOSH}
13126: Platform-dependent; on IEEE-FP systems typically produces a NaN.
13127: 
13128: @item @i{float}=<-1 (@code{FLNP1}):
13129: @cindex @code{FLNP1}, @i{float}=<-1
13130: @cindex floating-point unidentified fault, @code{FLNP1}
13131: Platform-dependent; on IEEE-FP systems typically produces a NaN (or a
13132: negative infinity for @i{float}=-1).
13133: 
13134: @item @i{float}=<0 (@code{FLN}, @code{FLOG}):
13135: @cindex @code{FLN}, @i{float}=<0
13136: @cindex @code{FLOG}, @i{float}=<0
13137: @cindex floating-point unidentified fault, @code{FLN} or @code{FLOG}
13138: Platform-dependent; on IEEE-FP systems typically produces a NaN (or a
13139: negative infinity for @i{float}=0).
13140: 
13141: @item @i{float}<0 (@code{FASINH}, @code{FSQRT}):
13142: @cindex @code{FASINH}, @i{float}<0
13143: @cindex @code{FSQRT}, @i{float}<0
13144: @cindex floating-point unidentified fault, @code{FASINH} or @code{FSQRT}
13145: Platform-dependent; for @code{fsqrt} this typically gives a NaN, for
13146: @code{fasinh} some platforms produce a NaN, others a number (bug in the
13147: C library?).
13148: 
13149: @item |@i{float}|>1 (@code{FACOS}, @code{FASIN}, @code{FATANH}):
13150: @cindex @code{FACOS}, |@i{float}|>1
13151: @cindex @code{FASIN}, |@i{float}|>1
13152: @cindex @code{FATANH}, |@i{float}|>1
13153: @cindex floating-point unidentified fault, @code{FACOS}, @code{FASIN} or @code{FATANH}
13154: Platform-dependent; IEEE-FP systems typically produce a NaN.
13155: 
13156: @item integer part of float cannot be represented by @i{d} in @code{F>D}:
13157: @cindex @code{F>D}, integer part of float cannot be represented by @i{d}
13158: @cindex floating-point unidentified fault, @code{F>D}
13159: Platform-dependent; typically, some double number is produced and no
13160: error is reported.
13161: 
13162: @item string larger than pictured numeric output area (@code{f.}, @code{fe.}, @code{fs.}):
13163: @cindex string larger than pictured numeric output area (@code{f.}, @code{fe.}, @code{fs.})
13164: @code{Precision} characters of the numeric output area are used.  If
13165: @code{precision} is too high, these words will smash the data or code
13166: close to @code{here}.
13167: @end table
13168: 
13169: @c =====================================================================
13170: @node  The optional Locals word set, The optional Memory-Allocation word set, The optional Floating-Point word set, ANS conformance
13171: @section The optional Locals word set
13172: @c =====================================================================
13173: @cindex system documentation, locals words
13174: @cindex locals words, system documentation
13175: 
13176: @menu
13177: * locals-idef::                 Implementation Defined Options                 
13178: * locals-ambcond::              Ambiguous Conditions              
13179: @end menu
13180: 
13181: 
13182: @c ---------------------------------------------------------------------
13183: @node locals-idef, locals-ambcond, The optional Locals word set, The optional Locals word set
13184: @subsection Implementation Defined Options
13185: @c ---------------------------------------------------------------------
13186: @cindex implementation-defined options, locals words
13187: @cindex locals words, implementation-defined options
13188: 
13189: @table @i
13190: @item maximum number of locals in a definition:
13191: @cindex maximum number of locals in a definition
13192: @cindex locals, maximum number in a definition
13193: @code{s" #locals" environment? drop .}. Currently 15. This is a lower
13194: bound, e.g., on a 32-bit machine there can be 41 locals of up to 8
13195: characters. The number of locals in a definition is bounded by the size
13196: of locals-buffer, which contains the names of the locals.
13197: 
13198: @end table
13199: 
13200: 
13201: @c ---------------------------------------------------------------------
13202: @node locals-ambcond,  , locals-idef, The optional Locals word set
13203: @subsection Ambiguous conditions
13204: @c ---------------------------------------------------------------------
13205: @cindex locals words, ambiguous conditions
13206: @cindex ambiguous conditions, locals words
13207: 
13208: @table @i
13209: @item executing a named local in interpretation state:
13210: @cindex local in interpretation state
13211: @cindex Interpreting a compile-only word, for a local
13212: Locals have no interpretation semantics. If you try to perform the
13213: interpretation semantics, you will get a @code{-14 throw} somewhere
13214: (Interpreting a compile-only word). If you perform the compilation
13215: semantics, the locals access will be compiled (irrespective of state).
13216: 
13217: @item @i{name} not defined by @code{VALUE} or @code{(LOCAL)} (@code{TO}):
13218: @cindex name not defined by @code{VALUE} or @code{(LOCAL)} used by @code{TO}
13219: @cindex @code{TO} on non-@code{VALUE}s and non-locals
13220: @cindex Invalid name argument, @code{TO}
13221: @code{-32 throw} (Invalid name argument)
13222: 
13223: @end table
13224: 
13225: 
13226: @c =====================================================================
13227: @node  The optional Memory-Allocation word set, The optional Programming-Tools word set, The optional Locals word set, ANS conformance
13228: @section The optional Memory-Allocation word set
13229: @c =====================================================================
13230: @cindex system documentation, memory-allocation words
13231: @cindex memory-allocation words, system documentation
13232: 
13233: @menu
13234: * memory-idef::                 Implementation Defined Options                 
13235: @end menu
13236: 
13237: 
13238: @c ---------------------------------------------------------------------
13239: @node memory-idef,  , The optional Memory-Allocation word set, The optional Memory-Allocation word set
13240: @subsection Implementation Defined Options
13241: @c ---------------------------------------------------------------------
13242: @cindex implementation-defined options, memory-allocation words
13243: @cindex memory-allocation words, implementation-defined options
13244: 
13245: @table @i
13246: @item values and meaning of @i{ior}:
13247: @cindex  @i{ior} values and meaning
13248: The @i{ior}s returned by the file and memory allocation words are
13249: intended as throw codes. They typically are in the range
13250: -512@minus{}-2047 of OS errors.  The mapping from OS error numbers to
13251: @i{ior}s is -512@minus{}@i{errno}.
13252: 
13253: @end table
13254: 
13255: @c =====================================================================
13256: @node  The optional Programming-Tools word set, The optional Search-Order word set, The optional Memory-Allocation word set, ANS conformance
13257: @section The optional Programming-Tools word set
13258: @c =====================================================================
13259: @cindex system documentation, programming-tools words
13260: @cindex programming-tools words, system documentation
13261: 
13262: @menu
13263: * programming-idef::            Implementation Defined Options            
13264: * programming-ambcond::         Ambiguous Conditions         
13265: @end menu
13266: 
13267: 
13268: @c ---------------------------------------------------------------------
13269: @node programming-idef, programming-ambcond, The optional Programming-Tools word set, The optional Programming-Tools word set
13270: @subsection Implementation Defined Options
13271: @c ---------------------------------------------------------------------
13272: @cindex implementation-defined options, programming-tools words
13273: @cindex programming-tools words, implementation-defined options
13274: 
13275: @table @i
13276: @item ending sequence for input following @code{;CODE} and @code{CODE}:
13277: @cindex @code{;CODE} ending sequence
13278: @cindex @code{CODE} ending sequence
13279: @code{END-CODE}
13280: 
13281: @item manner of processing input following @code{;CODE} and @code{CODE}:
13282: @cindex @code{;CODE}, processing input
13283: @cindex @code{CODE}, processing input
13284: The @code{ASSEMBLER} vocabulary is pushed on the search order stack, and
13285: the input is processed by the text interpreter, (starting) in interpret
13286: state.
13287: 
13288: @item search order capability for @code{EDITOR} and @code{ASSEMBLER}:
13289: @cindex @code{ASSEMBLER}, search order capability
13290: The ANS Forth search order word set.
13291: 
13292: @item source and format of display by @code{SEE}:
13293: @cindex @code{SEE}, source and format of output
13294: The source for @code{see} is the executable code used by the inner
13295: interpreter.  The current @code{see} tries to output Forth source code
13296: (and on some platforms, assembly code for primitives) as well as
13297: possible.
13298: 
13299: @end table
13300: 
13301: @c ---------------------------------------------------------------------
13302: @node programming-ambcond,  , programming-idef, The optional Programming-Tools word set
13303: @subsection Ambiguous conditions
13304: @c ---------------------------------------------------------------------
13305: @cindex programming-tools words, ambiguous conditions
13306: @cindex ambiguous conditions, programming-tools words
13307: 
13308: @table @i
13309: 
13310: @item deleting the compilation word list (@code{FORGET}):
13311: @cindex @code{FORGET}, deleting the compilation word list
13312: Not implemented (yet).
13313: 
13314: @item fewer than @i{u}+1 items on the control-flow stack (@code{CS-PICK}, @code{CS-ROLL}):
13315: @cindex @code{CS-PICK}, fewer than @i{u}+1 items on the control flow-stack
13316: @cindex @code{CS-ROLL}, fewer than @i{u}+1 items on the control flow-stack
13317: @cindex control-flow stack underflow
13318: This typically results in an @code{abort"} with a descriptive error
13319: message (may change into a @code{-22 throw} (Control structure mismatch)
13320: in the future). You may also get a memory access error. If you are
13321: unlucky, this ambiguous condition is not caught.
13322: 
13323: @item @i{name} can't be found (@code{FORGET}):
13324: @cindex @code{FORGET}, @i{name} can't be found
13325: Not implemented (yet).
13326: 
13327: @item @i{name} not defined via @code{CREATE}:
13328: @cindex @code{;CODE}, @i{name} not defined via @code{CREATE}
13329: @code{;CODE} behaves like @code{DOES>} in this respect, i.e., it changes
13330: the execution semantics of the last defined word no matter how it was
13331: defined.
13332: 
13333: @item @code{POSTPONE} applied to @code{[IF]}:
13334: @cindex @code{POSTPONE} applied to @code{[IF]}
13335: @cindex @code{[IF]} and @code{POSTPONE}
13336: After defining @code{: X POSTPONE [IF] ; IMMEDIATE}. @code{X} is
13337: equivalent to @code{[IF]}.
13338: 
13339: @item reaching the end of the input source before matching @code{[ELSE]} or @code{[THEN]}:
13340: @cindex @code{[IF]}, end of the input source before matching @code{[ELSE]} or @code{[THEN]}
13341: Continue in the same state of conditional compilation in the next outer
13342: input source. Currently there is no warning to the user about this.
13343: 
13344: @item removing a needed definition (@code{FORGET}):
13345: @cindex @code{FORGET}, removing a needed definition
13346: Not implemented (yet).
13347: 
13348: @end table
13349: 
13350: 
13351: @c =====================================================================
13352: @node  The optional Search-Order word set,  , The optional Programming-Tools word set, ANS conformance
13353: @section The optional Search-Order word set
13354: @c =====================================================================
13355: @cindex system documentation, search-order words
13356: @cindex search-order words, system documentation
13357: 
13358: @menu
13359: * search-idef::                 Implementation Defined Options                 
13360: * search-ambcond::              Ambiguous Conditions              
13361: @end menu
13362: 
13363: 
13364: @c ---------------------------------------------------------------------
13365: @node search-idef, search-ambcond, The optional Search-Order word set, The optional Search-Order word set
13366: @subsection Implementation Defined Options
13367: @c ---------------------------------------------------------------------
13368: @cindex implementation-defined options, search-order words
13369: @cindex search-order words, implementation-defined options
13370: 
13371: @table @i
13372: @item maximum number of word lists in search order:
13373: @cindex maximum number of word lists in search order
13374: @cindex search order, maximum depth
13375: @code{s" wordlists" environment? drop .}. Currently 16.
13376: 
13377: @item minimum search order:
13378: @cindex minimum search order
13379: @cindex search order, minimum
13380: @code{root root}.
13381: 
13382: @end table
13383: 
13384: @c ---------------------------------------------------------------------
13385: @node search-ambcond,  , search-idef, The optional Search-Order word set
13386: @subsection Ambiguous conditions
13387: @c ---------------------------------------------------------------------
13388: @cindex search-order words, ambiguous conditions
13389: @cindex ambiguous conditions, search-order words
13390: 
13391: @table @i
13392: @item changing the compilation word list (during compilation):
13393: @cindex changing the compilation word list (during compilation)
13394: @cindex compilation word list, change before definition ends
13395: The word is entered into the word list that was the compilation word list
13396: at the start of the definition. Any changes to the name field (e.g.,
13397: @code{immediate}) or the code field (e.g., when executing @code{DOES>})
13398: are applied to the latest defined word (as reported by @code{last} or
13399: @code{lastxt}), if possible, irrespective of the compilation word list.
13400: 
13401: @item search order empty (@code{previous}):
13402: @cindex @code{previous}, search order empty
13403: @cindex vocstack empty, @code{previous}
13404: @code{abort" Vocstack empty"}.
13405: 
13406: @item too many word lists in search order (@code{also}):
13407: @cindex @code{also}, too many word lists in search order
13408: @cindex vocstack full, @code{also}
13409: @code{abort" Vocstack full"}.
13410: 
13411: @end table
13412: 
13413: @c ***************************************************************
13414: @node Standard vs Extensions, Model, ANS conformance, Top
13415: @chapter Should I use Gforth extensions?
13416: @cindex Gforth extensions
13417: 
13418: As you read through the rest of this manual, you will see documentation
13419: for @i{Standard} words, and documentation for some appealing Gforth
13420: @i{extensions}. You might ask yourself the question: @i{``Should I
13421: restrict myself to the standard, or should I use the extensions?''}
13422: 
13423: The answer depends on the goals you have for the program you are working
13424: on:
13425: 
13426: @itemize @bullet
13427: 
13428: @item Is it just for yourself or do you want to share it with others?
13429: 
13430: @item
13431: If you want to share it, do the others all use Gforth?
13432: 
13433: @item
13434: If it is just for yourself, do you want to restrict yourself to Gforth?
13435: 
13436: @end itemize
13437: 
13438: If restricting the program to Gforth is ok, then there is no reason not
13439: to use extensions.  It is still a good idea to keep to the standard
13440: where it is easy, in case you want to reuse these parts in another
13441: program that you want to be portable.
13442: 
13443: If you want to be able to port the program to other Forth systems, there
13444: are the following points to consider:
13445: 
13446: @itemize @bullet
13447: 
13448: @item
13449: Most Forth systems that are being maintained support the ANS Forth
13450: standard.  So if your program complies with the standard, it will be
13451: portable among many systems.
13452: 
13453: @item
13454: A number of the Gforth extensions can be implemented in ANS Forth using
13455: public-domain files provided in the @file{compat/} directory. These are
13456: mentioned in the text in passing.  There is no reason not to use these
13457: extensions, your program will still be ANS Forth compliant; just include
13458: the appropriate compat files with your program.
13459: 
13460: @item
13461: The tool @file{ans-report.fs} (@pxref{ANS Report}) makes it easy to
13462: analyse your program and determine what non-Standard words it relies
13463: upon.  However, it does not check whether you use standard words in a
13464: non-standard way.
13465: 
13466: @item
13467: Some techniques are not standardized by ANS Forth, and are hard or
13468: impossible to implement in a standard way, but can be implemented in
13469: most Forth systems easily, and usually in similar ways (e.g., accessing
13470: word headers).  Forth has a rich historical precedent for programmers
13471: taking advantage of implementation-dependent features of their tools
13472: (for example, relying on a knowledge of the dictionary
13473: structure). Sometimes these techniques are necessary to extract every
13474: last bit of performance from the hardware, sometimes they are just a
13475: programming shorthand.
13476: 
13477: @item
13478: Does using a Gforth extension save more work than the porting this part
13479: to other Forth systems (if any) will cost?
13480: 
13481: @item
13482: Is the additional functionality worth the reduction in portability and
13483: the additional porting problems?
13484: 
13485: @end itemize
13486: 
13487: In order to perform these consideratios, you need to know what's
13488: standard and what's not.  This manual generally states if something is
13489: non-standard, but the authoritative source is the
13490: @uref{http://www.taygeta.com/forth/dpans.html,standard document}.
13491: Appendix A of the Standard (@var{Rationale}) provides a valuable insight
13492: into the thought processes of the technical committee.
13493: 
13494: Note also that portability between Forth systems is not the only
13495: portability issue; there is also the issue of portability between
13496: different platforms (processor/OS combinations).
13497: 
13498: @c ***************************************************************
13499: @node Model, Integrating Gforth, Standard vs Extensions, Top
13500: @chapter Model
13501: 
13502: This chapter has yet to be written. It will contain information, on
13503: which internal structures you can rely.
13504: 
13505: @c ***************************************************************
13506: @node Integrating Gforth, Emacs and Gforth, Model, Top
13507: @chapter Integrating Gforth into C programs
13508: 
13509: This is not yet implemented.
13510: 
13511: Several people like to use Forth as scripting language for applications
13512: that are otherwise written in C, C++, or some other language.
13513: 
13514: The Forth system ATLAST provides facilities for embedding it into
13515: applications; unfortunately it has several disadvantages: most
13516: importantly, it is not based on ANS Forth, and it is apparently dead
13517: (i.e., not developed further and not supported). The facilities
13518: provided by Gforth in this area are inspired by ATLAST's facilities, so
13519: making the switch should not be hard.
13520: 
13521: We also tried to design the interface such that it can easily be
13522: implemented by other Forth systems, so that we may one day arrive at a
13523: standardized interface. Such a standard interface would allow you to
13524: replace the Forth system without having to rewrite C code.
13525: 
13526: You embed the Gforth interpreter by linking with the library
13527: @code{libgforth.a} (give the compiler the option @code{-lgforth}).  All
13528: global symbols in this library that belong to the interface, have the
13529: prefix @code{forth_}. (Global symbols that are used internally have the
13530: prefix @code{gforth_}).
13531: 
13532: You can include the declarations of Forth types and the functions and
13533: variables of the interface with @code{#include <forth.h>}.
13534: 
13535: Types.
13536: 
13537: Variables.
13538: 
13539: Data and FP Stack pointer. Area sizes.
13540: 
13541: functions.
13542: 
13543: forth_init(imagefile)
13544: forth_evaluate(string) exceptions?
13545: forth_goto(address) (or forth_execute(xt)?)
13546: forth_continue() (a corountining mechanism)
13547: 
13548: Adding primitives.
13549: 
13550: No checking.
13551: 
13552: Signals?
13553: 
13554: Accessing the Stacks
13555: 
13556: @c ******************************************************************
13557: @node Emacs and Gforth, Image Files, Integrating Gforth, Top
13558: @chapter Emacs and Gforth
13559: @cindex Emacs and Gforth
13560: 
13561: @cindex @file{gforth.el}
13562: @cindex @file{forth.el}
13563: @cindex Rydqvist, Goran
13564: @cindex Kuehling, David
13565: @cindex comment editing commands
13566: @cindex @code{\}, editing with Emacs
13567: @cindex debug tracer editing commands
13568: @cindex @code{~~}, removal with Emacs
13569: @cindex Forth mode in Emacs
13570: 
13571: Gforth comes with @file{gforth.el}, an improved version of
13572: @file{forth.el} by Goran Rydqvist (included in the TILE package). The
13573: improvements are:
13574: 
13575: @itemize @bullet
13576: @item
13577: A better handling of indentation.
13578: @item
13579: A custom hilighting engine for Forth-code.
13580: @item
13581: Comment paragraph filling (@kbd{M-q})
13582: @item
13583: Commenting (@kbd{C-x \}) and uncommenting (@kbd{C-u C-x \}) of regions
13584: @item
13585: Removal of debugging tracers (@kbd{C-x ~}, @pxref{Debugging}).
13586: @item
13587: Support of the @code{info-lookup} feature for looking up the
13588: documentation of a word.
13589: @item
13590: Support for reading and writing blocks files.
13591: @end itemize
13592: 
13593: To get a basic description of these features, enter Forth mode and
13594: type @kbd{C-h m}.
13595: 
13596: @cindex source location of error or debugging output in Emacs
13597: @cindex error output, finding the source location in Emacs
13598: @cindex debugging output, finding the source location in Emacs
13599: In addition, Gforth supports Emacs quite well: The source code locations
13600: given in error messages, debugging output (from @code{~~}) and failed
13601: assertion messages are in the right format for Emacs' compilation mode
13602: (@pxref{Compilation, , Running Compilations under Emacs, emacs, Emacs
13603: Manual}) so the source location corresponding to an error or other
13604: message is only a few keystrokes away (@kbd{C-x `} for the next error,
13605: @kbd{C-c C-c} for the error under the cursor).
13606: 
13607: @cindex viewing the documentation of a word in Emacs
13608: @cindex context-sensitive help
13609: Moreover, for words documented in this manual, you can look up the
13610: glossary entry quickly by using @kbd{C-h TAB}
13611: (@code{info-lookup-symbol}, @pxref{Documentation, ,Documentation
13612: Commands, emacs, Emacs Manual}).  This feature requires Emacs 20.3 or
13613: later and does not work for words containing @code{:}.
13614: 
13615: @menu
13616: * Installing gforth.el::        Making Emacs aware of Forth.
13617: * Emacs Tags::                  Viewing the source of a word in Emacs.
13618: * Hilighting::                  Making Forth code look prettier.
13619: * Auto-Indentation::            Customizing auto-indentation.
13620: * Blocks Files::                Reading and writing blocks files.
13621: @end menu
13622: 
13623: @c ----------------------------------
13624: @node Installing gforth.el, Emacs Tags, Emacs and Gforth, Emacs and Gforth
13625: @section Installing gforth.el
13626: @cindex @file{.emacs}
13627: @cindex @file{gforth.el}, installation
13628: To make the features from @file{gforth.el} available in Emacs, add
13629: the following lines to your @file{.emacs} file:
13630: 
13631: @example
13632: (autoload 'forth-mode "gforth.el")
13633: (setq auto-mode-alist (cons '("\\.fs\\'" . forth-mode) 
13634: 			    auto-mode-alist))
13635: (autoload 'forth-block-mode "gforth.el")
13636: (setq auto-mode-alist (cons '("\\.fb\\'" . forth-block-mode) 
13637: 			    auto-mode-alist))
13638: (add-hook 'forth-mode-hook (function (lambda ()
13639:    ;; customize variables here:
13640:    (setq forth-indent-level 4)
13641:    (setq forth-minor-indent-level 2)
13642:    (setq forth-hilight-level 3)
13643:    ;;; ...
13644: )))
13645: @end example
13646: 
13647: @c ----------------------------------
13648: @node Emacs Tags, Hilighting, Installing gforth.el, Emacs and Gforth
13649: @section Emacs Tags
13650: @cindex @file{TAGS} file
13651: @cindex @file{etags.fs}
13652: @cindex viewing the source of a word in Emacs
13653: @cindex @code{require}, placement in files
13654: @cindex @code{include}, placement in files
13655: If you @code{require} @file{etags.fs}, a new @file{TAGS} file will be
13656: produced (@pxref{Tags, , Tags Tables, emacs, Emacs Manual}) that
13657: contains the definitions of all words defined afterwards. You can then
13658: find the source for a word using @kbd{M-.}. Note that Emacs can use
13659: several tags files at the same time (e.g., one for the Gforth sources
13660: and one for your program, @pxref{Select Tags Table,,Selecting a Tags
13661: Table,emacs, Emacs Manual}). The TAGS file for the preloaded words is
13662: @file{$(datadir)/gforth/$(VERSION)/TAGS} (e.g.,
13663: @file{/usr/local/share/gforth/0.2.0/TAGS}).  To get the best behaviour
13664: with @file{etags.fs}, you should avoid putting definitions both before
13665: and after @code{require} etc., otherwise you will see the same file
13666: visited several times by commands like @code{tags-search}.
13667: 
13668: @c ----------------------------------
13669: @node Hilighting, Auto-Indentation, Emacs Tags, Emacs and Gforth
13670: @section Hilighting
13671: @cindex hilighting Forth code in Emacs
13672: @cindex highlighting Forth code in Emacs
13673: @file{gforth.el} comes with a custom source hilighting engine.  When
13674: you open a file in @code{forth-mode}, it will be completely parsed,
13675: assigning faces to keywords, comments, strings etc.  While you edit
13676: the file, modified regions get parsed and updated on-the-fly. 
13677: 
13678: Use the variable `forth-hilight-level' to change the level of
13679: decoration from 0 (no hilighting at all) to 3 (the default).  Even if
13680: you set the hilighting level to 0, the parser will still work in the
13681: background, collecting information about whether regions of text are
13682: ``compiled'' or ``interpreted''.  Those information are required for
13683: auto-indentation to work properly.  Set `forth-disable-parser' to
13684: non-nil if your computer is too slow to handle parsing.  This will
13685: have an impact on the smartness of the auto-indentation engine,
13686: though.
13687: 
13688: Sometimes Forth sources define new features that should be hilighted,
13689: new control structures, defining-words etc.  You can use the variable
13690: `forth-custom-words' to make @code{forth-mode} hilight additional
13691: words and constructs.  See the docstring of `forth-words' for details
13692: (in Emacs, type @kbd{C-h v forth-words}).
13693: 
13694: `forth-custom-words' is meant to be customized in your
13695: @file{.emacs} file.  To customize hilighing in a file-specific manner,
13696: set `forth-local-words' in a local-variables section at the end of
13697: your source file (@pxref{Local Variables in Files,, Variables, emacs, Emacs Manual}).
13698: 
13699: Example:
13700: @example
13701: 0 [IF]
13702:    Local Variables:
13703:    forth-local-words:
13704:       ((("t:") definition-starter (font-lock-keyword-face . 1)
13705:         "[ \t\n]" t name (font-lock-function-name-face . 3))
13706:        ((";t") definition-ender (font-lock-keyword-face . 1)))
13707:    End:
13708: [THEN]
13709: @end example
13710: 
13711: @c ----------------------------------
13712: @node Auto-Indentation, Blocks Files, Hilighting, Emacs and Gforth
13713: @section Auto-Indentation
13714: @cindex auto-indentation of Forth code in Emacs
13715: @cindex indentation of Forth code in Emacs
13716: @code{forth-mode} automatically tries to indent lines in a smart way,
13717: whenever you type @key{TAB} or break a line with @kbd{C-m}.
13718: 
13719: Simple customization can be achieved by setting
13720: `forth-indent-level' and `forth-minor-indent-level' in your
13721: @file{.emacs} file. For historical reasons @file{gforth.el} indents
13722: per default by multiples of 4 columns.  To use the more traditional
13723: 3-column indentation, add the following lines to your @file{.emacs}:
13724: 
13725: @example
13726: (add-hook 'forth-mode-hook (function (lambda ()
13727:    ;; customize variables here:
13728:    (setq forth-indent-level 3)
13729:    (setq forth-minor-indent-level 1)
13730: )))
13731: @end example
13732: 
13733: If you want indentation to recognize non-default words, customize it
13734: by setting `forth-custom-indent-words' in your @file{.emacs}.  See the
13735: docstring of `forth-indent-words' for details (in Emacs, type @kbd{C-h
13736: v forth-indent-words}).
13737: 
13738: To customize indentation in a file-specific manner, set
13739: `forth-local-indent-words' in a local-variables section at the end of
13740: your source file (@pxref{Local Variables in Files, Variables,,emacs,
13741: Emacs Manual}).
13742: 
13743: Example:
13744: @example
13745: 0 [IF]
13746:    Local Variables:
13747:    forth-local-indent-words:
13748:       ((("t:") (0 . 2) (0 . 2))
13749:        ((";t") (-2 . 0) (0 . -2)))
13750:    End:
13751: [THEN]
13752: @end example
13753: 
13754: @c ----------------------------------
13755: @node Blocks Files,  , Auto-Indentation, Emacs and Gforth
13756: @section Blocks Files
13757: @cindex blocks files, use with Emacs
13758: @code{forth-mode} Autodetects blocks files by checking whether the
13759: length of the first line exceeds 1023 characters.  It then tries to
13760: convert the file into normal text format.  When you save the file, it
13761: will be written to disk as normal stream-source file.
13762: 
13763: If you want to write blocks files, use @code{forth-blocks-mode}.  It
13764: inherits all the features from @code{forth-mode}, plus some additions:
13765: 
13766: @itemize @bullet
13767: @item
13768: Files are written to disk in blocks file format.
13769: @item
13770: Screen numbers are displayed in the mode line (enumerated beginning
13771: with the value of `forth-block-base')
13772: @item
13773: Warnings are displayed when lines exceed 64 characters.
13774: @item
13775: The beginning of the currently edited block is marked with an
13776: overlay-arrow. 
13777: @end itemize
13778: 
13779: There are some restrictions you should be aware of.  When you open a
13780: blocks file that contains tabulator or newline characters, these
13781: characters will be translated into spaces when the file is written
13782: back to disk.  If tabs or newlines are encountered during blocks file
13783: reading, an error is output to the echo area. So have a look at the
13784: `*Messages*' buffer, when Emacs' bell rings during reading.
13785: 
13786: Please consult the docstring of @code{forth-blocks-mode} for more
13787: information by typing @kbd{C-h v forth-blocks-mode}).
13788: 
13789: @c ******************************************************************
13790: @node Image Files, Engine, Emacs and Gforth, Top
13791: @chapter Image Files
13792: @cindex image file
13793: @cindex @file{.fi} files
13794: @cindex precompiled Forth code
13795: @cindex dictionary in persistent form
13796: @cindex persistent form of dictionary
13797: 
13798: An image file is a file containing an image of the Forth dictionary,
13799: i.e., compiled Forth code and data residing in the dictionary.  By
13800: convention, we use the extension @code{.fi} for image files.
13801: 
13802: @menu
13803: * Image Licensing Issues::      Distribution terms for images.
13804: * Image File Background::       Why have image files?
13805: * Non-Relocatable Image Files::  don't always work.
13806: * Data-Relocatable Image Files::  are better.
13807: * Fully Relocatable Image Files::  better yet.
13808: * Stack and Dictionary Sizes::  Setting the default sizes for an image.
13809: * Running Image Files::         @code{gforth -i @i{file}} or @i{file}.
13810: * Modifying the Startup Sequence::  and turnkey applications.
13811: @end menu
13812: 
13813: @node Image Licensing Issues, Image File Background, Image Files, Image Files
13814: @section Image Licensing Issues
13815: @cindex license for images
13816: @cindex image license
13817: 
13818: An image created with @code{gforthmi} (@pxref{gforthmi}) or
13819: @code{savesystem} (@pxref{Non-Relocatable Image Files}) includes the
13820: original image; i.e., according to copyright law it is a derived work of
13821: the original image.
13822: 
13823: Since Gforth is distributed under the GNU GPL, the newly created image
13824: falls under the GNU GPL, too. In particular, this means that if you
13825: distribute the image, you have to make all of the sources for the image
13826: available, including those you wrote.  For details see @ref{Copying, ,
13827: GNU General Public License (Section 3)}.
13828: 
13829: If you create an image with @code{cross} (@pxref{cross.fs}), the image
13830: contains only code compiled from the sources you gave it; if none of
13831: these sources is under the GPL, the terms discussed above do not apply
13832: to the image. However, if your image needs an engine (a gforth binary)
13833: that is under the GPL, you should make sure that you distribute both in
13834: a way that is at most a @emph{mere aggregation}, if you don't want the
13835: terms of the GPL to apply to the image.
13836: 
13837: @node Image File Background, Non-Relocatable Image Files, Image Licensing Issues, Image Files
13838: @section Image File Background
13839: @cindex image file background
13840: 
13841: Gforth consists not only of primitives (in the engine), but also of
13842: definitions written in Forth. Since the Forth compiler itself belongs to
13843: those definitions, it is not possible to start the system with the
13844: engine and the Forth source alone. Therefore we provide the Forth
13845: code as an image file in nearly executable form. When Gforth starts up,
13846: a C routine loads the image file into memory, optionally relocates the
13847: addresses, then sets up the memory (stacks etc.) according to
13848: information in the image file, and (finally) starts executing Forth
13849: code.
13850: 
13851: The image file variants represent different compromises between the
13852: goals of making it easy to generate image files and making them
13853: portable.
13854: 
13855: @cindex relocation at run-time
13856: Win32Forth 3.4 and Mitch Bradley's @code{cforth} use relocation at
13857: run-time. This avoids many of the complications discussed below (image
13858: files are data relocatable without further ado), but costs performance
13859: (one addition per memory access).
13860: 
13861: @cindex relocation at load-time
13862: By contrast, the Gforth loader performs relocation at image load time. The
13863: loader also has to replace tokens that represent primitive calls with the
13864: appropriate code-field addresses (or code addresses in the case of
13865: direct threading).
13866: 
13867: There are three kinds of image files, with different degrees of
13868: relocatability: non-relocatable, data-relocatable, and fully relocatable
13869: image files.
13870: 
13871: @cindex image file loader
13872: @cindex relocating loader
13873: @cindex loader for image files
13874: These image file variants have several restrictions in common; they are
13875: caused by the design of the image file loader:
13876: 
13877: @itemize @bullet
13878: @item
13879: There is only one segment; in particular, this means, that an image file
13880: cannot represent @code{ALLOCATE}d memory chunks (and pointers to
13881: them). The contents of the stacks are not represented, either.
13882: 
13883: @item
13884: The only kinds of relocation supported are: adding the same offset to
13885: all cells that represent data addresses; and replacing special tokens
13886: with code addresses or with pieces of machine code.
13887: 
13888: If any complex computations involving addresses are performed, the
13889: results cannot be represented in the image file. Several applications that
13890: use such computations come to mind:
13891: @itemize @minus
13892: @item
13893: Hashing addresses (or data structures which contain addresses) for table
13894: lookup. If you use Gforth's @code{table}s or @code{wordlist}s for this
13895: purpose, you will have no problem, because the hash tables are
13896: recomputed automatically when the system is started. If you use your own
13897: hash tables, you will have to do something similar.
13898: 
13899: @item
13900: There's a cute implementation of doubly-linked lists that uses
13901: @code{XOR}ed addresses. You could represent such lists as singly-linked
13902: in the image file, and restore the doubly-linked representation on
13903: startup.@footnote{In my opinion, though, you should think thrice before
13904: using a doubly-linked list (whatever implementation).}
13905: 
13906: @item
13907: The code addresses of run-time routines like @code{docol:} cannot be
13908: represented in the image file (because their tokens would be replaced by
13909: machine code in direct threaded implementations). As a workaround,
13910: compute these addresses at run-time with @code{>code-address} from the
13911: executions tokens of appropriate words (see the definitions of
13912: @code{docol:} and friends in @file{kernel/getdoers.fs}).
13913: 
13914: @item
13915: On many architectures addresses are represented in machine code in some
13916: shifted or mangled form. You cannot put @code{CODE} words that contain
13917: absolute addresses in this form in a relocatable image file. Workarounds
13918: are representing the address in some relative form (e.g., relative to
13919: the CFA, which is present in some register), or loading the address from
13920: a place where it is stored in a non-mangled form.
13921: @end itemize
13922: @end itemize
13923: 
13924: @node  Non-Relocatable Image Files, Data-Relocatable Image Files, Image File Background, Image Files
13925: @section Non-Relocatable Image Files
13926: @cindex non-relocatable image files
13927: @cindex image file, non-relocatable
13928: 
13929: These files are simple memory dumps of the dictionary. They are specific
13930: to the executable (i.e., @file{gforth} file) they were created
13931: with. What's worse, they are specific to the place on which the
13932: dictionary resided when the image was created. Now, there is no
13933: guarantee that the dictionary will reside at the same place the next
13934: time you start Gforth, so there's no guarantee that a non-relocatable
13935: image will work the next time (Gforth will complain instead of crashing,
13936: though).
13937: 
13938: You can create a non-relocatable image file with
13939: 
13940: 
13941: doc-savesystem
13942: 
13943: 
13944: @node Data-Relocatable Image Files, Fully Relocatable Image Files, Non-Relocatable Image Files, Image Files
13945: @section Data-Relocatable Image Files
13946: @cindex data-relocatable image files
13947: @cindex image file, data-relocatable
13948: 
13949: These files contain relocatable data addresses, but fixed code addresses
13950: (instead of tokens). They are specific to the executable (i.e.,
13951: @file{gforth} file) they were created with. For direct threading on some
13952: architectures (e.g., the i386), data-relocatable images do not work. You
13953: get a data-relocatable image, if you use @file{gforthmi} with a
13954: Gforth binary that is not doubly indirect threaded (@pxref{Fully
13955: Relocatable Image Files}).
13956: 
13957: @node Fully Relocatable Image Files, Stack and Dictionary Sizes, Data-Relocatable Image Files, Image Files
13958: @section Fully Relocatable Image Files
13959: @cindex fully relocatable image files
13960: @cindex image file, fully relocatable
13961: 
13962: @cindex @file{kern*.fi}, relocatability
13963: @cindex @file{gforth.fi}, relocatability
13964: These image files have relocatable data addresses, and tokens for code
13965: addresses. They can be used with different binaries (e.g., with and
13966: without debugging) on the same machine, and even across machines with
13967: the same data formats (byte order, cell size, floating point
13968: format). However, they are usually specific to the version of Gforth
13969: they were created with. The files @file{gforth.fi} and @file{kernl*.fi}
13970: are fully relocatable.
13971: 
13972: There are two ways to create a fully relocatable image file:
13973: 
13974: @menu
13975: * gforthmi::                    The normal way
13976: * cross.fs::                    The hard way
13977: @end menu
13978: 
13979: @node gforthmi, cross.fs, Fully Relocatable Image Files, Fully Relocatable Image Files
13980: @subsection @file{gforthmi}
13981: @cindex @file{comp-i.fs}
13982: @cindex @file{gforthmi}
13983: 
13984: You will usually use @file{gforthmi}. If you want to create an
13985: image @i{file} that contains everything you would load by invoking
13986: Gforth with @code{gforth @i{options}}, you simply say:
13987: @example
13988: gforthmi @i{file} @i{options}
13989: @end example
13990: 
13991: E.g., if you want to create an image @file{asm.fi} that has the file
13992: @file{asm.fs} loaded in addition to the usual stuff, you could do it
13993: like this:
13994: 
13995: @example
13996: gforthmi asm.fi asm.fs
13997: @end example
13998: 
13999: @file{gforthmi} is implemented as a sh script and works like this: It
14000: produces two non-relocatable images for different addresses and then
14001: compares them. Its output reflects this: first you see the output (if
14002: any) of the two Gforth invocations that produce the non-relocatable image
14003: files, then you see the output of the comparing program: It displays the
14004: offset used for data addresses and the offset used for code addresses;
14005: moreover, for each cell that cannot be represented correctly in the
14006: image files, it displays a line like this:
14007: 
14008: @example
14009:      78DC         BFFFFA50         BFFFFA40
14010: @end example
14011: 
14012: This means that at offset $78dc from @code{forthstart}, one input image
14013: contains $bffffa50, and the other contains $bffffa40. Since these cells
14014: cannot be represented correctly in the output image, you should examine
14015: these places in the dictionary and verify that these cells are dead
14016: (i.e., not read before they are written).
14017: 
14018: @cindex --application, @code{gforthmi} option
14019: If you insert the option @code{--application} in front of the image file
14020: name, you will get an image that uses the @code{--appl-image} option
14021: instead of the @code{--image-file} option (@pxref{Invoking
14022: Gforth}). When you execute such an image on Unix (by typing the image
14023: name as command), the Gforth engine will pass all options to the image
14024: instead of trying to interpret them as engine options.
14025: 
14026: If you type @file{gforthmi} with no arguments, it prints some usage
14027: instructions.
14028: 
14029: @cindex @code{savesystem} during @file{gforthmi}
14030: @cindex @code{bye} during @file{gforthmi}
14031: @cindex doubly indirect threaded code
14032: @cindex environment variables
14033: @cindex @code{GFORTHD} -- environment variable
14034: @cindex @code{GFORTH} -- environment variable
14035: @cindex @code{gforth-ditc}
14036: There are a few wrinkles: After processing the passed @i{options}, the
14037: words @code{savesystem} and @code{bye} must be visible. A special doubly
14038: indirect threaded version of the @file{gforth} executable is used for
14039: creating the non-relocatable images; you can pass the exact filename of
14040: this executable through the environment variable @code{GFORTHD}
14041: (default: @file{gforth-ditc}); if you pass a version that is not doubly
14042: indirect threaded, you will not get a fully relocatable image, but a
14043: data-relocatable image (because there is no code address offset). The
14044: normal @file{gforth} executable is used for creating the relocatable
14045: image; you can pass the exact filename of this executable through the
14046: environment variable @code{GFORTH}.
14047: 
14048: @node cross.fs,  , gforthmi, Fully Relocatable Image Files
14049: @subsection @file{cross.fs}
14050: @cindex @file{cross.fs}
14051: @cindex cross-compiler
14052: @cindex metacompiler
14053: @cindex target compiler
14054: 
14055: You can also use @code{cross}, a batch compiler that accepts a Forth-like
14056: programming language (@pxref{Cross Compiler}).
14057: 
14058: @code{cross} allows you to create image files for machines with
14059: different data sizes and data formats than the one used for generating
14060: the image file. You can also use it to create an application image that
14061: does not contain a Forth compiler. These features are bought with
14062: restrictions and inconveniences in programming. E.g., addresses have to
14063: be stored in memory with special words (@code{A!}, @code{A,}, etc.) in
14064: order to make the code relocatable.
14065: 
14066: 
14067: @node Stack and Dictionary Sizes, Running Image Files, Fully Relocatable Image Files, Image Files
14068: @section Stack and Dictionary Sizes
14069: @cindex image file, stack and dictionary sizes
14070: @cindex dictionary size default
14071: @cindex stack size default
14072: 
14073: If you invoke Gforth with a command line flag for the size
14074: (@pxref{Invoking Gforth}), the size you specify is stored in the
14075: dictionary. If you save the dictionary with @code{savesystem} or create
14076: an image with @file{gforthmi}, this size will become the default
14077: for the resulting image file. E.g., the following will create a
14078: fully relocatable version of @file{gforth.fi} with a 1MB dictionary:
14079: 
14080: @example
14081: gforthmi gforth.fi -m 1M
14082: @end example
14083: 
14084: In other words, if you want to set the default size for the dictionary
14085: and the stacks of an image, just invoke @file{gforthmi} with the
14086: appropriate options when creating the image.
14087: 
14088: @cindex stack size, cache-friendly
14089: Note: For cache-friendly behaviour (i.e., good performance), you should
14090: make the sizes of the stacks modulo, say, 2K, somewhat different. E.g.,
14091: the default stack sizes are: data: 16k (mod 2k=0); fp: 15.5k (mod
14092: 2k=1.5k); return: 15k(mod 2k=1k); locals: 14.5k (mod 2k=0.5k).
14093: 
14094: @node Running Image Files, Modifying the Startup Sequence, Stack and Dictionary Sizes, Image Files
14095: @section Running Image Files
14096: @cindex running image files
14097: @cindex invoking image files
14098: @cindex image file invocation
14099: 
14100: @cindex -i, invoke image file
14101: @cindex --image file, invoke image file
14102: You can invoke Gforth with an image file @i{image} instead of the
14103: default @file{gforth.fi} with the @code{-i} flag (@pxref{Invoking Gforth}):
14104: @example
14105: gforth -i @i{image}
14106: @end example
14107: 
14108: @cindex executable image file
14109: @cindex image file, executable
14110: If your operating system supports starting scripts with a line of the
14111: form @code{#! ...}, you just have to type the image file name to start
14112: Gforth with this image file (note that the file extension @code{.fi} is
14113: just a convention). I.e., to run Gforth with the image file @i{image},
14114: you can just type @i{image} instead of @code{gforth -i @i{image}}.
14115: This works because every @code{.fi} file starts with a line of this
14116: format:
14117: 
14118: @example
14119: #! /usr/local/bin/gforth-0.4.0 -i
14120: @end example
14121: 
14122: The file and pathname for the Gforth engine specified on this line is
14123: the specific Gforth executable that it was built against; i.e. the value
14124: of the environment variable @code{GFORTH} at the time that
14125: @file{gforthmi} was executed.
14126: 
14127: You can make use of the same shell capability to make a Forth source
14128: file into an executable. For example, if you place this text in a file:
14129: 
14130: @example
14131: #! /usr/local/bin/gforth
14132: 
14133: ." Hello, world" CR
14134: bye
14135: @end example
14136: 
14137: @noindent
14138: and then make the file executable (chmod +x in Unix), you can run it
14139: directly from the command line. The sequence @code{#!} is used in two
14140: ways; firstly, it is recognised as a ``magic sequence'' by the operating
14141: system@footnote{The Unix kernel actually recognises two types of files:
14142: executable files and files of data, where the data is processed by an
14143: interpreter that is specified on the ``interpreter line'' -- the first
14144: line of the file, starting with the sequence #!. There may be a small
14145: limit (e.g., 32) on the number of characters that may be specified on
14146: the interpreter line.} secondly it is treated as a comment character by
14147: Gforth. Because of the second usage, a space is required between
14148: @code{#!} and the path to the executable (moreover, some Unixes
14149: require the sequence @code{#! /}).
14150: 
14151: The disadvantage of this latter technique, compared with using
14152: @file{gforthmi}, is that it is slightly slower; the Forth source code is
14153: compiled on-the-fly, each time the program is invoked.
14154: 
14155: doc-#!
14156: 
14157: 
14158: @node Modifying the Startup Sequence,  , Running Image Files, Image Files
14159: @section Modifying the Startup Sequence
14160: @cindex startup sequence for image file
14161: @cindex image file initialization sequence
14162: @cindex initialization sequence of image file
14163: 
14164: You can add your own initialization to the startup sequence through the
14165: deferred word @code{'cold}. @code{'cold} is invoked just before the
14166: image-specific command line processing (i.e., loading files and
14167: evaluating (@code{-e}) strings) starts.
14168: 
14169: A sequence for adding your initialization usually looks like this:
14170: 
14171: @example
14172: :noname
14173:     Defers 'cold \ do other initialization stuff (e.g., rehashing wordlists)
14174:     ... \ your stuff
14175: ; IS 'cold
14176: @end example
14177: 
14178: @cindex turnkey image files
14179: @cindex image file, turnkey applications
14180: You can make a turnkey image by letting @code{'cold} execute a word
14181: (your turnkey application) that never returns; instead, it exits Gforth
14182: via @code{bye} or @code{throw}.
14183: 
14184: @cindex command-line arguments, access
14185: @cindex arguments on the command line, access
14186: You can access the (image-specific) command-line arguments through the
14187: variables @code{argc} and @code{argv}. @code{arg} provides convenient
14188: access to @code{argv}.
14189: 
14190: If @code{'cold} exits normally, Gforth processes the command-line
14191: arguments as files to be loaded and strings to be evaluated.  Therefore,
14192: @code{'cold} should remove the arguments it has used in this case.
14193: 
14194: 
14195: 
14196: doc-'cold
14197: doc-argc
14198: doc-argv
14199: doc-arg
14200: 
14201: 
14202: 
14203: @c ******************************************************************
14204: @node Engine, Cross Compiler, Image Files, Top
14205: @chapter Engine
14206: @cindex engine
14207: @cindex virtual machine
14208: 
14209: Reading this chapter is not necessary for programming with Gforth. It
14210: may be helpful for finding your way in the Gforth sources.
14211: 
14212: The ideas in this section have also been published in the following
14213: papers: Bernd Paysan, @cite{ANS fig/GNU/??? Forth} (in German),
14214: Forth-Tagung '93; M. Anton Ertl,
14215: @cite{@uref{http://www.complang.tuwien.ac.at/papers/ertl93.ps.Z, A
14216: Portable Forth Engine}}, EuroForth '93; M. Anton Ertl,
14217: @cite{@uref{http://www.complang.tuwien.ac.at/papers/ertl02.ps.gz,
14218: Threaded code variations and optimizations (extended version)}},
14219: Forth-Tagung '02.
14220: 
14221: @menu
14222: * Portability::                 
14223: * Threading::                   
14224: * Primitives::                  
14225: * Performance::                 
14226: @end menu
14227: 
14228: @node Portability, Threading, Engine, Engine
14229: @section Portability
14230: @cindex engine portability
14231: 
14232: An important goal of the Gforth Project is availability across a wide
14233: range of personal machines. fig-Forth, and, to a lesser extent, F83,
14234: achieved this goal by manually coding the engine in assembly language
14235: for several then-popular processors. This approach is very
14236: labor-intensive and the results are short-lived due to progress in
14237: computer architecture.
14238: 
14239: @cindex C, using C for the engine
14240: Others have avoided this problem by coding in C, e.g., Mitch Bradley
14241: (cforth), Mikael Patel (TILE) and Dirk Zoller (pfe). This approach is
14242: particularly popular for UNIX-based Forths due to the large variety of
14243: architectures of UNIX machines. Unfortunately an implementation in C
14244: does not mix well with the goals of efficiency and with using
14245: traditional techniques: Indirect or direct threading cannot be expressed
14246: in C, and switch threading, the fastest technique available in C, is
14247: significantly slower. Another problem with C is that it is very
14248: cumbersome to express double integer arithmetic.
14249: 
14250: @cindex GNU C for the engine
14251: @cindex long long
14252: Fortunately, there is a portable language that does not have these
14253: limitations: GNU C, the version of C processed by the GNU C compiler
14254: (@pxref{C Extensions, , Extensions to the C Language Family, gcc.info,
14255: GNU C Manual}). Its labels as values feature (@pxref{Labels as Values, ,
14256: Labels as Values, gcc.info, GNU C Manual}) makes direct and indirect
14257: threading possible, its @code{long long} type (@pxref{Long Long, ,
14258: Double-Word Integers, gcc.info, GNU C Manual}) corresponds to Forth's
14259: double numbers on many systems.  GNU C is freely available on all
14260: important (and many unimportant) UNIX machines, VMS, 80386s running
14261: MS-DOS, the Amiga, and the Atari ST, so a Forth written in GNU C can run
14262: on all these machines.
14263: 
14264: Writing in a portable language has the reputation of producing code that
14265: is slower than assembly. For our Forth engine we repeatedly looked at
14266: the code produced by the compiler and eliminated most compiler-induced
14267: inefficiencies by appropriate changes in the source code.
14268: 
14269: @cindex explicit register declarations
14270: @cindex --enable-force-reg, configuration flag
14271: @cindex -DFORCE_REG
14272: However, register allocation cannot be portably influenced by the
14273: programmer, leading to some inefficiencies on register-starved
14274: machines. We use explicit register declarations (@pxref{Explicit Reg
14275: Vars, , Variables in Specified Registers, gcc.info, GNU C Manual}) to
14276: improve the speed on some machines. They are turned on by using the
14277: configuration flag @code{--enable-force-reg} (@code{gcc} switch
14278: @code{-DFORCE_REG}). Unfortunately, this feature not only depends on the
14279: machine, but also on the compiler version: On some machines some
14280: compiler versions produce incorrect code when certain explicit register
14281: declarations are used. So by default @code{-DFORCE_REG} is not used.
14282: 
14283: @node Threading, Primitives, Portability, Engine
14284: @section Threading
14285: @cindex inner interpreter implementation
14286: @cindex threaded code implementation
14287: 
14288: @cindex labels as values
14289: GNU C's labels as values extension (available since @code{gcc-2.0},
14290: @pxref{Labels as Values, , Labels as Values, gcc.info, GNU C Manual})
14291: makes it possible to take the address of @i{label} by writing
14292: @code{&&@i{label}}.  This address can then be used in a statement like
14293: @code{goto *@i{address}}. I.e., @code{goto *&&x} is the same as
14294: @code{goto x}.
14295: 
14296: @cindex @code{NEXT}, indirect threaded
14297: @cindex indirect threaded inner interpreter
14298: @cindex inner interpreter, indirect threaded
14299: With this feature an indirect threaded @code{NEXT} looks like:
14300: @example
14301: cfa = *ip++;
14302: ca = *cfa;
14303: goto *ca;
14304: @end example
14305: @cindex instruction pointer
14306: For those unfamiliar with the names: @code{ip} is the Forth instruction
14307: pointer; the @code{cfa} (code-field address) corresponds to ANS Forths
14308: execution token and points to the code field of the next word to be
14309: executed; The @code{ca} (code address) fetched from there points to some
14310: executable code, e.g., a primitive or the colon definition handler
14311: @code{docol}.
14312: 
14313: @cindex @code{NEXT}, direct threaded
14314: @cindex direct threaded inner interpreter
14315: @cindex inner interpreter, direct threaded
14316: Direct threading is even simpler:
14317: @example
14318: ca = *ip++;
14319: goto *ca;
14320: @end example
14321: 
14322: Of course we have packaged the whole thing neatly in macros called
14323: @code{NEXT} and @code{NEXT1} (the part of @code{NEXT} after fetching the cfa).
14324: 
14325: @menu
14326: * Scheduling::                  
14327: * Direct or Indirect Threaded?::  
14328: * Dynamic Superinstructions::   
14329: * DOES>::                       
14330: @end menu
14331: 
14332: @node Scheduling, Direct or Indirect Threaded?, Threading, Threading
14333: @subsection Scheduling
14334: @cindex inner interpreter optimization
14335: 
14336: There is a little complication: Pipelined and superscalar processors,
14337: i.e., RISC and some modern CISC machines can process independent
14338: instructions while waiting for the results of an instruction. The
14339: compiler usually reorders (schedules) the instructions in a way that
14340: achieves good usage of these delay slots. However, on our first tries
14341: the compiler did not do well on scheduling primitives. E.g., for
14342: @code{+} implemented as
14343: @example
14344: n=sp[0]+sp[1];
14345: sp++;
14346: sp[0]=n;
14347: NEXT;
14348: @end example
14349: the @code{NEXT} comes strictly after the other code, i.e., there is
14350: nearly no scheduling. After a little thought the problem becomes clear:
14351: The compiler cannot know that @code{sp} and @code{ip} point to different
14352: addresses (and the version of @code{gcc} we used would not know it even
14353: if it was possible), so it could not move the load of the cfa above the
14354: store to the TOS. Indeed the pointers could be the same, if code on or
14355: very near the top of stack were executed. In the interest of speed we
14356: chose to forbid this probably unused ``feature'' and helped the compiler
14357: in scheduling: @code{NEXT} is divided into several parts:
14358: @code{NEXT_P0}, @code{NEXT_P1} and @code{NEXT_P2}). @code{+} now looks
14359: like:
14360: @example
14361: NEXT_P0;
14362: n=sp[0]+sp[1];
14363: sp++;
14364: NEXT_P1;
14365: sp[0]=n;
14366: NEXT_P2;
14367: @end example
14368: 
14369: There are various schemes that distribute the different operations of
14370: NEXT between these parts in several ways; in general, different schemes
14371: perform best on different processors.  We use a scheme for most
14372: architectures that performs well for most processors of this
14373: architecture; in the future we may switch to benchmarking and chosing
14374: the scheme on installation time.
14375: 
14376: 
14377: @node Direct or Indirect Threaded?, Dynamic Superinstructions, Scheduling, Threading
14378: @subsection Direct or Indirect Threaded?
14379: @cindex threading, direct or indirect?
14380: 
14381: Threaded forth code consists of references to primitives (simple machine
14382: code routines like @code{+}) and to non-primitives (e.g., colon
14383: definitions, variables, constants); for a specific class of
14384: non-primitives (e.g., variables) there is one code routine (e.g.,
14385: @code{dovar}), but each variable needs a separate reference to its data.
14386: 
14387: Traditionally Forth has been implemented as indirect threaded code,
14388: because this allows to use only one cell to reference a non-primitive
14389: (basically you point to the data, and find the code address there).
14390: 
14391: @cindex primitive-centric threaded code
14392: However, threaded code in Gforth (since 0.6.0) uses two cells for
14393: non-primitives, one for the code address, and one for the data address;
14394: the data pointer is an immediate argument for the virtual machine
14395: instruction represented by the code address.  We call this
14396: @emph{primitive-centric} threaded code, because all code addresses point
14397: to simple primitives.  E.g., for a variable, the code address is for
14398: @code{lit} (also used for integer literals like @code{99}).
14399: 
14400: Primitive-centric threaded code allows us to use (faster) direct
14401: threading as dispatch method, completely portably (direct threaded code
14402: in Gforth before 0.6.0 required architecture-specific code).  It also
14403: eliminates the performance problems related to I-cache consistency that
14404: 386 implementations have with direct threaded code, and allows
14405: additional optimizations.
14406: 
14407: @cindex hybrid direct/indirect threaded code
14408: There is a catch, however: the @var{xt} parameter of @code{execute} can
14409: occupy only one cell, so how do we pass non-primitives with their code
14410: @emph{and} data addresses to them?  Our answer is to use indirect
14411: threaded dispatch for @code{execute} and other words that use a
14412: single-cell xt.  So, normal threaded code in colon definitions uses
14413: direct threading, and @code{execute} and similar words, which dispatch
14414: to xts on the data stack, use indirect threaded code.  We call this
14415: @emph{hybrid direct/indirect} threaded code.
14416: 
14417: @cindex engines, gforth vs. gforth-fast vs. gforth-itc
14418: @cindex gforth engine
14419: @cindex gforth-fast engine
14420: The engines @command{gforth} and @command{gforth-fast} use hybrid
14421: direct/indirect threaded code.  This means that with these engines you
14422: cannot use @code{,} to compile an xt.  Instead, you have to use
14423: @code{compile,}.
14424: 
14425: @cindex gforth-itc engine
14426: If you want to compile xts with @code{,}, use @command{gforth-itc}.
14427: This engine uses plain old indirect threaded code.  It still compiles in
14428: a primitive-centric style, so you cannot use @code{compile,} instead of
14429: @code{,} (e.g., for producing tables of xts with @code{] word1 word2
14430: ... [}).  If you want to do that, you have to use @command{gforth-itc}
14431: and execute @code{' , is compile,}.  Your program can check if it is
14432: running on a hybrid direct/indirect threaded engine or a pure indirect
14433: threaded engine with @code{threading-method} (@pxref{Threading Words}).
14434: 
14435: 
14436: @node Dynamic Superinstructions, DOES>, Direct or Indirect Threaded?, Threading
14437: @subsection Dynamic Superinstructions
14438: @cindex Dynamic superinstructions with replication
14439: @cindex Superinstructions
14440: @cindex Replication
14441: 
14442: The engines @command{gforth} and @command{gforth-fast} use another
14443: optimization: Dynamic superinstructions with replication.  As an
14444: example, consider the following colon definition:
14445: 
14446: @example
14447: : squared ( n1 -- n2 )
14448:   dup * ;
14449: @end example
14450: 
14451: Gforth compiles this into the threaded code sequence
14452: 
14453: @example
14454: dup
14455: *
14456: ;s
14457: @end example
14458: 
14459: In normal direct threaded code there is a code address occupying one
14460: cell for each of these primitives.  Each code address points to a
14461: machine code routine, and the interpreter jumps to this machine code in
14462: order to execute the primitive.  The routines for these three
14463: primitives are (in @command{gforth-fast} on the 386):
14464: 
14465: @example
14466: Code dup  
14467: ( $804B950 )  add     esi , # -4  \ $83 $C6 $FC 
14468: ( $804B953 )  add     ebx , # 4  \ $83 $C3 $4 
14469: ( $804B956 )  mov     dword ptr 4 [esi] , ecx  \ $89 $4E $4 
14470: ( $804B959 )  jmp     dword ptr FC [ebx]  \ $FF $63 $FC 
14471: end-code
14472: Code *  
14473: ( $804ACC4 )  mov     eax , dword ptr 4 [esi]  \ $8B $46 $4 
14474: ( $804ACC7 )  add     esi , # 4  \ $83 $C6 $4 
14475: ( $804ACCA )  add     ebx , # 4  \ $83 $C3 $4 
14476: ( $804ACCD )  imul    ecx , eax  \ $F $AF $C8 
14477: ( $804ACD0 )  jmp     dword ptr FC [ebx]  \ $FF $63 $FC 
14478: end-code
14479: Code ;s  
14480: ( $804A693 )  mov     eax , dword ptr [edi]  \ $8B $7 
14481: ( $804A695 )  add     edi , # 4  \ $83 $C7 $4 
14482: ( $804A698 )  lea     ebx , dword ptr 4 [eax]  \ $8D $58 $4 
14483: ( $804A69B )  jmp     dword ptr FC [ebx]  \ $FF $63 $FC 
14484: end-code
14485: @end example
14486: 
14487: With dynamic superinstructions and replication the compiler does not
14488: just lay down the threaded code, but also copies the machine code