File:  [gforth] / gforth / doc / gforth.ds
Revision 1.199: download - view: text, annotated - select for diffs
Sat Aug 9 20:44:03 2008 UTC (13 years, 2 months ago) by anton
Branches: MAIN
CVS tags: v0-7-0, HEAD
fixed documentation bugs

    1: \input texinfo   @c -*-texinfo-*-
    2: @comment The source is gforth.ds, from which gforth.texi is generated
    3: 
    4: @comment TODO: nac29jan99 - a list of things to add in the next edit:
    5: @comment 1. x-ref all ambiguous or implementation-defined features?
    6: @comment 2. Describe the use of Auser Avariable AConstant A, etc.
    7: @comment 3. words in miscellaneous section need a home.
    8: @comment 4. search for TODO for other minor and major works required.
    9: @comment 5. [rats] change all @var to @i in Forth source so that info
   10: @comment    file looks decent.
   11: @c          Not an improvement IMO - anton
   12: @c          and anyway, this should be taken up
   13: @c          with Karl Berry (the texinfo guy) - anton
   14: @c
   15: @c Karl Berry writes:
   16: @c  If they don't like the all-caps for @var Info output, all I can say is
   17: @c  that it's always been that way, and the usage of all-caps for
   18: @c  metavariables has a long tradition.  I think it's best to just let it be
   19: @c  what it is, for the sake of consistency among manuals.
   20: @c
   21: @comment .. would be useful to have a word that identified all deferred words
   22: @comment should semantics stuff in intro be moved to another section
   23: 
   24: @c POSTPONE, COMPILE, [COMPILE], LITERAL should have their own section
   25: 
   26: @comment %**start of header (This is for running Texinfo on a region.)
   27: @setfilename gforth.info
   28: @include version.texi
   29: @settitle Gforth Manual
   30: @c @syncodeindex pg cp
   31: 
   32: @macro progstyle {}
   33: Programming style note:
   34: @end macro
   35: 
   36: @macro assignment {}
   37: @table @i
   38: @item Assignment:
   39: @end macro
   40: @macro endassignment {}
   41: @end table
   42: @end macro
   43: 
   44: @comment macros for beautifying glossary entries
   45: @macro GLOSS-START {}
   46: @iftex
   47: @ninerm
   48: @end iftex
   49: @end macro
   50: 
   51: @macro GLOSS-END {}
   52: @iftex
   53: @rm
   54: @end iftex
   55: @end macro
   56: 
   57: @comment %**end of header (This is for running Texinfo on a region.)
   58: @copying
   59: This manual is for Gforth (version @value{VERSION}, @value{UPDATED}),
   60: a fast and portable implementation of the ANS Forth language.  It
   61: serves as reference manual, but it also contains an introduction to
   62: Forth and a Forth tutorial.
   63: 
   64: Copyright @copyright{} 1995, 1996, 1997, 1998, 2000, 2003, 2004,2005,2006,2007,2008 Free Software Foundation, Inc.
   65: 
   66: @quotation
   67: Permission is granted to copy, distribute and/or modify this document
   68: under the terms of the GNU Free Documentation License, Version 1.1 or
   69: any later version published by the Free Software Foundation; with no
   70: Invariant Sections, with the Front-Cover texts being ``A GNU Manual,''
   71: and with the Back-Cover Texts as in (a) below.  A copy of the
   72: license is included in the section entitled ``GNU Free Documentation
   73: License.''
   74: 
   75: (a) The FSF's Back-Cover Text is: ``You have freedom to copy and modify
   76: this GNU Manual, like GNU software.  Copies published by the Free
   77: Software Foundation raise funds for GNU development.''
   78: @end quotation
   79: @end copying
   80: 
   81: @dircategory Software development
   82: @direntry
   83: * Gforth: (gforth).             A fast interpreter for the Forth language.
   84: @end direntry
   85: @c The Texinfo manual also recommends doing this, but for Gforth it may
   86: @c  not make much sense
   87: @c @dircategory Individual utilities
   88: @c @direntry
   89: @c * Gforth: (gforth)Invoking Gforth.      gforth, gforth-fast, gforthmi
   90: @c @end direntry
   91: 
   92: @titlepage
   93: @title Gforth
   94: @subtitle for version @value{VERSION}, @value{UPDATED}
   95: @author Neal Crook
   96: @author Anton Ertl
   97: @author David Kuehling
   98: @author Bernd Paysan
   99: @author Jens Wilke
  100: @page
  101: @vskip 0pt plus 1filll
  102: @insertcopying
  103: @end titlepage
  104: 
  105: @contents
  106: 
  107: @ifnottex
  108: @node Top, Goals, (dir), (dir)
  109: @top Gforth
  110: 
  111: @insertcopying
  112: @end ifnottex
  113: 
  114: @menu
  115: * Goals::                       About the Gforth Project
  116: * Gforth Environment::          Starting (and exiting) Gforth
  117: * Tutorial::                    Hands-on Forth Tutorial
  118: * Introduction::                An introduction to ANS Forth
  119: * Words::                       Forth words available in Gforth
  120: * Error messages::              How to interpret them
  121: * Tools::                       Programming tools
  122: * ANS conformance::             Implementation-defined options etc.
  123: * Standard vs Extensions::      Should I use extensions?
  124: * Model::                       The abstract machine of Gforth
  125: * Integrating Gforth::          Forth as scripting language for applications
  126: * Emacs and Gforth::            The Gforth Mode
  127: * Image Files::                 @code{.fi} files contain compiled code
  128: * Engine::                      The inner interpreter and the primitives
  129: * Cross Compiler::              The Cross Compiler
  130: * Bugs::                        How to report them
  131: * Origin::                      Authors and ancestors of Gforth
  132: * Forth-related information::   Books and places to look on the WWW
  133: * Licenses::                    
  134: * Word Index::                  An item for each Forth word
  135: * Concept Index::               A menu covering many topics
  136: 
  137: @detailmenu
  138:  --- The Detailed Node Listing ---
  139: 
  140: Gforth Environment
  141: 
  142: * Invoking Gforth::             Getting in
  143: * Leaving Gforth::              Getting out
  144: * Command-line editing::        
  145: * Environment variables::       that affect how Gforth starts up
  146: * Gforth Files::                What gets installed and where
  147: * Gforth in pipes::             
  148: * Startup speed::               When 35ms is not fast enough ...
  149: 
  150: Forth Tutorial
  151: 
  152: * Starting Gforth Tutorial::    
  153: * Syntax Tutorial::             
  154: * Crash Course Tutorial::       
  155: * Stack Tutorial::              
  156: * Arithmetics Tutorial::        
  157: * Stack Manipulation Tutorial::  
  158: * Using files for Forth code Tutorial::  
  159: * Comments Tutorial::           
  160: * Colon Definitions Tutorial::  
  161: * Decompilation Tutorial::      
  162: * Stack-Effect Comments Tutorial::  
  163: * Types Tutorial::              
  164: * Factoring Tutorial::          
  165: * Designing the stack effect Tutorial::  
  166: * Local Variables Tutorial::    
  167: * Conditional execution Tutorial::  
  168: * Flags and Comparisons Tutorial::  
  169: * General Loops Tutorial::      
  170: * Counted loops Tutorial::      
  171: * Recursion Tutorial::          
  172: * Leaving definitions or loops Tutorial::  
  173: * Return Stack Tutorial::       
  174: * Memory Tutorial::             
  175: * Characters and Strings Tutorial::  
  176: * Alignment Tutorial::          
  177: * Floating Point Tutorial::     
  178: * Files Tutorial::              
  179: * Interpretation and Compilation Semantics and Immediacy Tutorial::  
  180: * Execution Tokens Tutorial::   
  181: * Exceptions Tutorial::         
  182: * Defining Words Tutorial::     
  183: * Arrays and Records Tutorial::  
  184: * POSTPONE Tutorial::           
  185: * Literal Tutorial::            
  186: * Advanced macros Tutorial::    
  187: * Compilation Tokens Tutorial::  
  188: * Wordlists and Search Order Tutorial::  
  189: 
  190: An Introduction to ANS Forth
  191: 
  192: * Introducing the Text Interpreter::  
  193: * Stacks and Postfix notation::  
  194: * Your first definition::       
  195: * How does that work?::         
  196: * Forth is written in Forth::   
  197: * Review - elements of a Forth system::  
  198: * Where to go next::            
  199: * Exercises::                   
  200: 
  201: Forth Words
  202: 
  203: * Notation::                    
  204: * Case insensitivity::          
  205: * Comments::                    
  206: * Boolean Flags::               
  207: * Arithmetic::                  
  208: * Stack Manipulation::          
  209: * Memory::                      
  210: * Control Structures::          
  211: * Defining Words::              
  212: * Interpretation and Compilation Semantics::  
  213: * Tokens for Words::            
  214: * Compiling words::             
  215: * The Text Interpreter::        
  216: * The Input Stream::            
  217: * Word Lists::                  
  218: * Environmental Queries::       
  219: * Files::                       
  220: * Blocks::                      
  221: * Other I/O::                   
  222: * OS command line arguments::   
  223: * Locals::                      
  224: * Structures::                  
  225: * Object-oriented Forth::       
  226: * Programming Tools::           
  227: * C Interface::                 
  228: * Assembler and Code Words::    
  229: * Threading Words::             
  230: * Passing Commands to the OS::  
  231: * Keeping track of Time::       
  232: * Miscellaneous Words::         
  233: 
  234: Arithmetic
  235: 
  236: * Single precision::            
  237: * Double precision::            Double-cell integer arithmetic
  238: * Bitwise operations::          
  239: * Numeric comparison::          
  240: * Mixed precision::             Operations with single and double-cell integers
  241: * Floating Point::              
  242: 
  243: Stack Manipulation
  244: 
  245: * Data stack::                  
  246: * Floating point stack::        
  247: * Return stack::                
  248: * Locals stack::                
  249: * Stack pointer manipulation::  
  250: 
  251: Memory
  252: 
  253: * Memory model::                
  254: * Dictionary allocation::       
  255: * Heap Allocation::             
  256: * Memory Access::               
  257: * Address arithmetic::          
  258: * Memory Blocks::               
  259: 
  260: Control Structures
  261: 
  262: * Selection::                   IF ... ELSE ... ENDIF
  263: * Simple Loops::                BEGIN ...
  264: * Counted Loops::               DO
  265: * Arbitrary control structures::  
  266: * Calls and returns::           
  267: * Exception Handling::          
  268: 
  269: Defining Words
  270: 
  271: * CREATE::                      
  272: * Variables::                   Variables and user variables
  273: * Constants::                   
  274: * Values::                      Initialised variables
  275: * Colon Definitions::           
  276: * Anonymous Definitions::       Definitions without names
  277: * Supplying names::             Passing definition names as strings
  278: * User-defined Defining Words::  
  279: * Deferred Words::              Allow forward references
  280: * Aliases::                     
  281: 
  282: User-defined Defining Words
  283: 
  284: * CREATE..DOES> applications::  
  285: * CREATE..DOES> details::       
  286: * Advanced does> usage example::  
  287: * Const-does>::                 
  288: 
  289: Interpretation and Compilation Semantics
  290: 
  291: * Combined words::              
  292: 
  293: Tokens for Words
  294: 
  295: * Execution token::             represents execution/interpretation semantics
  296: * Compilation token::           represents compilation semantics
  297: * Name token::                  represents named words
  298: 
  299: Compiling words
  300: 
  301: * Literals::                    Compiling data values
  302: * Macros::                      Compiling words
  303: 
  304: The Text Interpreter
  305: 
  306: * Input Sources::               
  307: * Number Conversion::           
  308: * Interpret/Compile states::    
  309: * Interpreter Directives::      
  310: 
  311: Word Lists
  312: 
  313: * Vocabularies::                
  314: * Why use word lists?::         
  315: * Word list example::           
  316: 
  317: Files
  318: 
  319: * Forth source files::          
  320: * General files::               
  321: * Redirection::                 
  322: * Search Paths::                
  323: 
  324: Search Paths
  325: 
  326: * Source Search Paths::         
  327: * General Search Paths::        
  328: 
  329: Other I/O
  330: 
  331: * Simple numeric output::       Predefined formats
  332: * Formatted numeric output::    Formatted (pictured) output
  333: * String Formats::              How Forth stores strings in memory
  334: * Displaying characters and strings::  Other stuff
  335: * Terminal output::             Cursor positioning etc.
  336: * Single-key input::            
  337: * Line input and conversion::   
  338: * Pipes::                       How to create your own pipes
  339: * Xchars and Unicode::          Non-ASCII characters
  340: 
  341: Locals
  342: 
  343: * Gforth locals::               
  344: * ANS Forth locals::            
  345: 
  346: Gforth locals
  347: 
  348: * Where are locals visible by name?::  
  349: * How long do locals live?::    
  350: * Locals programming style::    
  351: * Locals implementation::       
  352: 
  353: Structures
  354: 
  355: * Why explicit structure support?::  
  356: * Structure Usage::             
  357: * Structure Naming Convention::  
  358: * Structure Implementation::    
  359: * Structure Glossary::          
  360: * Forth200x Structures::        
  361: 
  362: Object-oriented Forth
  363: 
  364: * Why object-oriented programming?::  
  365: * Object-Oriented Terminology::  
  366: * Objects::                     
  367: * OOF::                         
  368: * Mini-OOF::                    
  369: * Comparison with other object models::  
  370: 
  371: The @file{objects.fs} model
  372: 
  373: * Properties of the Objects model::  
  374: * Basic Objects Usage::         
  375: * The Objects base class::      
  376: * Creating objects::            
  377: * Object-Oriented Programming Style::  
  378: * Class Binding::               
  379: * Method conveniences::         
  380: * Classes and Scoping::         
  381: * Dividing classes::            
  382: * Object Interfaces::           
  383: * Objects Implementation::      
  384: * Objects Glossary::            
  385: 
  386: The @file{oof.fs} model
  387: 
  388: * Properties of the OOF model::  
  389: * Basic OOF Usage::             
  390: * The OOF base class::          
  391: * Class Declaration::           
  392: * Class Implementation::        
  393: 
  394: The @file{mini-oof.fs} model
  395: 
  396: * Basic Mini-OOF Usage::        
  397: * Mini-OOF Example::            
  398: * Mini-OOF Implementation::     
  399: 
  400: Programming Tools
  401: 
  402: * Examining::                   Data and Code.
  403: * Forgetting words::            Usually before reloading.
  404: * Debugging::                   Simple and quick.
  405: * Assertions::                  Making your programs self-checking.
  406: * Singlestep Debugger::         Executing your program word by word.
  407: 
  408: C Interface
  409: 
  410: * Calling C Functions::         
  411: * Declaring C Functions::       
  412: * Calling C function pointers::  
  413: * Defining library interfaces::  
  414: * Declaring OS-level libraries::  
  415: * Callbacks::                   
  416: * C interface internals::       
  417: * Low-Level C Interface Words::  
  418: 
  419: Assembler and Code Words
  420: 
  421: * Code and ;code::              
  422: * Common Assembler::            Assembler Syntax
  423: * Common Disassembler::         
  424: * 386 Assembler::               Deviations and special cases
  425: * Alpha Assembler::             Deviations and special cases
  426: * MIPS assembler::              Deviations and special cases
  427: * PowerPC assembler::           Deviations and special cases
  428: * ARM Assembler::               Deviations and special cases
  429: * Other assemblers::            How to write them
  430: 
  431: Tools
  432: 
  433: * ANS Report::                  Report the words used, sorted by wordset.
  434: * Stack depth changes::         Where does this stack item come from?
  435: 
  436: ANS conformance
  437: 
  438: * The Core Words::              
  439: * The optional Block word set::  
  440: * The optional Double Number word set::  
  441: * The optional Exception word set::  
  442: * The optional Facility word set::  
  443: * The optional File-Access word set::  
  444: * The optional Floating-Point word set::  
  445: * The optional Locals word set::  
  446: * The optional Memory-Allocation word set::  
  447: * The optional Programming-Tools word set::  
  448: * The optional Search-Order word set::  
  449: 
  450: The Core Words
  451: 
  452: * core-idef::                   Implementation Defined Options                   
  453: * core-ambcond::                Ambiguous Conditions                
  454: * core-other::                  Other System Documentation                  
  455: 
  456: The optional Block word set
  457: 
  458: * block-idef::                  Implementation Defined Options
  459: * block-ambcond::               Ambiguous Conditions               
  460: * block-other::                 Other System Documentation                 
  461: 
  462: The optional Double Number word set
  463: 
  464: * double-ambcond::              Ambiguous Conditions              
  465: 
  466: The optional Exception word set
  467: 
  468: * exception-idef::              Implementation Defined Options              
  469: 
  470: The optional Facility word set
  471: 
  472: * facility-idef::               Implementation Defined Options               
  473: * facility-ambcond::            Ambiguous Conditions            
  474: 
  475: The optional File-Access word set
  476: 
  477: * file-idef::                   Implementation Defined Options
  478: * file-ambcond::                Ambiguous Conditions                
  479: 
  480: The optional Floating-Point word set
  481: 
  482: * floating-idef::               Implementation Defined Options
  483: * floating-ambcond::            Ambiguous Conditions            
  484: 
  485: The optional Locals word set
  486: 
  487: * locals-idef::                 Implementation Defined Options                 
  488: * locals-ambcond::              Ambiguous Conditions              
  489: 
  490: The optional Memory-Allocation word set
  491: 
  492: * memory-idef::                 Implementation Defined Options                 
  493: 
  494: The optional Programming-Tools word set
  495: 
  496: * programming-idef::            Implementation Defined Options            
  497: * programming-ambcond::         Ambiguous Conditions         
  498: 
  499: The optional Search-Order word set
  500: 
  501: * search-idef::                 Implementation Defined Options                 
  502: * search-ambcond::              Ambiguous Conditions              
  503: 
  504: Emacs and Gforth
  505: 
  506: * Installing gforth.el::        Making Emacs aware of Forth.
  507: * Emacs Tags::                  Viewing the source of a word in Emacs.
  508: * Hilighting::                  Making Forth code look prettier.
  509: * Auto-Indentation::            Customizing auto-indentation.
  510: * Blocks Files::                Reading and writing blocks files.
  511: 
  512: Image Files
  513: 
  514: * Image Licensing Issues::      Distribution terms for images.
  515: * Image File Background::       Why have image files?
  516: * Non-Relocatable Image Files::  don't always work.
  517: * Data-Relocatable Image Files::  are better.
  518: * Fully Relocatable Image Files::  better yet.
  519: * Stack and Dictionary Sizes::  Setting the default sizes for an image.
  520: * Running Image Files::         @code{gforth -i @i{file}} or @i{file}.
  521: * Modifying the Startup Sequence::  and turnkey applications.
  522: 
  523: Fully Relocatable Image Files
  524: 
  525: * gforthmi::                    The normal way
  526: * cross.fs::                    The hard way
  527: 
  528: Engine
  529: 
  530: * Portability::                 
  531: * Threading::                   
  532: * Primitives::                  
  533: * Performance::                 
  534: 
  535: Threading
  536: 
  537: * Scheduling::                  
  538: * Direct or Indirect Threaded?::  
  539: * Dynamic Superinstructions::   
  540: * DOES>::                       
  541: 
  542: Primitives
  543: 
  544: * Automatic Generation::        
  545: * TOS Optimization::            
  546: * Produced code::               
  547: 
  548: Cross Compiler
  549: 
  550: * Using the Cross Compiler::    
  551: * How the Cross Compiler Works::  
  552: 
  553: Licenses
  554: 
  555: * GNU Free Documentation License::  License for copying this manual.
  556: * Copying::                     GPL (for copying this software).
  557: 
  558: @end detailmenu
  559: @end menu
  560: 
  561: @c ----------------------------------------------------------
  562: @iftex
  563: @unnumbered Preface
  564: @cindex Preface
  565: This manual documents Gforth. Some introductory material is provided for
  566: readers who are unfamiliar with Forth or who are migrating to Gforth
  567: from other Forth compilers. However, this manual is primarily a
  568: reference manual.
  569: @end iftex
  570: 
  571: @comment TODO much more blurb here.
  572: 
  573: @c ******************************************************************
  574: @node Goals, Gforth Environment, Top, Top
  575: @comment node-name,     next,           previous, up
  576: @chapter Goals of Gforth
  577: @cindex goals of the Gforth project
  578: The goal of the Gforth Project is to develop a standard model for
  579: ANS Forth. This can be split into several subgoals:
  580: 
  581: @itemize @bullet
  582: @item
  583: Gforth should conform to the ANS Forth Standard.
  584: @item
  585: It should be a model, i.e. it should define all the
  586: implementation-dependent things.
  587: @item
  588: It should become standard, i.e. widely accepted and used. This goal
  589: is the most difficult one.
  590: @end itemize
  591: 
  592: To achieve these goals Gforth should be
  593: @itemize @bullet
  594: @item
  595: Similar to previous models (fig-Forth, F83)
  596: @item
  597: Powerful. It should provide for all the things that are considered
  598: necessary today and even some that are not yet considered necessary.
  599: @item
  600: Efficient. It should not get the reputation of being exceptionally
  601: slow.
  602: @item
  603: Free.
  604: @item
  605: Available on many machines/easy to port.
  606: @end itemize
  607: 
  608: Have we achieved these goals? Gforth conforms to the ANS Forth
  609: standard. It may be considered a model, but we have not yet documented
  610: which parts of the model are stable and which parts we are likely to
  611: change. It certainly has not yet become a de facto standard, but it
  612: appears to be quite popular. It has some similarities to and some
  613: differences from previous models. It has some powerful features, but not
  614: yet everything that we envisioned. We certainly have achieved our
  615: execution speed goals (@pxref{Performance})@footnote{However, in 1998
  616: the bar was raised when the major commercial Forth vendors switched to
  617: native code compilers.}.  It is free and available on many machines.
  618: 
  619: @c ******************************************************************
  620: @node Gforth Environment, Tutorial, Goals, Top
  621: @chapter Gforth Environment
  622: @cindex Gforth environment
  623: 
  624: Note: ultimately, the Gforth man page will be auto-generated from the
  625: material in this chapter.
  626: 
  627: @menu
  628: * Invoking Gforth::             Getting in
  629: * Leaving Gforth::              Getting out
  630: * Command-line editing::        
  631: * Environment variables::       that affect how Gforth starts up
  632: * Gforth Files::                What gets installed and where
  633: * Gforth in pipes::             
  634: * Startup speed::               When 35ms is not fast enough ...
  635: @end menu
  636: 
  637: For related information about the creation of images see @ref{Image Files}.
  638: 
  639: @comment ----------------------------------------------
  640: @node Invoking Gforth, Leaving Gforth, Gforth Environment, Gforth Environment
  641: @section Invoking Gforth
  642: @cindex invoking Gforth
  643: @cindex running Gforth
  644: @cindex command-line options
  645: @cindex options on the command line
  646: @cindex flags on the command line
  647: 
  648: Gforth is made up of two parts; an executable ``engine'' (named
  649: @command{gforth} or @command{gforth-fast}) and an image file. To start it, you
  650: will usually just say @code{gforth} -- this automatically loads the
  651: default image file @file{gforth.fi}. In many other cases the default
  652: Gforth image will be invoked like this:
  653: @example
  654: gforth [file | -e forth-code] ...
  655: @end example
  656: @noindent
  657: This interprets the contents of the files and the Forth code in the order they
  658: are given.
  659: 
  660: In addition to the @command{gforth} engine, there is also an engine
  661: called @command{gforth-fast}, which is faster, but gives less
  662: informative error messages (@pxref{Error messages}) and may catch some
  663: errors (in particular, stack underflows and integer division errors)
  664: later or not at all.  You should use it for debugged,
  665: performance-critical programs.
  666: 
  667: Moreover, there is an engine called @command{gforth-itc}, which is
  668: useful in some backwards-compatibility situations (@pxref{Direct or
  669: Indirect Threaded?}).
  670: 
  671: In general, the command line looks like this:
  672: 
  673: @example
  674: gforth[-fast] [engine options] [image options]
  675: @end example
  676: 
  677: The engine options must come before the rest of the command
  678: line. They are:
  679: 
  680: @table @code
  681: @cindex -i, command-line option
  682: @cindex --image-file, command-line option
  683: @item --image-file @i{file}
  684: @itemx -i @i{file}
  685: Loads the Forth image @i{file} instead of the default
  686: @file{gforth.fi} (@pxref{Image Files}).
  687: 
  688: @cindex --appl-image, command-line option
  689: @item --appl-image @i{file}
  690: Loads the image @i{file} and leaves all further command-line arguments
  691: to the image (instead of processing them as engine options).  This is
  692: useful for building executable application images on Unix, built with
  693: @code{gforthmi --application ...}.
  694: 
  695: @cindex --path, command-line option
  696: @cindex -p, command-line option
  697: @item --path @i{path}
  698: @itemx -p @i{path}
  699: Uses @i{path} for searching the image file and Forth source code files
  700: instead of the default in the environment variable @code{GFORTHPATH} or
  701: the path specified at installation time (e.g.,
  702: @file{/usr/local/share/gforth/0.2.0:.}). A path is given as a list of
  703: directories, separated by @samp{:} (on Unix) or @samp{;} (on other OSs).
  704: 
  705: @cindex --dictionary-size, command-line option
  706: @cindex -m, command-line option
  707: @cindex @i{size} parameters for command-line options
  708: @cindex size of the dictionary and the stacks
  709: @item --dictionary-size @i{size}
  710: @itemx -m @i{size}
  711: Allocate @i{size} space for the Forth dictionary space instead of
  712: using the default specified in the image (typically 256K). The
  713: @i{size} specification for this and subsequent options consists of
  714: an integer and a unit (e.g.,
  715: @code{4M}). The unit can be one of @code{b} (bytes), @code{e} (element
  716: size, in this case Cells), @code{k} (kilobytes), @code{M} (Megabytes),
  717: @code{G} (Gigabytes), and @code{T} (Terabytes). If no unit is specified,
  718: @code{e} is used.
  719: 
  720: @cindex --data-stack-size, command-line option
  721: @cindex -d, command-line option
  722: @item --data-stack-size @i{size}
  723: @itemx -d @i{size}
  724: Allocate @i{size} space for the data stack instead of using the
  725: default specified in the image (typically 16K).
  726: 
  727: @cindex --return-stack-size, command-line option
  728: @cindex -r, command-line option
  729: @item --return-stack-size @i{size}
  730: @itemx -r @i{size}
  731: Allocate @i{size} space for the return stack instead of using the
  732: default specified in the image (typically 15K).
  733: 
  734: @cindex --fp-stack-size, command-line option
  735: @cindex -f, command-line option
  736: @item --fp-stack-size @i{size}
  737: @itemx -f @i{size}
  738: Allocate @i{size} space for the floating point stack instead of
  739: using the default specified in the image (typically 15.5K). In this case
  740: the unit specifier @code{e} refers to floating point numbers.
  741: 
  742: @cindex --locals-stack-size, command-line option
  743: @cindex -l, command-line option
  744: @item --locals-stack-size @i{size}
  745: @itemx -l @i{size}
  746: Allocate @i{size} space for the locals stack instead of using the
  747: default specified in the image (typically 14.5K).
  748: 
  749: @cindex --vm-commit, command-line option
  750: @cindex overcommit memory for dictionary and stacks
  751: @cindex memory overcommit for dictionary and stacks
  752: @item --vm-commit
  753: Normally, Gforth tries to start up even if there is not enough virtual
  754: memory for the dictionary and the stacks (using @code{MAP_NORESERVE}
  755: on OSs that support it); so you can ask for a really big dictionary
  756: and/or stacks, and as long as you don't use more virtual memory than
  757: is available, everything will be fine (but if you use more, processes
  758: get killed).  With this option you just use the default allocation
  759: policy of the OS; for OSs that don't overcommit (e.g., Solaris), this
  760: means that you cannot and should not ask for as big dictionary and
  761: stacks, but once Gforth successfully starts up, out-of-memory won't
  762: kill it.
  763: 
  764: @cindex -h, command-line option
  765: @cindex --help, command-line option
  766: @item --help
  767: @itemx -h
  768: Print a message about the command-line options
  769: 
  770: @cindex -v, command-line option
  771: @cindex --version, command-line option
  772: @item --version
  773: @itemx -v
  774: Print version and exit
  775: 
  776: @cindex --debug, command-line option
  777: @item --debug
  778: Print some information useful for debugging on startup.
  779: 
  780: @cindex --offset-image, command-line option
  781: @item --offset-image
  782: Start the dictionary at a slightly different position than would be used
  783: otherwise (useful for creating data-relocatable images,
  784: @pxref{Data-Relocatable Image Files}).
  785: 
  786: @cindex --no-offset-im, command-line option
  787: @item --no-offset-im
  788: Start the dictionary at the normal position.
  789: 
  790: @cindex --clear-dictionary, command-line option
  791: @item --clear-dictionary
  792: Initialize all bytes in the dictionary to 0 before loading the image
  793: (@pxref{Data-Relocatable Image Files}).
  794: 
  795: @cindex --die-on-signal, command-line-option
  796: @item --die-on-signal
  797: Normally Gforth handles most signals (e.g., the user interrupt SIGINT,
  798: or the segmentation violation SIGSEGV) by translating it into a Forth
  799: @code{THROW}. With this option, Gforth exits if it receives such a
  800: signal. This option is useful when the engine and/or the image might be
  801: severely broken (such that it causes another signal before recovering
  802: from the first); this option avoids endless loops in such cases.
  803: 
  804: @cindex --no-dynamic, command-line option
  805: @cindex --dynamic, command-line option
  806: @item --no-dynamic
  807: @item --dynamic
  808: Disable or enable dynamic superinstructions with replication
  809: (@pxref{Dynamic Superinstructions}).
  810: 
  811: @cindex --no-super, command-line option
  812: @item --no-super
  813: Disable dynamic superinstructions, use just dynamic replication; this is
  814: useful if you want to patch threaded code (@pxref{Dynamic
  815: Superinstructions}).
  816: 
  817: @cindex --ss-number, command-line option
  818: @item --ss-number=@var{N}
  819: Use only the first @var{N} static superinstructions compiled into the
  820: engine (default: use them all; note that only @code{gforth-fast} has
  821: any).  This option is useful for measuring the performance impact of
  822: static superinstructions.
  823: 
  824: @cindex --ss-min-..., command-line options
  825: @item --ss-min-codesize
  826: @item --ss-min-ls
  827: @item --ss-min-lsu
  828: @item --ss-min-nexts
  829: Use specified metric for determining the cost of a primitive or static
  830: superinstruction for static superinstruction selection.  @code{Codesize}
  831: is the native code size of the primive or static superinstruction,
  832: @code{ls} is the number of loads and stores, @code{lsu} is the number of
  833: loads, stores, and updates, and @code{nexts} is the number of dispatches
  834: (not taking dynamic superinstructions into account), i.e. every
  835: primitive or static superinstruction has cost 1. Default:
  836: @code{codesize} if you use dynamic code generation, otherwise
  837: @code{nexts}.
  838: 
  839: @cindex --ss-greedy, command-line option
  840: @item --ss-greedy
  841: This option is useful for measuring the performance impact of static
  842: superinstructions.  By default, an optimal shortest-path algorithm is
  843: used for selecting static superinstructions.  With @option{--ss-greedy}
  844: this algorithm is modified to assume that anything after the static
  845: superinstruction currently under consideration is not combined into
  846: static superinstructions.  With @option{--ss-min-nexts} this produces
  847: the same result as a greedy algorithm that always selects the longest
  848: superinstruction available at the moment.  E.g., if there are
  849: superinstructions AB and BCD, then for the sequence A B C D the optimal
  850: algorithm will select A BCD and the greedy algorithm will select AB C D.
  851: 
  852: @cindex --print-metrics, command-line option
  853: @item --print-metrics
  854: Prints some metrics used during static superinstruction selection:
  855: @code{code size} is the actual size of the dynamically generated code.
  856: @code{Metric codesize} is the sum of the codesize metrics as seen by
  857: static superinstruction selection; there is a difference from @code{code
  858: size}, because not all primitives and static superinstructions are
  859: compiled into dynamically generated code, and because of markers.  The
  860: other metrics correspond to the @option{ss-min-...} options.  This
  861: option is useful for evaluating the effects of the @option{--ss-...}
  862: options.
  863: 
  864: @end table
  865: 
  866: @cindex loading files at startup
  867: @cindex executing code on startup
  868: @cindex batch processing with Gforth
  869: As explained above, the image-specific command-line arguments for the
  870: default image @file{gforth.fi} consist of a sequence of filenames and
  871: @code{-e @var{forth-code}} options that are interpreted in the sequence
  872: in which they are given. The @code{-e @var{forth-code}} or
  873: @code{--evaluate @var{forth-code}} option evaluates the Forth code. This
  874: option takes only one argument; if you want to evaluate more Forth
  875: words, you have to quote them or use @code{-e} several times. To exit
  876: after processing the command line (instead of entering interactive mode)
  877: append @code{-e bye} to the command line.  You can also process the
  878: command-line arguments with a Forth program (@pxref{OS command line
  879: arguments}).
  880: 
  881: @cindex versions, invoking other versions of Gforth
  882: If you have several versions of Gforth installed, @code{gforth} will
  883: invoke the version that was installed last. @code{gforth-@i{version}}
  884: invokes a specific version. If your environment contains the variable
  885: @code{GFORTHPATH}, you may want to override it by using the
  886: @code{--path} option.
  887: 
  888: Not yet implemented:
  889: On startup the system first executes the system initialization file
  890: (unless the option @code{--no-init-file} is given; note that the system
  891: resulting from using this option may not be ANS Forth conformant). Then
  892: the user initialization file @file{.gforth.fs} is executed, unless the
  893: option @code{--no-rc} is given; this file is searched for in @file{.},
  894: then in @file{~}, then in the normal path (see above).
  895: 
  896: 
  897: 
  898: @comment ----------------------------------------------
  899: @node Leaving Gforth, Command-line editing, Invoking Gforth, Gforth Environment
  900: @section Leaving Gforth
  901: @cindex Gforth - leaving
  902: @cindex leaving Gforth
  903: 
  904: You can leave Gforth by typing @code{bye} or @kbd{Ctrl-d} (at the start
  905: of a line) or (if you invoked Gforth with the @code{--die-on-signal}
  906: option) @kbd{Ctrl-c}. When you leave Gforth, all of your definitions and
  907: data are discarded.  For ways of saving the state of the system before
  908: leaving Gforth see @ref{Image Files}.
  909: 
  910: doc-bye
  911: 
  912: 
  913: @comment ----------------------------------------------
  914: @node Command-line editing, Environment variables, Leaving Gforth, Gforth Environment
  915: @section Command-line editing
  916: @cindex command-line editing
  917: 
  918: Gforth maintains a history file that records every line that you type to
  919: the text interpreter. This file is preserved between sessions, and is
  920: used to provide a command-line recall facility; if you type @kbd{Ctrl-P}
  921: repeatedly you can recall successively older commands from this (or
  922: previous) session(s). The full list of command-line editing facilities is:
  923: 
  924: @itemize @bullet
  925: @item
  926: @kbd{Ctrl-p} (``previous'') (or up-arrow) to recall successively older
  927: commands from the history buffer.
  928: @item
  929: @kbd{Ctrl-n} (``next'') (or down-arrow) to recall successively newer commands
  930: from the history buffer.
  931: @item
  932: @kbd{Ctrl-f} (or right-arrow) to move the cursor right, non-destructively.
  933: @item
  934: @kbd{Ctrl-b} (or left-arrow) to move the cursor left, non-destructively.
  935: @item
  936: @kbd{Ctrl-h} (backspace) to delete the character to the left of the cursor,
  937: closing up the line.
  938: @item
  939: @kbd{Ctrl-k} to delete (``kill'') from the cursor to the end of the line.
  940: @item
  941: @kbd{Ctrl-a} to move the cursor to the start of the line.
  942: @item
  943: @kbd{Ctrl-e} to move the cursor to the end of the line.
  944: @item
  945: @key{RET} (@kbd{Ctrl-m}) or @key{LFD} (@kbd{Ctrl-j}) to submit the current
  946: line.
  947: @item
  948: @key{TAB} to step through all possible full-word completions of the word
  949: currently being typed.
  950: @item
  951: @kbd{Ctrl-d} on an empty line line to terminate Gforth (gracefully,
  952: using @code{bye}). 
  953: @item
  954: @kbd{Ctrl-x} (or @code{Ctrl-d} on a non-empty line) to delete the
  955: character under the cursor.
  956: @end itemize
  957: 
  958: When editing, displayable characters are inserted to the left of the
  959: cursor position; the line is always in ``insert'' (as opposed to
  960: ``overstrike'') mode.
  961: 
  962: @cindex history file
  963: @cindex @file{.gforth-history}
  964: On Unix systems, the history file is @file{~/.gforth-history} by
  965: default@footnote{i.e. it is stored in the user's home directory.}. You
  966: can find out the name and location of your history file using:
  967: 
  968: @example 
  969: history-file type \ Unix-class systems
  970: 
  971: history-file type \ Other systems
  972: history-dir  type
  973: @end example
  974: 
  975: If you enter long definitions by hand, you can use a text editor to
  976: paste them out of the history file into a Forth source file for reuse at
  977: a later time.
  978: 
  979: Gforth never trims the size of the history file, so you should do this
  980: periodically, if necessary.
  981: 
  982: @comment this is all defined in history.fs
  983: @comment NAC TODO the ctrl-D behaviour can either do a bye or a beep.. how is that option
  984: @comment chosen?
  985: 
  986: 
  987: @comment ----------------------------------------------
  988: @node Environment variables, Gforth Files, Command-line editing, Gforth Environment
  989: @section Environment variables
  990: @cindex environment variables
  991: 
  992: Gforth uses these environment variables:
  993: 
  994: @itemize @bullet
  995: @item
  996: @cindex @code{GFORTHHIST} -- environment variable
  997: @code{GFORTHHIST} -- (Unix systems only) specifies the directory in which to
  998: open/create the history file, @file{.gforth-history}. Default:
  999: @code{$HOME}.
 1000: 
 1001: @item
 1002: @cindex @code{GFORTHPATH} -- environment variable
 1003: @code{GFORTHPATH} -- specifies the path used when searching for the gforth image file and
 1004: for Forth source-code files.
 1005: 
 1006: @item
 1007: @cindex @code{LANG} -- environment variable
 1008: @code{LANG} -- see @code{LC_CTYPE}
 1009: 
 1010: @item
 1011: @cindex @code{LC_ALL} -- environment variable
 1012: @code{LC_ALL} -- see @code{LC_CTYPE}
 1013: 
 1014: @item
 1015: @cindex @code{LC_CTYPE} -- environment variable
 1016: @code{LC_CTYPE} -- If this variable contains ``UTF-8'' on Gforth
 1017: startup, Gforth uses the UTF-8 encoding for strings internally and
 1018: expects its input and produces its output in UTF-8 encoding, otherwise
 1019: the encoding is 8bit (see @pxref{Xchars and Unicode}).  If this
 1020: environment variable is unset, Gforth looks in @code{LC_ALL}, and if
 1021: that is unset, in @code{LANG}.
 1022: 
 1023: @item
 1024: @cindex @code{GFORTHSYSTEMPREFIX} -- environment variable
 1025: 
 1026: @code{GFORTHSYSTEMPREFIX} -- specifies what to prepend to the argument
 1027: of @code{system} before passing it to C's @code{system()}.  Default:
 1028: @code{"./$COMSPEC /c "} on Windows, @code{""} on other OSs.  The prefix
 1029: and the command are directly concatenated, so if a space between them is
 1030: necessary, append it to the prefix.
 1031: 
 1032: @item
 1033: @cindex @code{GFORTH} -- environment variable
 1034: @code{GFORTH} -- used by @file{gforthmi}, @xref{gforthmi}.
 1035: 
 1036: @item
 1037: @cindex @code{GFORTHD} -- environment variable
 1038: @code{GFORTHD} -- used by @file{gforthmi}, @xref{gforthmi}.
 1039: 
 1040: @item
 1041: @cindex @code{TMP}, @code{TEMP} - environment variable
 1042: @code{TMP}, @code{TEMP} - (non-Unix systems only) used as a potential
 1043: location for the history file.
 1044: @end itemize
 1045: 
 1046: @comment also POSIXELY_CORRECT LINES COLUMNS HOME but no interest in
 1047: @comment mentioning these.
 1048: 
 1049: All the Gforth environment variables default to sensible values if they
 1050: are not set.
 1051: 
 1052: 
 1053: @comment ----------------------------------------------
 1054: @node Gforth Files, Gforth in pipes, Environment variables, Gforth Environment
 1055: @section Gforth files
 1056: @cindex Gforth files
 1057: 
 1058: When you install Gforth on a Unix system, it installs files in these
 1059: locations by default:
 1060: 
 1061: @itemize @bullet
 1062: @item
 1063: @file{/usr/local/bin/gforth}
 1064: @item
 1065: @file{/usr/local/bin/gforthmi}
 1066: @item
 1067: @file{/usr/local/man/man1/gforth.1} - man page.
 1068: @item
 1069: @file{/usr/local/info} - the Info version of this manual.
 1070: @item
 1071: @file{/usr/local/lib/gforth/<version>/...} - Gforth @file{.fi} files.
 1072: @item
 1073: @file{/usr/local/share/gforth/<version>/TAGS} - Emacs TAGS file.
 1074: @item
 1075: @file{/usr/local/share/gforth/<version>/...} - Gforth source files.
 1076: @item
 1077: @file{.../emacs/site-lisp/gforth.el} - Emacs gforth mode.
 1078: @end itemize
 1079: 
 1080: You can select different places for installation by using
 1081: @code{configure} options (listed with @code{configure --help}).
 1082: 
 1083: @comment ----------------------------------------------
 1084: @node Gforth in pipes, Startup speed, Gforth Files, Gforth Environment
 1085: @section Gforth in pipes
 1086: @cindex pipes, Gforth as part of
 1087: 
 1088: Gforth can be used in pipes created elsewhere (described here).  It can
 1089: also create pipes on its own (@pxref{Pipes}).
 1090: 
 1091: @cindex input from pipes
 1092: If you pipe into Gforth, your program should read with @code{read-file}
 1093: or @code{read-line} from @code{stdin} (@pxref{General files}).
 1094: @code{Key} does not recognize the end of input.  Words like
 1095: @code{accept} echo the input and are therefore usually not useful for
 1096: reading from a pipe.  You have to invoke the Forth program with an OS
 1097: command-line option, as you have no chance to use the Forth command line
 1098: (the text interpreter would try to interpret the pipe input).
 1099: 
 1100: @cindex output in pipes
 1101: You can output to a pipe with @code{type}, @code{emit}, @code{cr} etc.
 1102: 
 1103: @cindex silent exiting from Gforth
 1104: When you write to a pipe that has been closed at the other end, Gforth
 1105: receives a SIGPIPE signal (``pipe broken'').  Gforth translates this
 1106: into the exception @code{broken-pipe-error}.  If your application does
 1107: not catch that exception, the system catches it and exits, usually
 1108: silently (unless you were working on the Forth command line; then it
 1109: prints an error message and exits).  This is usually the desired
 1110: behaviour.
 1111: 
 1112: If you do not like this behaviour, you have to catch the exception
 1113: yourself, and react to it.
 1114: 
 1115: Here's an example of an invocation of Gforth that is usable in a pipe:
 1116: 
 1117: @example
 1118: gforth -e ": foo begin pad dup 10 stdin read-file throw dup while \
 1119:  type repeat ; foo bye"
 1120: @end example
 1121: 
 1122: This example just copies the input verbatim to the output.  A very
 1123: simple pipe containing this example looks like this:
 1124: 
 1125: @example
 1126: cat startup.fs |
 1127: gforth -e ": foo begin pad dup 80 stdin read-file throw dup while \
 1128:  type repeat ; foo bye"|
 1129: head
 1130: @end example
 1131: 
 1132: @cindex stderr and pipes
 1133: Pipes involving Gforth's @code{stderr} output do not work.
 1134: 
 1135: @comment ----------------------------------------------
 1136: @node Startup speed,  , Gforth in pipes, Gforth Environment
 1137: @section Startup speed
 1138: @cindex Startup speed
 1139: @cindex speed, startup
 1140: 
 1141: If Gforth is used for CGI scripts or in shell scripts, its startup
 1142: speed may become a problem.  On a 300MHz 21064a under Linux-2.2.13 with
 1143: glibc-2.0.7, @code{gforth -e bye} takes about 24.6ms user and 11.3ms
 1144: system time.
 1145: 
 1146: If startup speed is a problem, you may consider the following ways to
 1147: improve it; or you may consider ways to reduce the number of startups
 1148: (for example, by using Fast-CGI).
 1149: 
 1150: An easy step that influences Gforth startup speed is the use of the
 1151: @option{--no-dynamic} option; this decreases image loading speed, but
 1152: increases compile-time and run-time.
 1153: 
 1154: Another step to improve startup speed is to statically link Gforth, by
 1155: building it with @code{XLDFLAGS=-static}.  This requires more memory for
 1156: the code and will therefore slow down the first invocation, but
 1157: subsequent invocations avoid the dynamic linking overhead.  Another
 1158: disadvantage is that Gforth won't profit from library upgrades.  As a
 1159: result, @code{gforth-static -e bye} takes about 17.1ms user and
 1160: 8.2ms system time.
 1161: 
 1162: The next step to improve startup speed is to use a non-relocatable image
 1163: (@pxref{Non-Relocatable Image Files}).  You can create this image with
 1164: @code{gforth -e "savesystem gforthnr.fi bye"} and later use it with
 1165: @code{gforth -i gforthnr.fi ...}.  This avoids the relocation overhead
 1166: and a part of the copy-on-write overhead.  The disadvantage is that the
 1167: non-relocatable image does not work if the OS gives Gforth a different
 1168: address for the dictionary, for whatever reason; so you better provide a
 1169: fallback on a relocatable image.  @code{gforth-static -i gforthnr.fi -e
 1170: bye} takes about 15.3ms user and 7.5ms system time.
 1171: 
 1172: The final step is to disable dictionary hashing in Gforth.  Gforth
 1173: builds the hash table on startup, which takes much of the startup
 1174: overhead. You can do this by commenting out the @code{include hash.fs}
 1175: in @file{startup.fs} and everything that requires @file{hash.fs} (at the
 1176: moment @file{table.fs} and @file{ekey.fs}) and then doing @code{make}.
 1177: The disadvantages are that functionality like @code{table} and
 1178: @code{ekey} is missing and that text interpretation (e.g., compiling)
 1179: now takes much longer. So, you should only use this method if there is
 1180: no significant text interpretation to perform (the script should be
 1181: compiled into the image, amongst other things).  @code{gforth-static -i
 1182: gforthnrnh.fi -e bye} takes about 2.1ms user and 6.1ms system time.
 1183: 
 1184: @c ******************************************************************
 1185: @node Tutorial, Introduction, Gforth Environment, Top
 1186: @chapter Forth Tutorial
 1187: @cindex Tutorial
 1188: @cindex Forth Tutorial
 1189: 
 1190: @c Topics from nac's Introduction that could be mentioned:
 1191: @c press <ret> after each line
 1192: @c Prompt
 1193: @c numbers vs. words in dictionary on text interpretation
 1194: @c what happens on redefinition
 1195: @c parsing words (in particular, defining words)
 1196: 
 1197: The difference of this chapter from the Introduction
 1198: (@pxref{Introduction}) is that this tutorial is more fast-paced, should
 1199: be used while sitting in front of a computer, and covers much more
 1200: material, but does not explain how the Forth system works.
 1201: 
 1202: This tutorial can be used with any ANS-compliant Forth; any
 1203: Gforth-specific features are marked as such and you can skip them if you
 1204: work with another Forth.  This tutorial does not explain all features of
 1205: Forth, just enough to get you started and give you some ideas about the
 1206: facilities available in Forth.  Read the rest of the manual and the
 1207: standard when you are through this.
 1208: 
 1209: The intended way to use this tutorial is that you work through it while
 1210: sitting in front of the console, take a look at the examples and predict
 1211: what they will do, then try them out; if the outcome is not as expected,
 1212: find out why (e.g., by trying out variations of the example), so you
 1213: understand what's going on.  There are also some assignments that you
 1214: should solve.
 1215: 
 1216: This tutorial assumes that you have programmed before and know what,
 1217: e.g., a loop is.
 1218: 
 1219: @c !! explain compat library
 1220: 
 1221: @menu
 1222: * Starting Gforth Tutorial::    
 1223: * Syntax Tutorial::             
 1224: * Crash Course Tutorial::       
 1225: * Stack Tutorial::              
 1226: * Arithmetics Tutorial::        
 1227: * Stack Manipulation Tutorial::  
 1228: * Using files for Forth code Tutorial::  
 1229: * Comments Tutorial::           
 1230: * Colon Definitions Tutorial::  
 1231: * Decompilation Tutorial::      
 1232: * Stack-Effect Comments Tutorial::  
 1233: * Types Tutorial::              
 1234: * Factoring Tutorial::          
 1235: * Designing the stack effect Tutorial::  
 1236: * Local Variables Tutorial::    
 1237: * Conditional execution Tutorial::  
 1238: * Flags and Comparisons Tutorial::  
 1239: * General Loops Tutorial::      
 1240: * Counted loops Tutorial::      
 1241: * Recursion Tutorial::          
 1242: * Leaving definitions or loops Tutorial::  
 1243: * Return Stack Tutorial::       
 1244: * Memory Tutorial::             
 1245: * Characters and Strings Tutorial::  
 1246: * Alignment Tutorial::          
 1247: * Floating Point Tutorial::     
 1248: * Files Tutorial::              
 1249: * Interpretation and Compilation Semantics and Immediacy Tutorial::  
 1250: * Execution Tokens Tutorial::   
 1251: * Exceptions Tutorial::         
 1252: * Defining Words Tutorial::     
 1253: * Arrays and Records Tutorial::  
 1254: * POSTPONE Tutorial::           
 1255: * Literal Tutorial::            
 1256: * Advanced macros Tutorial::    
 1257: * Compilation Tokens Tutorial::  
 1258: * Wordlists and Search Order Tutorial::  
 1259: @end menu
 1260: 
 1261: @node Starting Gforth Tutorial, Syntax Tutorial, Tutorial, Tutorial
 1262: @section Starting Gforth
 1263: @cindex starting Gforth tutorial
 1264: You can start Gforth by typing its name:
 1265: 
 1266: @example
 1267: gforth
 1268: @end example
 1269: 
 1270: That puts you into interactive mode; you can leave Gforth by typing
 1271: @code{bye}.  While in Gforth, you can edit the command line and access
 1272: the command line history with cursor keys, similar to bash.
 1273: 
 1274: 
 1275: @node Syntax Tutorial, Crash Course Tutorial, Starting Gforth Tutorial, Tutorial
 1276: @section Syntax
 1277: @cindex syntax tutorial
 1278: 
 1279: A @dfn{word} is a sequence of arbitrary characters (except white
 1280: space).  Words are separated by white space.  E.g., each of the
 1281: following lines contains exactly one word:
 1282: 
 1283: @example
 1284: word
 1285: !@@#$%^&*()
 1286: 1234567890
 1287: 5!a
 1288: @end example
 1289: 
 1290: A frequent beginner's error is to leave away necessary white space,
 1291: resulting in an error like @samp{Undefined word}; so if you see such an
 1292: error, check if you have put spaces wherever necessary.
 1293: 
 1294: @example
 1295: ." hello, world" \ correct
 1296: ."hello, world"  \ gives an "Undefined word" error
 1297: @end example
 1298: 
 1299: Gforth and most other Forth systems ignore differences in case (they are
 1300: case-insensitive), i.e., @samp{word} is the same as @samp{Word}.  If
 1301: your system is case-sensitive, you may have to type all the examples
 1302: given here in upper case.
 1303: 
 1304: 
 1305: @node Crash Course Tutorial, Stack Tutorial, Syntax Tutorial, Tutorial
 1306: @section Crash Course
 1307: 
 1308: Type
 1309: 
 1310: @example
 1311: 0 0 !
 1312: here execute
 1313: ' catch >body 20 erase abort
 1314: ' (quit) >body 20 erase
 1315: @end example
 1316: 
 1317: The last two examples are guaranteed to destroy parts of Gforth (and
 1318: most other systems), so you better leave Gforth afterwards (if it has
 1319: not finished by itself).  On some systems you may have to kill gforth
 1320: from outside (e.g., in Unix with @code{kill}).
 1321: 
 1322: Now that you know how to produce crashes (and that there's not much to
 1323: them), let's learn how to produce meaningful programs.
 1324: 
 1325: 
 1326: @node Stack Tutorial, Arithmetics Tutorial, Crash Course Tutorial, Tutorial
 1327: @section Stack
 1328: @cindex stack tutorial
 1329: 
 1330: The most obvious feature of Forth is the stack.  When you type in a
 1331: number, it is pushed on the stack.  You can display the content of the
 1332: stack with @code{.s}.
 1333: 
 1334: @example
 1335: 1 2 .s
 1336: 3 .s
 1337: @end example
 1338: 
 1339: @code{.s} displays the top-of-stack to the right, i.e., the numbers
 1340: appear in @code{.s} output as they appeared in the input.
 1341: 
 1342: You can print the top of stack element with @code{.}.
 1343: 
 1344: @example
 1345: 1 2 3 . . .
 1346: @end example
 1347: 
 1348: In general, words consume their stack arguments (@code{.s} is an
 1349: exception).
 1350: 
 1351: @quotation Assignment
 1352: What does the stack contain after @code{5 6 7 .}?
 1353: @end quotation
 1354: 
 1355: 
 1356: @node Arithmetics Tutorial, Stack Manipulation Tutorial, Stack Tutorial, Tutorial
 1357: @section Arithmetics
 1358: @cindex arithmetics tutorial
 1359: 
 1360: The words @code{+}, @code{-}, @code{*}, @code{/}, and @code{mod} always
 1361: operate on the top two stack items:
 1362: 
 1363: @example
 1364: 2 2 .s
 1365: + .s
 1366: .
 1367: 2 1 - .
 1368: 7 3 mod .
 1369: @end example
 1370: 
 1371: The operands of @code{-}, @code{/}, and @code{mod} are in the same order
 1372: as in the corresponding infix expression (this is generally the case in
 1373: Forth).
 1374: 
 1375: Parentheses are superfluous (and not available), because the order of
 1376: the words unambiguously determines the order of evaluation and the
 1377: operands:
 1378: 
 1379: @example
 1380: 3 4 + 5 * .
 1381: 3 4 5 * + .
 1382: @end example
 1383: 
 1384: @quotation Assignment
 1385: What are the infix expressions corresponding to the Forth code above?
 1386: Write @code{6-7*8+9} in Forth notation@footnote{This notation is also
 1387: known as Postfix or RPN (Reverse Polish Notation).}.
 1388: @end quotation
 1389: 
 1390: To change the sign, use @code{negate}:
 1391: 
 1392: @example
 1393: 2 negate .
 1394: @end example
 1395: 
 1396: @quotation Assignment
 1397: Convert -(-3)*4-5 to Forth.
 1398: @end quotation
 1399: 
 1400: @code{/mod} performs both @code{/} and @code{mod}.
 1401: 
 1402: @example
 1403: 7 3 /mod . .
 1404: @end example
 1405: 
 1406: Reference: @ref{Arithmetic}.
 1407: 
 1408: 
 1409: @node Stack Manipulation Tutorial, Using files for Forth code Tutorial, Arithmetics Tutorial, Tutorial
 1410: @section Stack Manipulation
 1411: @cindex stack manipulation tutorial
 1412: 
 1413: Stack manipulation words rearrange the data on the stack.
 1414: 
 1415: @example
 1416: 1 .s drop .s
 1417: 1 .s dup .s drop drop .s
 1418: 1 2 .s over .s drop drop drop
 1419: 1 2 .s swap .s drop drop
 1420: 1 2 3 .s rot .s drop drop drop
 1421: @end example
 1422: 
 1423: These are the most important stack manipulation words.  There are also
 1424: variants that manipulate twice as many stack items:
 1425: 
 1426: @example
 1427: 1 2 3 4 .s 2swap .s 2drop 2drop
 1428: @end example
 1429: 
 1430: Two more stack manipulation words are:
 1431: 
 1432: @example
 1433: 1 2 .s nip .s drop
 1434: 1 2 .s tuck .s 2drop drop
 1435: @end example
 1436: 
 1437: @quotation Assignment
 1438: Replace @code{nip} and @code{tuck} with combinations of other stack
 1439: manipulation words.
 1440: 
 1441: @example
 1442: Given:          How do you get:
 1443: 1 2 3           3 2 1           
 1444: 1 2 3           1 2 3 2                 
 1445: 1 2 3           1 2 3 3                 
 1446: 1 2 3           1 3 3           
 1447: 1 2 3           2 1 3           
 1448: 1 2 3 4         4 3 2 1         
 1449: 1 2 3           1 2 3 1 2 3             
 1450: 1 2 3 4         1 2 3 4 1 2             
 1451: 1 2 3
 1452: 1 2 3           1 2 3 4                 
 1453: 1 2 3           1 3             
 1454: @end example
 1455: @end quotation
 1456: 
 1457: @example
 1458: 5 dup * .
 1459: @end example
 1460: 
 1461: @quotation Assignment
 1462: Write 17^3 and 17^4 in Forth, without writing @code{17} more than once.
 1463: Write a piece of Forth code that expects two numbers on the stack
 1464: (@var{a} and @var{b}, with @var{b} on top) and computes
 1465: @code{(a-b)(a+1)}.
 1466: @end quotation
 1467: 
 1468: Reference: @ref{Stack Manipulation}.
 1469: 
 1470: 
 1471: @node Using files for Forth code Tutorial, Comments Tutorial, Stack Manipulation Tutorial, Tutorial
 1472: @section Using files for Forth code
 1473: @cindex loading Forth code, tutorial
 1474: @cindex files containing Forth code, tutorial
 1475: 
 1476: While working at the Forth command line is convenient for one-line
 1477: examples and short one-off code, you probably want to store your source
 1478: code in files for convenient editing and persistence.  You can use your
 1479: favourite editor (Gforth includes Emacs support, @pxref{Emacs and
 1480: Gforth}) to create @var{file.fs} and use
 1481: 
 1482: @example
 1483: s" @var{file.fs}" included
 1484: @end example
 1485: 
 1486: to load it into your Forth system.  The file name extension I use for
 1487: Forth files is @samp{.fs}.
 1488: 
 1489: You can easily start Gforth with some files loaded like this:
 1490: 
 1491: @example
 1492: gforth @var{file1.fs} @var{file2.fs}
 1493: @end example
 1494: 
 1495: If an error occurs during loading these files, Gforth terminates,
 1496: whereas an error during @code{INCLUDED} within Gforth usually gives you
 1497: a Gforth command line.  Starting the Forth system every time gives you a
 1498: clean start every time, without interference from the results of earlier
 1499: tries.
 1500: 
 1501: I often put all the tests in a file, then load the code and run the
 1502: tests with
 1503: 
 1504: @example
 1505: gforth @var{code.fs} @var{tests.fs} -e bye
 1506: @end example
 1507: 
 1508: (often by performing this command with @kbd{C-x C-e} in Emacs).  The
 1509: @code{-e bye} ensures that Gforth terminates afterwards so that I can
 1510: restart this command without ado.
 1511: 
 1512: The advantage of this approach is that the tests can be repeated easily
 1513: every time the program ist changed, making it easy to catch bugs
 1514: introduced by the change.
 1515: 
 1516: Reference: @ref{Forth source files}.
 1517: 
 1518: 
 1519: @node Comments Tutorial, Colon Definitions Tutorial, Using files for Forth code Tutorial, Tutorial
 1520: @section Comments
 1521: @cindex comments tutorial
 1522: 
 1523: @example
 1524: \ That's a comment; it ends at the end of the line
 1525: ( Another comment; it ends here: )  .s
 1526: @end example
 1527: 
 1528: @code{\} and @code{(} are ordinary Forth words and therefore have to be
 1529: separated with white space from the following text.
 1530: 
 1531: @example
 1532: \This gives an "Undefined word" error
 1533: @end example
 1534: 
 1535: The first @code{)} ends a comment started with @code{(}, so you cannot
 1536: nest @code{(}-comments; and you cannot comment out text containing a
 1537: @code{)} with @code{( ... )}@footnote{therefore it's a good idea to
 1538: avoid @code{)} in word names.}.
 1539: 
 1540: I use @code{\}-comments for descriptive text and for commenting out code
 1541: of one or more line; I use @code{(}-comments for describing the stack
 1542: effect, the stack contents, or for commenting out sub-line pieces of
 1543: code.
 1544: 
 1545: The Emacs mode @file{gforth.el} (@pxref{Emacs and Gforth}) supports
 1546: these uses by commenting out a region with @kbd{C-x \}, uncommenting a
 1547: region with @kbd{C-u C-x \}, and filling a @code{\}-commented region
 1548: with @kbd{M-q}.
 1549: 
 1550: Reference: @ref{Comments}.
 1551: 
 1552: 
 1553: @node Colon Definitions Tutorial, Decompilation Tutorial, Comments Tutorial, Tutorial
 1554: @section Colon Definitions
 1555: @cindex colon definitions, tutorial
 1556: @cindex definitions, tutorial
 1557: @cindex procedures, tutorial
 1558: @cindex functions, tutorial
 1559: 
 1560: are similar to procedures and functions in other programming languages.
 1561: 
 1562: @example
 1563: : squared ( n -- n^2 )
 1564:    dup * ;
 1565: 5 squared .
 1566: 7 squared .
 1567: @end example
 1568: 
 1569: @code{:} starts the colon definition; its name is @code{squared}.  The
 1570: following comment describes its stack effect.  The words @code{dup *}
 1571: are not executed, but compiled into the definition.  @code{;} ends the
 1572: colon definition.
 1573: 
 1574: The newly-defined word can be used like any other word, including using
 1575: it in other definitions:
 1576: 
 1577: @example
 1578: : cubed ( n -- n^3 )
 1579:    dup squared * ;
 1580: -5 cubed .
 1581: : fourth-power ( n -- n^4 )
 1582:    squared squared ;
 1583: 3 fourth-power .
 1584: @end example
 1585: 
 1586: @quotation Assignment
 1587: Write colon definitions for @code{nip}, @code{tuck}, @code{negate}, and
 1588: @code{/mod} in terms of other Forth words, and check if they work (hint:
 1589: test your tests on the originals first).  Don't let the
 1590: @samp{redefined}-Messages spook you, they are just warnings.
 1591: @end quotation
 1592: 
 1593: Reference: @ref{Colon Definitions}.
 1594: 
 1595: 
 1596: @node Decompilation Tutorial, Stack-Effect Comments Tutorial, Colon Definitions Tutorial, Tutorial
 1597: @section Decompilation
 1598: @cindex decompilation tutorial
 1599: @cindex see tutorial
 1600: 
 1601: You can decompile colon definitions with @code{see}:
 1602: 
 1603: @example
 1604: see squared
 1605: see cubed
 1606: @end example
 1607: 
 1608: In Gforth @code{see} shows you a reconstruction of the source code from
 1609: the executable code.  Informations that were present in the source, but
 1610: not in the executable code, are lost (e.g., comments).
 1611: 
 1612: You can also decompile the predefined words:
 1613: 
 1614: @example
 1615: see .
 1616: see +
 1617: @end example
 1618: 
 1619: 
 1620: @node Stack-Effect Comments Tutorial, Types Tutorial, Decompilation Tutorial, Tutorial
 1621: @section Stack-Effect Comments
 1622: @cindex stack-effect comments, tutorial
 1623: @cindex --, tutorial
 1624: By convention the comment after the name of a definition describes the
 1625: stack effect: The part in front of the @samp{--} describes the state of
 1626: the stack before the execution of the definition, i.e., the parameters
 1627: that are passed into the colon definition; the part behind the @samp{--}
 1628: is the state of the stack after the execution of the definition, i.e.,
 1629: the results of the definition.  The stack comment only shows the top
 1630: stack items that the definition accesses and/or changes.
 1631: 
 1632: You should put a correct stack effect on every definition, even if it is
 1633: just @code{( -- )}.  You should also add some descriptive comment to
 1634: more complicated words (I usually do this in the lines following
 1635: @code{:}).  If you don't do this, your code becomes unreadable (because
 1636: you have to work through every definition before you can understand
 1637: any).
 1638: 
 1639: @quotation Assignment
 1640: The stack effect of @code{swap} can be written like this: @code{x1 x2 --
 1641: x2 x1}.  Describe the stack effect of @code{-}, @code{drop}, @code{dup},
 1642: @code{over}, @code{rot}, @code{nip}, and @code{tuck}.  Hint: When you
 1643: are done, you can compare your stack effects to those in this manual
 1644: (@pxref{Word Index}).
 1645: @end quotation
 1646: 
 1647: Sometimes programmers put comments at various places in colon
 1648: definitions that describe the contents of the stack at that place (stack
 1649: comments); i.e., they are like the first part of a stack-effect
 1650: comment. E.g.,
 1651: 
 1652: @example
 1653: : cubed ( n -- n^3 )
 1654:    dup squared  ( n n^2 ) * ;
 1655: @end example
 1656: 
 1657: In this case the stack comment is pretty superfluous, because the word
 1658: is simple enough.  If you think it would be a good idea to add such a
 1659: comment to increase readability, you should also consider factoring the
 1660: word into several simpler words (@pxref{Factoring Tutorial,,
 1661: Factoring}), which typically eliminates the need for the stack comment;
 1662: however, if you decide not to refactor it, then having such a comment is
 1663: better than not having it.
 1664: 
 1665: The names of the stack items in stack-effect and stack comments in the
 1666: standard, in this manual, and in many programs specify the type through
 1667: a type prefix, similar to Fortran and Hungarian notation.  The most
 1668: frequent prefixes are:
 1669: 
 1670: @table @code
 1671: @item n
 1672: signed integer
 1673: @item u
 1674: unsigned integer
 1675: @item c
 1676: character
 1677: @item f
 1678: Boolean flags, i.e. @code{false} or @code{true}.
 1679: @item a-addr,a-
 1680: Cell-aligned address
 1681: @item c-addr,c-
 1682: Char-aligned address (note that a Char may have two bytes in Windows NT)
 1683: @item xt
 1684: Execution token, same size as Cell
 1685: @item w,x
 1686: Cell, can contain an integer or an address.  It usually takes 32, 64 or
 1687: 16 bits (depending on your platform and Forth system). A cell is more
 1688: commonly known as machine word, but the term @emph{word} already means
 1689: something different in Forth.
 1690: @item d
 1691: signed double-cell integer
 1692: @item ud
 1693: unsigned double-cell integer
 1694: @item r
 1695: Float (on the FP stack)
 1696: @end table
 1697: 
 1698: You can find a more complete list in @ref{Notation}.
 1699: 
 1700: @quotation Assignment
 1701: Write stack-effect comments for all definitions you have written up to
 1702: now.
 1703: @end quotation
 1704: 
 1705: 
 1706: @node Types Tutorial, Factoring Tutorial, Stack-Effect Comments Tutorial, Tutorial
 1707: @section Types
 1708: @cindex types tutorial
 1709: 
 1710: In Forth the names of the operations are not overloaded; so similar
 1711: operations on different types need different names; e.g., @code{+} adds
 1712: integers, and you have to use @code{f+} to add floating-point numbers.
 1713: The following prefixes are often used for related operations on
 1714: different types:
 1715: 
 1716: @table @code
 1717: @item (none)
 1718: signed integer
 1719: @item u
 1720: unsigned integer
 1721: @item c
 1722: character
 1723: @item d
 1724: signed double-cell integer
 1725: @item ud, du
 1726: unsigned double-cell integer
 1727: @item 2
 1728: two cells (not-necessarily double-cell numbers)
 1729: @item m, um
 1730: mixed single-cell and double-cell operations
 1731: @item f
 1732: floating-point (note that in stack comments @samp{f} represents flags,
 1733: and @samp{r} represents FP numbers).
 1734: @end table
 1735: 
 1736: If there are no differences between the signed and the unsigned variant
 1737: (e.g., for @code{+}), there is only the prefix-less variant.
 1738: 
 1739: Forth does not perform type checking, neither at compile time, nor at
 1740: run time.  If you use the wrong oeration, the data are interpreted
 1741: incorrectly:
 1742: 
 1743: @example
 1744: -1 u.
 1745: @end example
 1746: 
 1747: If you have only experience with type-checked languages until now, and
 1748: have heard how important type-checking is, don't panic!  In my
 1749: experience (and that of other Forthers), type errors in Forth code are
 1750: usually easy to find (once you get used to it), the increased vigilance
 1751: of the programmer tends to catch some harder errors in addition to most
 1752: type errors, and you never have to work around the type system, so in
 1753: most situations the lack of type-checking seems to be a win (projects to
 1754: add type checking to Forth have not caught on).
 1755: 
 1756: 
 1757: @node Factoring Tutorial, Designing the stack effect Tutorial, Types Tutorial, Tutorial
 1758: @section Factoring
 1759: @cindex factoring tutorial
 1760: 
 1761: If you try to write longer definitions, you will soon find it hard to
 1762: keep track of the stack contents.  Therefore, good Forth programmers
 1763: tend to write only short definitions (e.g., three lines).  The art of
 1764: finding meaningful short definitions is known as factoring (as in
 1765: factoring polynomials).
 1766: 
 1767: Well-factored programs offer additional advantages: smaller, more
 1768: general words, are easier to test and debug and can be reused more and
 1769: better than larger, specialized words.
 1770: 
 1771: So, if you run into difficulties with stack management, when writing
 1772: code, try to define meaningful factors for the word, and define the word
 1773: in terms of those.  Even if a factor contains only two words, it is
 1774: often helpful.
 1775: 
 1776: Good factoring is not easy, and it takes some practice to get the knack
 1777: for it; but even experienced Forth programmers often don't find the
 1778: right solution right away, but only when rewriting the program.  So, if
 1779: you don't come up with a good solution immediately, keep trying, don't
 1780: despair.
 1781: 
 1782: @c example !!
 1783: 
 1784: 
 1785: @node Designing the stack effect Tutorial, Local Variables Tutorial, Factoring Tutorial, Tutorial
 1786: @section Designing the stack effect
 1787: @cindex Stack effect design, tutorial
 1788: @cindex design of stack effects, tutorial
 1789: 
 1790: In other languages you can use an arbitrary order of parameters for a
 1791: function; and since there is only one result, you don't have to deal with
 1792: the order of results, either.
 1793: 
 1794: In Forth (and other stack-based languages, e.g., PostScript) the
 1795: parameter and result order of a definition is important and should be
 1796: designed well.  The general guideline is to design the stack effect such
 1797: that the word is simple to use in most cases, even if that complicates
 1798: the implementation of the word.  Some concrete rules are:
 1799: 
 1800: @itemize @bullet
 1801: 
 1802: @item
 1803: Words consume all of their parameters (e.g., @code{.}).
 1804: 
 1805: @item
 1806: If there is a convention on the order of parameters (e.g., from
 1807: mathematics or another programming language), stick with it (e.g.,
 1808: @code{-}).
 1809: 
 1810: @item
 1811: If one parameter usually requires only a short computation (e.g., it is
 1812: a constant), pass it on the top of the stack.  Conversely, parameters
 1813: that usually require a long sequence of code to compute should be passed
 1814: as the bottom (i.e., first) parameter.  This makes the code easier to
 1815: read, because the reader does not need to keep track of the bottom item
 1816: through a long sequence of code (or, alternatively, through stack
 1817: manipulations). E.g., @code{!} (store, @pxref{Memory}) expects the
 1818: address on top of the stack because it is usually simpler to compute
 1819: than the stored value (often the address is just a variable).
 1820: 
 1821: @item
 1822: Similarly, results that are usually consumed quickly should be returned
 1823: on the top of stack, whereas a result that is often used in long
 1824: computations should be passed as bottom result.  E.g., the file words
 1825: like @code{open-file} return the error code on the top of stack, because
 1826: it is usually consumed quickly by @code{throw}; moreover, the error code
 1827: has to be checked before doing anything with the other results.
 1828: 
 1829: @end itemize
 1830: 
 1831: These rules are just general guidelines, don't lose sight of the overall
 1832: goal to make the words easy to use.  E.g., if the convention rule
 1833: conflicts with the computation-length rule, you might decide in favour
 1834: of the convention if the word will be used rarely, and in favour of the
 1835: computation-length rule if the word will be used frequently (because
 1836: with frequent use the cost of breaking the computation-length rule would
 1837: be quite high, and frequent use makes it easier to remember an
 1838: unconventional order).
 1839: 
 1840: @c example !! structure package
 1841: 
 1842: 
 1843: @node Local Variables Tutorial, Conditional execution Tutorial, Designing the stack effect Tutorial, Tutorial
 1844: @section Local Variables
 1845: @cindex local variables, tutorial
 1846: 
 1847: You can define local variables (@emph{locals}) in a colon definition:
 1848: 
 1849: @example
 1850: : swap @{ a b -- b a @}
 1851:   b a ;
 1852: 1 2 swap .s 2drop
 1853: @end example
 1854: 
 1855: (If your Forth system does not support this syntax, include
 1856: @file{compat/anslocal.fs} first).
 1857: 
 1858: In this example @code{@{ a b -- b a @}} is the locals definition; it
 1859: takes two cells from the stack, puts the top of stack in @code{b} and
 1860: the next stack element in @code{a}.  @code{--} starts a comment ending
 1861: with @code{@}}.  After the locals definition, using the name of the
 1862: local will push its value on the stack.  You can leave the comment
 1863: part (@code{-- b a}) away:
 1864: 
 1865: @example
 1866: : swap ( x1 x2 -- x2 x1 )
 1867:   @{ a b @} b a ;
 1868: @end example
 1869: 
 1870: In Gforth you can have several locals definitions, anywhere in a colon
 1871: definition; in contrast, in a standard program you can have only one
 1872: locals definition per colon definition, and that locals definition must
 1873: be outside any control structure.
 1874: 
 1875: With locals you can write slightly longer definitions without running
 1876: into stack trouble.  However, I recommend trying to write colon
 1877: definitions without locals for exercise purposes to help you gain the
 1878: essential factoring skills.
 1879: 
 1880: @quotation Assignment
 1881: Rewrite your definitions until now with locals
 1882: @end quotation
 1883: 
 1884: Reference: @ref{Locals}.
 1885: 
 1886: 
 1887: @node Conditional execution Tutorial, Flags and Comparisons Tutorial, Local Variables Tutorial, Tutorial
 1888: @section Conditional execution
 1889: @cindex conditionals, tutorial
 1890: @cindex if, tutorial
 1891: 
 1892: In Forth you can use control structures only inside colon definitions.
 1893: An @code{if}-structure looks like this:
 1894: 
 1895: @example
 1896: : abs ( n1 -- +n2 )
 1897:     dup 0 < if
 1898:         negate
 1899:     endif ;
 1900: 5 abs .
 1901: -5 abs .
 1902: @end example
 1903: 
 1904: @code{if} takes a flag from the stack.  If the flag is non-zero (true),
 1905: the following code is performed, otherwise execution continues after the
 1906: @code{endif} (or @code{else}).  @code{<} compares the top two stack
 1907: elements and produces a flag:
 1908: 
 1909: @example
 1910: 1 2 < .
 1911: 2 1 < .
 1912: 1 1 < .
 1913: @end example
 1914: 
 1915: Actually the standard name for @code{endif} is @code{then}.  This
 1916: tutorial presents the examples using @code{endif}, because this is often
 1917: less confusing for people familiar with other programming languages
 1918: where @code{then} has a different meaning.  If your system does not have
 1919: @code{endif}, define it with
 1920: 
 1921: @example
 1922: : endif postpone then ; immediate
 1923: @end example
 1924: 
 1925: You can optionally use an @code{else}-part:
 1926: 
 1927: @example
 1928: : min ( n1 n2 -- n )
 1929:   2dup < if
 1930:     drop
 1931:   else
 1932:     nip
 1933:   endif ;
 1934: 2 3 min .
 1935: 3 2 min .
 1936: @end example
 1937: 
 1938: @quotation Assignment
 1939: Write @code{min} without @code{else}-part (hint: what's the definition
 1940: of @code{nip}?).
 1941: @end quotation
 1942: 
 1943: Reference: @ref{Selection}.
 1944: 
 1945: 
 1946: @node Flags and Comparisons Tutorial, General Loops Tutorial, Conditional execution Tutorial, Tutorial
 1947: @section Flags and Comparisons
 1948: @cindex flags tutorial
 1949: @cindex comparison tutorial
 1950: 
 1951: In a false-flag all bits are clear (0 when interpreted as integer).  In
 1952: a canonical true-flag all bits are set (-1 as a twos-complement signed
 1953: integer); in many contexts (e.g., @code{if}) any non-zero value is
 1954: treated as true flag.
 1955: 
 1956: @example
 1957: false .
 1958: true .
 1959: true hex u. decimal
 1960: @end example
 1961: 
 1962: Comparison words produce canonical flags:
 1963: 
 1964: @example
 1965: 1 1 = .
 1966: 1 0= .
 1967: 0 1 < .
 1968: 0 0 < .
 1969: -1 1 u< . \ type error, u< interprets -1 as large unsigned number
 1970: -1 1 < .
 1971: @end example
 1972: 
 1973: Gforth supports all combinations of the prefixes @code{0 u d d0 du f f0}
 1974: (or none) and the comparisons @code{= <> < > <= >=}.  Only a part of
 1975: these combinations are standard (for details see the standard,
 1976: @ref{Numeric comparison}, @ref{Floating Point} or @ref{Word Index}).
 1977: 
 1978: You can use @code{and or xor invert} as operations on canonical flags.
 1979: Actually they are bitwise operations:
 1980: 
 1981: @example
 1982: 1 2 and .
 1983: 1 2 or .
 1984: 1 3 xor .
 1985: 1 invert .
 1986: @end example
 1987: 
 1988: You can convert a zero/non-zero flag into a canonical flag with
 1989: @code{0<>} (and complement it on the way with @code{0=}).
 1990: 
 1991: @example
 1992: 1 0= .
 1993: 1 0<> .
 1994: @end example
 1995: 
 1996: You can use the all-bits-set feature of canonical flags and the bitwise
 1997: operation of the Boolean operations to avoid @code{if}s:
 1998: 
 1999: @example
 2000: : foo ( n1 -- n2 )
 2001:   0= if
 2002:     14
 2003:   else
 2004:     0
 2005:   endif ;
 2006: 0 foo .
 2007: 1 foo .
 2008: 
 2009: : foo ( n1 -- n2 )
 2010:   0= 14 and ;
 2011: 0 foo .
 2012: 1 foo .
 2013: @end example
 2014: 
 2015: @quotation Assignment
 2016: Write @code{min} without @code{if}.
 2017: @end quotation
 2018: 
 2019: For reference, see @ref{Boolean Flags}, @ref{Numeric comparison}, and
 2020: @ref{Bitwise operations}.
 2021: 
 2022: 
 2023: @node General Loops Tutorial, Counted loops Tutorial, Flags and Comparisons Tutorial, Tutorial
 2024: @section General Loops
 2025: @cindex loops, indefinite, tutorial
 2026: 
 2027: The endless loop is the most simple one:
 2028: 
 2029: @example
 2030: : endless ( -- )
 2031:   0 begin
 2032:     dup . 1+
 2033:   again ;
 2034: endless
 2035: @end example
 2036: 
 2037: Terminate this loop by pressing @kbd{Ctrl-C} (in Gforth).  @code{begin}
 2038: does nothing at run-time, @code{again} jumps back to @code{begin}.
 2039: 
 2040: A loop with one exit at any place looks like this:
 2041: 
 2042: @example
 2043: : log2 ( +n1 -- n2 )
 2044: \ logarithmus dualis of n1>0, rounded down to the next integer
 2045:   assert( dup 0> )
 2046:   2/ 0 begin
 2047:     over 0> while
 2048:       1+ swap 2/ swap
 2049:   repeat
 2050:   nip ;
 2051: 7 log2 .
 2052: 8 log2 .
 2053: @end example
 2054: 
 2055: At run-time @code{while} consumes a flag; if it is 0, execution
 2056: continues behind the @code{repeat}; if the flag is non-zero, execution
 2057: continues behind the @code{while}.  @code{Repeat} jumps back to
 2058: @code{begin}, just like @code{again}.
 2059: 
 2060: In Forth there are many combinations/abbreviations, like @code{1+}.
 2061: However, @code{2/} is not one of them; it shifts its argument right by
 2062: one bit (arithmetic shift right):
 2063: 
 2064: @example
 2065: -5 2 / .
 2066: -5 2/ .
 2067: @end example
 2068: 
 2069: @code{assert(} is no standard word, but you can get it on systems other
 2070: than Gforth by including @file{compat/assert.fs}.  You can see what it
 2071: does by trying
 2072: 
 2073: @example
 2074: 0 log2 .
 2075: @end example
 2076: 
 2077: Here's a loop with an exit at the end:
 2078: 
 2079: @example
 2080: : log2 ( +n1 -- n2 )
 2081: \ logarithmus dualis of n1>0, rounded down to the next integer
 2082:   assert( dup 0 > )
 2083:   -1 begin
 2084:     1+ swap 2/ swap
 2085:     over 0 <=
 2086:   until
 2087:   nip ;
 2088: @end example
 2089: 
 2090: @code{Until} consumes a flag; if it is non-zero, execution continues at
 2091: the @code{begin}, otherwise after the @code{until}.
 2092: 
 2093: @quotation Assignment
 2094: Write a definition for computing the greatest common divisor.
 2095: @end quotation
 2096: 
 2097: Reference: @ref{Simple Loops}.
 2098: 
 2099: 
 2100: @node Counted loops Tutorial, Recursion Tutorial, General Loops Tutorial, Tutorial
 2101: @section Counted loops
 2102: @cindex loops, counted, tutorial
 2103: 
 2104: @example
 2105: : ^ ( n1 u -- n )
 2106: \ n = the uth power of n1
 2107:   1 swap 0 u+do
 2108:     over *
 2109:   loop
 2110:   nip ;
 2111: 3 2 ^ .
 2112: 4 3 ^ .
 2113: @end example
 2114: 
 2115: @code{U+do} (from @file{compat/loops.fs}, if your Forth system doesn't
 2116: have it) takes two numbers of the stack @code{( u3 u4 -- )}, and then
 2117: performs the code between @code{u+do} and @code{loop} for @code{u3-u4}
 2118: times (or not at all, if @code{u3-u4<0}).
 2119: 
 2120: You can see the stack effect design rules at work in the stack effect of
 2121: the loop start words: Since the start value of the loop is more
 2122: frequently constant than the end value, the start value is passed on
 2123: the top-of-stack.
 2124: 
 2125: You can access the counter of a counted loop with @code{i}:
 2126: 
 2127: @example
 2128: : fac ( u -- u! )
 2129:   1 swap 1+ 1 u+do
 2130:     i *
 2131:   loop ;
 2132: 5 fac .
 2133: 7 fac .
 2134: @end example
 2135: 
 2136: There is also @code{+do}, which expects signed numbers (important for
 2137: deciding whether to enter the loop).
 2138: 
 2139: @quotation Assignment
 2140: Write a definition for computing the nth Fibonacci number.
 2141: @end quotation
 2142: 
 2143: You can also use increments other than 1:
 2144: 
 2145: @example
 2146: : up2 ( n1 n2 -- )
 2147:   +do
 2148:     i .
 2149:   2 +loop ;
 2150: 10 0 up2
 2151: 
 2152: : down2 ( n1 n2 -- )
 2153:   -do
 2154:     i .
 2155:   2 -loop ;
 2156: 0 10 down2
 2157: @end example
 2158: 
 2159: Reference: @ref{Counted Loops}.
 2160: 
 2161: 
 2162: @node Recursion Tutorial, Leaving definitions or loops Tutorial, Counted loops Tutorial, Tutorial
 2163: @section Recursion
 2164: @cindex recursion tutorial
 2165: 
 2166: Usually the name of a definition is not visible in the definition; but
 2167: earlier definitions are usually visible:
 2168: 
 2169: @example
 2170: 1 0 / . \ "Floating-point unidentified fault" in Gforth on some platforms
 2171: : / ( n1 n2 -- n )
 2172:   dup 0= if
 2173:     -10 throw \ report division by zero
 2174:   endif
 2175:   /           \ old version
 2176: ;
 2177: 1 0 /
 2178: @end example
 2179: 
 2180: For recursive definitions you can use @code{recursive} (non-standard) or
 2181: @code{recurse}:
 2182: 
 2183: @example
 2184: : fac1 ( n -- n! ) recursive
 2185:  dup 0> if
 2186:    dup 1- fac1 *
 2187:  else
 2188:    drop 1
 2189:  endif ;
 2190: 7 fac1 .
 2191: 
 2192: : fac2 ( n -- n! )
 2193:  dup 0> if
 2194:    dup 1- recurse *
 2195:  else
 2196:    drop 1
 2197:  endif ;
 2198: 8 fac2 .
 2199: @end example
 2200: 
 2201: @quotation Assignment
 2202: Write a recursive definition for computing the nth Fibonacci number.
 2203: @end quotation
 2204: 
 2205: Reference (including indirect recursion): @xref{Calls and returns}.
 2206: 
 2207: 
 2208: @node Leaving definitions or loops Tutorial, Return Stack Tutorial, Recursion Tutorial, Tutorial
 2209: @section Leaving definitions or loops
 2210: @cindex leaving definitions, tutorial
 2211: @cindex leaving loops, tutorial
 2212: 
 2213: @code{EXIT} exits the current definition right away.  For every counted
 2214: loop that is left in this way, an @code{UNLOOP} has to be performed
 2215: before the @code{EXIT}:
 2216: 
 2217: @c !! real examples
 2218: @example
 2219: : ...
 2220:  ... u+do
 2221:    ... if
 2222:      ... unloop exit
 2223:    endif
 2224:    ...
 2225:  loop
 2226:  ... ;
 2227: @end example
 2228: 
 2229: @code{LEAVE} leaves the innermost counted loop right away:
 2230: 
 2231: @example
 2232: : ...
 2233:  ... u+do
 2234:    ... if
 2235:      ... leave
 2236:    endif
 2237:    ...
 2238:  loop
 2239:  ... ;
 2240: @end example
 2241: 
 2242: @c !! example
 2243: 
 2244: Reference: @ref{Calls and returns}, @ref{Counted Loops}.
 2245: 
 2246: 
 2247: @node Return Stack Tutorial, Memory Tutorial, Leaving definitions or loops Tutorial, Tutorial
 2248: @section Return Stack
 2249: @cindex return stack tutorial
 2250: 
 2251: In addition to the data stack Forth also has a second stack, the return
 2252: stack; most Forth systems store the return addresses of procedure calls
 2253: there (thus its name).  Programmers can also use this stack:
 2254: 
 2255: @example
 2256: : foo ( n1 n2 -- )
 2257:  .s
 2258:  >r .s
 2259:  r@@ .
 2260:  >r .s
 2261:  r@@ .
 2262:  r> .
 2263:  r@@ .
 2264:  r> . ;
 2265: 1 2 foo
 2266: @end example
 2267: 
 2268: @code{>r} takes an element from the data stack and pushes it onto the
 2269: return stack; conversely, @code{r>} moves an elementm from the return to
 2270: the data stack; @code{r@@} pushes a copy of the top of the return stack
 2271: on the data stack.
 2272: 
 2273: Forth programmers usually use the return stack for storing data
 2274: temporarily, if using the data stack alone would be too complex, and
 2275: factoring and locals are not an option:
 2276: 
 2277: @example
 2278: : 2swap ( x1 x2 x3 x4 -- x3 x4 x1 x2 )
 2279:  rot >r rot r> ;
 2280: @end example
 2281: 
 2282: The return address of the definition and the loop control parameters of
 2283: counted loops usually reside on the return stack, so you have to take
 2284: all items, that you have pushed on the return stack in a colon
 2285: definition or counted loop, from the return stack before the definition
 2286: or loop ends.  You cannot access items that you pushed on the return
 2287: stack outside some definition or loop within the definition of loop.
 2288: 
 2289: If you miscount the return stack items, this usually ends in a crash:
 2290: 
 2291: @example
 2292: : crash ( n -- )
 2293:   >r ;
 2294: 5 crash
 2295: @end example
 2296: 
 2297: You cannot mix using locals and using the return stack (according to the
 2298: standard; Gforth has no problem).  However, they solve the same
 2299: problems, so this shouldn't be an issue.
 2300: 
 2301: @quotation Assignment
 2302: Can you rewrite any of the definitions you wrote until now in a better
 2303: way using the return stack?
 2304: @end quotation
 2305: 
 2306: Reference: @ref{Return stack}.
 2307: 
 2308: 
 2309: @node Memory Tutorial, Characters and Strings Tutorial, Return Stack Tutorial, Tutorial
 2310: @section Memory
 2311: @cindex memory access/allocation tutorial
 2312: 
 2313: You can create a global variable @code{v} with
 2314: 
 2315: @example
 2316: variable v ( -- addr )
 2317: @end example
 2318: 
 2319: @code{v} pushes the address of a cell in memory on the stack.  This cell
 2320: was reserved by @code{variable}.  You can use @code{!} (store) to store
 2321: values into this cell and @code{@@} (fetch) to load the value from the
 2322: stack into memory:
 2323: 
 2324: @example
 2325: v .
 2326: 5 v ! .s
 2327: v @@ .
 2328: @end example
 2329: 
 2330: You can see a raw dump of memory with @code{dump}:
 2331: 
 2332: @example
 2333: v 1 cells .s dump
 2334: @end example
 2335: 
 2336: @code{Cells ( n1 -- n2 )} gives you the number of bytes (or, more
 2337: generally, address units (aus)) that @code{n1 cells} occupy.  You can
 2338: also reserve more memory:
 2339: 
 2340: @example
 2341: create v2 20 cells allot
 2342: v2 20 cells dump
 2343: @end example
 2344: 
 2345: creates a word @code{v2} and reserves 20 uninitialized cells; the
 2346: address pushed by @code{v2} points to the start of these 20 cells.  You
 2347: can use address arithmetic to access these cells:
 2348: 
 2349: @example
 2350: 3 v2 5 cells + !
 2351: v2 20 cells dump
 2352: @end example
 2353: 
 2354: You can reserve and initialize memory with @code{,}:
 2355: 
 2356: @example
 2357: create v3
 2358:   5 , 4 , 3 , 2 , 1 ,
 2359: v3 @@ .
 2360: v3 cell+ @@ .
 2361: v3 2 cells + @@ .
 2362: v3 5 cells dump
 2363: @end example
 2364: 
 2365: @quotation Assignment
 2366: Write a definition @code{vsum ( addr u -- n )} that computes the sum of
 2367: @code{u} cells, with the first of these cells at @code{addr}, the next
 2368: one at @code{addr cell+} etc.
 2369: @end quotation
 2370: 
 2371: You can also reserve memory without creating a new word:
 2372: 
 2373: @example
 2374: here 10 cells allot .
 2375: here .
 2376: @end example
 2377: 
 2378: @code{Here} pushes the start address of the memory area.  You should
 2379: store it somewhere, or you will have a hard time finding the memory area
 2380: again.
 2381: 
 2382: @code{Allot} manages dictionary memory.  The dictionary memory contains
 2383: the system's data structures for words etc. on Gforth and most other
 2384: Forth systems.  It is managed like a stack: You can free the memory that
 2385: you have just @code{allot}ed with
 2386: 
 2387: @example
 2388: -10 cells allot
 2389: here .
 2390: @end example
 2391: 
 2392: Note that you cannot do this if you have created a new word in the
 2393: meantime (because then your @code{allot}ed memory is no longer on the
 2394: top of the dictionary ``stack'').
 2395: 
 2396: Alternatively, you can use @code{allocate} and @code{free} which allow
 2397: freeing memory in any order:
 2398: 
 2399: @example
 2400: 10 cells allocate throw .s
 2401: 20 cells allocate throw .s
 2402: swap
 2403: free throw
 2404: free throw
 2405: @end example
 2406: 
 2407: The @code{throw}s deal with errors (e.g., out of memory).
 2408: 
 2409: And there is also a
 2410: @uref{http://www.complang.tuwien.ac.at/forth/garbage-collection.zip,
 2411: garbage collector}, which eliminates the need to @code{free} memory
 2412: explicitly.
 2413: 
 2414: Reference: @ref{Memory}.
 2415: 
 2416: 
 2417: @node Characters and Strings Tutorial, Alignment Tutorial, Memory Tutorial, Tutorial
 2418: @section Characters and Strings
 2419: @cindex strings tutorial
 2420: @cindex characters tutorial
 2421: 
 2422: On the stack characters take up a cell, like numbers.  In memory they
 2423: have their own size (one 8-bit byte on most systems), and therefore
 2424: require their own words for memory access:
 2425: 
 2426: @example
 2427: create v4 
 2428:   104 c, 97 c, 108 c, 108 c, 111 c,
 2429: v4 4 chars + c@@ .
 2430: v4 5 chars dump
 2431: @end example
 2432: 
 2433: The preferred representation of strings on the stack is @code{addr
 2434: u-count}, where @code{addr} is the address of the first character and
 2435: @code{u-count} is the number of characters in the string.
 2436: 
 2437: @example
 2438: v4 5 type
 2439: @end example
 2440: 
 2441: You get a string constant with
 2442: 
 2443: @example
 2444: s" hello, world" .s
 2445: type
 2446: @end example
 2447: 
 2448: Make sure you have a space between @code{s"} and the string; @code{s"}
 2449: is a normal Forth word and must be delimited with white space (try what
 2450: happens when you remove the space).
 2451: 
 2452: However, this interpretive use of @code{s"} is quite restricted: the
 2453: string exists only until the next call of @code{s"} (some Forth systems
 2454: keep more than one of these strings, but usually they still have a
 2455: limited lifetime).
 2456: 
 2457: @example
 2458: s" hello," s" world" .s
 2459: type
 2460: type
 2461: @end example
 2462: 
 2463: You can also use @code{s"} in a definition, and the resulting
 2464: strings then live forever (well, for as long as the definition):
 2465: 
 2466: @example
 2467: : foo s" hello," s" world" ;
 2468: foo .s
 2469: type
 2470: type
 2471: @end example
 2472: 
 2473: @quotation Assignment
 2474: @code{Emit ( c -- )} types @code{c} as character (not a number).
 2475: Implement @code{type ( addr u -- )}.
 2476: @end quotation
 2477: 
 2478: Reference: @ref{Memory Blocks}.
 2479: 
 2480: 
 2481: @node Alignment Tutorial, Floating Point Tutorial, Characters and Strings Tutorial, Tutorial
 2482: @section Alignment
 2483: @cindex alignment tutorial
 2484: @cindex memory alignment tutorial
 2485: 
 2486: On many processors cells have to be aligned in memory, if you want to
 2487: access them with @code{@@} and @code{!} (and even if the processor does
 2488: not require alignment, access to aligned cells is faster).
 2489: 
 2490: @code{Create} aligns @code{here} (i.e., the place where the next
 2491: allocation will occur, and that the @code{create}d word points to).
 2492: Likewise, the memory produced by @code{allocate} starts at an aligned
 2493: address.  Adding a number of @code{cells} to an aligned address produces
 2494: another aligned address.
 2495: 
 2496: However, address arithmetic involving @code{char+} and @code{chars} can
 2497: create an address that is not cell-aligned.  @code{Aligned ( addr --
 2498: a-addr )} produces the next aligned address:
 2499: 
 2500: @example
 2501: v3 char+ aligned .s @@ .
 2502: v3 char+ .s @@ .
 2503: @end example
 2504: 
 2505: Similarly, @code{align} advances @code{here} to the next aligned
 2506: address:
 2507: 
 2508: @example
 2509: create v5 97 c,
 2510: here .
 2511: align here .
 2512: 1000 ,
 2513: @end example
 2514: 
 2515: Note that you should use aligned addresses even if your processor does
 2516: not require them, if you want your program to be portable.
 2517: 
 2518: Reference: @ref{Address arithmetic}.
 2519: 
 2520: @node Floating Point Tutorial, Files Tutorial, Alignment Tutorial, Tutorial
 2521: @section Floating Point
 2522: @cindex floating point tutorial
 2523: @cindex FP tutorial
 2524: 
 2525: Floating-point (FP) numbers and arithmetic in Forth works mostly as one
 2526: might expect, but there are a few things worth noting:
 2527: 
 2528: The first point is not specific to Forth, but so important and yet not
 2529: universally known that I mention it here: FP numbers are not reals.
 2530: Many properties (e.g., arithmetic laws) that reals have and that one
 2531: expects of all kinds of numbers do not hold for FP numbers.  If you
 2532: want to use FP computations, you should learn about their problems and
 2533: how to avoid them; a good starting point is @cite{David Goldberg,
 2534: @uref{http://docs.sun.com/source/806-3568/ncg_goldberg.html,What Every
 2535: Computer Scientist Should Know About Floating-Point Arithmetic}, ACM
 2536: Computing Surveys 23(1):5@minus{}48, March 1991}.
 2537: 
 2538: In Forth source code literal FP numbers need an exponent, e.g.,
 2539: @code{1e0}; this can also be written shorter as @code{1e},
 2540: @code{+1.0e+0}, and many variations in between.  The reason for this
 2541: is that, for historical reasons, Forth interprets a decimal point
 2542: alone (e.g., @code{1.}) as indicating a double-cell integer.  Another
 2543: requirement for literal FP numbers is that the current base is
 2544: decimal; with a hex base @code{1e} is interpreted as an integer.
 2545: 
 2546: Forth has a separate stack for FP numbers.@footnote{Theoretically, an
 2547: ANS Forth system may implement the FP stack on the data stack, but
 2548: virtually all systems implement a separate FP stack; and programming
 2549: in a way that accommodates all models is so cumbersome that nobody
 2550: does it.}  One advantage of this model is that cells are not in the
 2551: way when accessing FP values, and vice versa.  Forth has a set of
 2552: words for manipulating the FP stack: @code{fdup fswap fdrop fover
 2553: frot} and (non-standard) @code{fnip ftuck fpick}.
 2554: 
 2555: FP arithmetic words are prefixed with @code{F}.  There is the usual
 2556: set @code{f+ f- f* f/ f** fnegate} as well as a number of words for
 2557: other functions, e.g., @code{fsqrt fsin fln fmin}.  One word that you
 2558: might expect is @code{f=}; but @code{f=} is non-standard, because FP
 2559: computation results are usually inaccurate, so exact comparison is
 2560: usually a mistake, and one should use approximate comparison.
 2561: Unfortunately, @code{f~}, the standard word for that purpose, is not
 2562: well designed, so Gforth provides @code{f~abs} and @code{f~rel} as
 2563: well.
 2564: 
 2565: And of course there are words for accessing FP numbers in memory
 2566: (@code{f@@ f!}), and for address arithmetic (@code{floats float+
 2567: faligned}).  There are also variants of these words with an @code{sf}
 2568: and @code{df} prefix for accessing IEEE format single-precision and
 2569: double-precision numbers in memory; their main purpose is for
 2570: accessing external FP data (e.g., that has been read from or will be
 2571: written to a file).
 2572: 
 2573: Here is an example of a dot-product word and its use:
 2574: 
 2575: @example
 2576: : v* ( f_addr1 nstride1 f_addr2 nstride2 ucount -- r )
 2577:   >r swap 2swap swap 0e r> 0 ?DO
 2578:     dup f@@ over + 2swap dup f@@ f* f+ over + 2swap
 2579:   LOOP
 2580:   2drop 2drop ;
 2581: 
 2582: create v 1.23e f, 4.56e f, 7.89e f,
 2583: 
 2584: v 1 floats  v 1 floats  3  v* f.
 2585: @end example
 2586: 
 2587: @quotation Assignment
 2588: Write a program to solve a quadratic equation.  Then read @cite{Henry
 2589: G. Baker,
 2590: @uref{http://home.pipeline.com/~hbaker1/sigplannotices/sigcol05.ps.gz,You
 2591: Could Learn a Lot from a Quadratic}, ACM SIGPLAN Notices,
 2592: 33(1):30@minus{}39, January 1998}, and see if you can improve your
 2593: program.  Finally, find a test case where the original and the
 2594: improved version produce different results.
 2595: @end quotation
 2596: 
 2597: Reference: @ref{Floating Point}; @ref{Floating point stack};
 2598: @ref{Number Conversion}; @ref{Memory Access}; @ref{Address
 2599: arithmetic}.
 2600: 
 2601: @node Files Tutorial, Interpretation and Compilation Semantics and Immediacy Tutorial, Floating Point Tutorial, Tutorial
 2602: @section Files
 2603: @cindex files tutorial
 2604: 
 2605: This section gives a short introduction into how to use files inside
 2606: Forth. It's broken up into five easy steps:
 2607: 
 2608: @enumerate 1
 2609: @item Opened an ASCII text file for input
 2610: @item Opened a file for output
 2611: @item Read input file until string matched (or some other condition matched)
 2612: @item Wrote some lines from input ( modified or not) to output
 2613: @item Closed the files.
 2614: @end enumerate
 2615: 
 2616: Reference: @ref{General files}.
 2617: 
 2618: @subsection Open file for input
 2619: 
 2620: @example
 2621: s" foo.in"  r/o open-file throw Value fd-in
 2622: @end example
 2623: 
 2624: @subsection Create file for output
 2625: 
 2626: @example
 2627: s" foo.out" w/o create-file throw Value fd-out
 2628: @end example
 2629: 
 2630: The available file modes are r/o for read-only access, r/w for
 2631: read-write access, and w/o for write-only access. You could open both
 2632: files with r/w, too, if you like. All file words return error codes; for
 2633: most applications, it's best to pass there error codes with @code{throw}
 2634: to the outer error handler.
 2635: 
 2636: If you want words for opening and assigning, define them as follows:
 2637: 
 2638: @example
 2639: 0 Value fd-in
 2640: 0 Value fd-out
 2641: : open-input ( addr u -- )  r/o open-file throw to fd-in ;
 2642: : open-output ( addr u -- )  w/o create-file throw to fd-out ;
 2643: @end example
 2644: 
 2645: Usage example:
 2646: 
 2647: @example
 2648: s" foo.in" open-input
 2649: s" foo.out" open-output
 2650: @end example
 2651: 
 2652: @subsection Scan file for a particular line
 2653: 
 2654: @example
 2655: 256 Constant max-line
 2656: Create line-buffer  max-line 2 + allot
 2657: 
 2658: : scan-file ( addr u -- )
 2659:   begin
 2660:       line-buffer max-line fd-in read-line throw
 2661:   while
 2662:          >r 2dup line-buffer r> compare 0=
 2663:      until
 2664:   else
 2665:      drop
 2666:   then
 2667:   2drop ;
 2668: @end example
 2669: 
 2670: @code{read-line ( addr u1 fd -- u2 flag ior )} reads up to u1 bytes into
 2671: the buffer at addr, and returns the number of bytes read, a flag that is
 2672: false when the end of file is reached, and an error code.
 2673: 
 2674: @code{compare ( addr1 u1 addr2 u2 -- n )} compares two strings and
 2675: returns zero if both strings are equal. It returns a positive number if
 2676: the first string is lexically greater, a negative if the second string
 2677: is lexically greater.
 2678: 
 2679: We haven't seen this loop here; it has two exits. Since the @code{while}
 2680: exits with the number of bytes read on the stack, we have to clean up
 2681: that separately; that's after the @code{else}.
 2682: 
 2683: Usage example:
 2684: 
 2685: @example
 2686: s" The text I search is here" scan-file
 2687: @end example
 2688: 
 2689: @subsection Copy input to output
 2690: 
 2691: @example
 2692: : copy-file ( -- )
 2693:   begin
 2694:       line-buffer max-line fd-in read-line throw
 2695:   while
 2696:       line-buffer swap fd-out write-line throw
 2697:   repeat ;
 2698: @end example
 2699: @c !! does not handle long lines, no newline at end of file
 2700: 
 2701: @subsection Close files
 2702: 
 2703: @example
 2704: fd-in close-file throw
 2705: fd-out close-file throw
 2706: @end example
 2707: 
 2708: Likewise, you can put that into definitions, too:
 2709: 
 2710: @example
 2711: : close-input ( -- )  fd-in close-file throw ;
 2712: : close-output ( -- )  fd-out close-file throw ;
 2713: @end example
 2714: 
 2715: @quotation Assignment
 2716: How could you modify @code{copy-file} so that it copies until a second line is
 2717: matched? Can you write a program that extracts a section of a text file,
 2718: given the line that starts and the line that terminates that section?
 2719: @end quotation
 2720: 
 2721: @node Interpretation and Compilation Semantics and Immediacy Tutorial, Execution Tokens Tutorial, Files Tutorial, Tutorial
 2722: @section Interpretation and Compilation Semantics and Immediacy
 2723: @cindex semantics tutorial
 2724: @cindex interpretation semantics tutorial
 2725: @cindex compilation semantics tutorial
 2726: @cindex immediate, tutorial
 2727: 
 2728: When a word is compiled, it behaves differently from being interpreted.
 2729: E.g., consider @code{+}:
 2730: 
 2731: @example
 2732: 1 2 + .
 2733: : foo + ;
 2734: @end example
 2735: 
 2736: These two behaviours are known as compilation and interpretation
 2737: semantics.  For normal words (e.g., @code{+}), the compilation semantics
 2738: is to append the interpretation semantics to the currently defined word
 2739: (@code{foo} in the example above).  I.e., when @code{foo} is executed
 2740: later, the interpretation semantics of @code{+} (i.e., adding two
 2741: numbers) will be performed.
 2742: 
 2743: However, there are words with non-default compilation semantics, e.g.,
 2744: the control-flow words like @code{if}.  You can use @code{immediate} to
 2745: change the compilation semantics of the last defined word to be equal to
 2746: the interpretation semantics:
 2747: 
 2748: @example
 2749: : [FOO] ( -- )
 2750:  5 . ; immediate
 2751: 
 2752: [FOO]
 2753: : bar ( -- )
 2754:   [FOO] ;
 2755: bar
 2756: see bar
 2757: @end example
 2758: 
 2759: Two conventions to mark words with non-default compilation semantics are
 2760: names with brackets (more frequently used) and to write them all in
 2761: upper case (less frequently used).
 2762: 
 2763: In Gforth (and many other systems) you can also remove the
 2764: interpretation semantics with @code{compile-only} (the compilation
 2765: semantics is derived from the original interpretation semantics):
 2766: 
 2767: @example
 2768: : flip ( -- )
 2769:  6 . ; compile-only \ but not immediate
 2770: flip
 2771: 
 2772: : flop ( -- )
 2773:  flip ;
 2774: flop
 2775: @end example
 2776: 
 2777: In this example the interpretation semantics of @code{flop} is equal to
 2778: the original interpretation semantics of @code{flip}.
 2779: 
 2780: The text interpreter has two states: in interpret state, it performs the
 2781: interpretation semantics of words it encounters; in compile state, it
 2782: performs the compilation semantics of these words.
 2783: 
 2784: Among other things, @code{:} switches into compile state, and @code{;}
 2785: switches back to interpret state.  They contain the factors @code{]}
 2786: (switch to compile state) and @code{[} (switch to interpret state), that
 2787: do nothing but switch the state.
 2788: 
 2789: @example
 2790: : xxx ( -- )
 2791:   [ 5 . ]
 2792: ;
 2793: 
 2794: xxx
 2795: see xxx
 2796: @end example
 2797: 
 2798: These brackets are also the source of the naming convention mentioned
 2799: above.
 2800: 
 2801: Reference: @ref{Interpretation and Compilation Semantics}.
 2802: 
 2803: 
 2804: @node Execution Tokens Tutorial, Exceptions Tutorial, Interpretation and Compilation Semantics and Immediacy Tutorial, Tutorial
 2805: @section Execution Tokens
 2806: @cindex execution tokens tutorial
 2807: @cindex XT tutorial
 2808: 
 2809: @code{' word} gives you the execution token (XT) of a word.  The XT is a
 2810: cell representing the interpretation semantics of a word.  You can
 2811: execute this semantics with @code{execute}:
 2812: 
 2813: @example
 2814: ' + .s
 2815: 1 2 rot execute .
 2816: @end example
 2817: 
 2818: The XT is similar to a function pointer in C.  However, parameter
 2819: passing through the stack makes it a little more flexible:
 2820: 
 2821: @example
 2822: : map-array ( ... addr u xt -- ... )
 2823: \ executes xt ( ... x -- ... ) for every element of the array starting
 2824: \ at addr and containing u elements
 2825:   @{ xt @}
 2826:   cells over + swap ?do
 2827:     i @@ xt execute
 2828:   1 cells +loop ;
 2829: 
 2830: create a 3 , 4 , 2 , -1 , 4 ,
 2831: a 5 ' . map-array .s
 2832: 0 a 5 ' + map-array .
 2833: s" max-n" environment? drop .s
 2834: a 5 ' min map-array .
 2835: @end example
 2836: 
 2837: You can use map-array with the XTs of words that consume one element
 2838: more than they produce.  In theory you can also use it with other XTs,
 2839: but the stack effect then depends on the size of the array, which is
 2840: hard to understand.
 2841: 
 2842: Since XTs are cell-sized, you can store them in memory and manipulate
 2843: them on the stack like other cells.  You can also compile the XT into a
 2844: word with @code{compile,}:
 2845: 
 2846: @example
 2847: : foo1 ( n1 n2 -- n )
 2848:    [ ' + compile, ] ;
 2849: see foo
 2850: @end example
 2851: 
 2852: This is non-standard, because @code{compile,} has no compilation
 2853: semantics in the standard, but it works in good Forth systems.  For the
 2854: broken ones, use
 2855: 
 2856: @example
 2857: : [compile,] compile, ; immediate
 2858: 
 2859: : foo1 ( n1 n2 -- n )
 2860:    [ ' + ] [compile,] ;
 2861: see foo
 2862: @end example
 2863: 
 2864: @code{'} is a word with default compilation semantics; it parses the
 2865: next word when its interpretation semantics are executed, not during
 2866: compilation:
 2867: 
 2868: @example
 2869: : foo ( -- xt )
 2870:   ' ;
 2871: see foo
 2872: : bar ( ... "word" -- ... )
 2873:   ' execute ;
 2874: see bar
 2875: 1 2 bar + .
 2876: @end example
 2877: 
 2878: You often want to parse a word during compilation and compile its XT so
 2879: it will be pushed on the stack at run-time.  @code{[']} does this:
 2880: 
 2881: @example
 2882: : xt-+ ( -- xt )
 2883:   ['] + ;
 2884: see xt-+
 2885: 1 2 xt-+ execute .
 2886: @end example
 2887: 
 2888: Many programmers tend to see @code{'} and the word it parses as one
 2889: unit, and expect it to behave like @code{[']} when compiled, and are
 2890: confused by the actual behaviour.  If you are, just remember that the
 2891: Forth system just takes @code{'} as one unit and has no idea that it is
 2892: a parsing word (attempts to convenience programmers in this issue have
 2893: usually resulted in even worse pitfalls, see
 2894: @uref{http://www.complang.tuwien.ac.at/papers/ertl98.ps.gz,
 2895: @code{State}-smartness---Why it is evil and How to Exorcise it}).
 2896: 
 2897: Note that the state of the interpreter does not come into play when
 2898: creating and executing XTs.  I.e., even when you execute @code{'} in
 2899: compile state, it still gives you the interpretation semantics.  And
 2900: whatever that state is, @code{execute} performs the semantics
 2901: represented by the XT (i.e., for XTs produced with @code{'} the
 2902: interpretation semantics).
 2903: 
 2904: Reference: @ref{Tokens for Words}.
 2905: 
 2906: 
 2907: @node Exceptions Tutorial, Defining Words Tutorial, Execution Tokens Tutorial, Tutorial
 2908: @section Exceptions
 2909: @cindex exceptions tutorial
 2910: 
 2911: @code{throw ( n -- )} causes an exception unless n is zero.
 2912: 
 2913: @example
 2914: 100 throw .s
 2915: 0 throw .s
 2916: @end example
 2917: 
 2918: @code{catch ( ... xt -- ... n )} behaves similar to @code{execute}, but
 2919: it catches exceptions and pushes the number of the exception on the
 2920: stack (or 0, if the xt executed without exception).  If there was an
 2921: exception, the stacks have the same depth as when entering @code{catch}:
 2922: 
 2923: @example
 2924: .s
 2925: 3 0 ' / catch .s
 2926: 3 2 ' / catch .s
 2927: @end example
 2928: 
 2929: @quotation Assignment
 2930: Try the same with @code{execute} instead of @code{catch}.
 2931: @end quotation
 2932: 
 2933: @code{Throw} always jumps to the dynamically next enclosing
 2934: @code{catch}, even if it has to leave several call levels to achieve
 2935: this:
 2936: 
 2937: @example
 2938: : foo 100 throw ;
 2939: : foo1 foo ." after foo" ;
 2940: : bar ['] foo1 catch ;
 2941: bar .
 2942: @end example
 2943: 
 2944: It is often important to restore a value upon leaving a definition, even
 2945: if the definition is left through an exception.  You can ensure this
 2946: like this:
 2947: 
 2948: @example
 2949: : ...
 2950:    save-x
 2951:    ['] word-changing-x catch ( ... n )
 2952:    restore-x
 2953:    ( ... n ) throw ;
 2954: @end example
 2955: 
 2956: However, this is still not safe against, e.g., the user pressing
 2957: @kbd{Ctrl-C} when execution is between the @code{catch} and
 2958: @code{restore-x}.
 2959: 
 2960: Gforth provides an alternative exception handling syntax that is safe
 2961: against such cases: @code{try ... restore ... endtry}.  If the code
 2962: between @code{try} and @code{endtry} has an exception, the stack
 2963: depths are restored, the exception number is pushed on the stack, and
 2964: the execution continues right after @code{restore}.
 2965: 
 2966: The safer equivalent to the restoration code above is
 2967: 
 2968: @example
 2969: : ...
 2970:   save-x
 2971:   try
 2972:     word-changing-x 0
 2973:   restore
 2974:     restore-x
 2975:   endtry
 2976:   throw ;
 2977: @end example
 2978: 
 2979: Reference: @ref{Exception Handling}.
 2980: 
 2981: 
 2982: @node Defining Words Tutorial, Arrays and Records Tutorial, Exceptions Tutorial, Tutorial
 2983: @section Defining Words
 2984: @cindex defining words tutorial
 2985: @cindex does> tutorial
 2986: @cindex create...does> tutorial
 2987: 
 2988: @c before semantics?
 2989: 
 2990: @code{:}, @code{create}, and @code{variable} are definition words: They
 2991: define other words.  @code{Constant} is another definition word:
 2992: 
 2993: @example
 2994: 5 constant foo
 2995: foo .
 2996: @end example
 2997: 
 2998: You can also use the prefixes @code{2} (double-cell) and @code{f}
 2999: (floating point) with @code{variable} and @code{constant}.
 3000: 
 3001: You can also define your own defining words.  E.g.:
 3002: 
 3003: @example
 3004: : variable ( "name" -- )
 3005:   create 0 , ;
 3006: @end example
 3007: 
 3008: You can also define defining words that create words that do something
 3009: other than just producing their address:
 3010: 
 3011: @example
 3012: : constant ( n "name" -- )
 3013:   create ,
 3014: does> ( -- n )
 3015:   ( addr ) @@ ;
 3016: 
 3017: 5 constant foo
 3018: foo .
 3019: @end example
 3020: 
 3021: The definition of @code{constant} above ends at the @code{does>}; i.e.,
 3022: @code{does>} replaces @code{;}, but it also does something else: It
 3023: changes the last defined word such that it pushes the address of the
 3024: body of the word and then performs the code after the @code{does>}
 3025: whenever it is called.
 3026: 
 3027: In the example above, @code{constant} uses @code{,} to store 5 into the
 3028: body of @code{foo}.  When @code{foo} executes, it pushes the address of
 3029: the body onto the stack, then (in the code after the @code{does>})
 3030: fetches the 5 from there.
 3031: 
 3032: The stack comment near the @code{does>} reflects the stack effect of the
 3033: defined word, not the stack effect of the code after the @code{does>}
 3034: (the difference is that the code expects the address of the body that
 3035: the stack comment does not show).
 3036: 
 3037: You can use these definition words to do factoring in cases that involve
 3038: (other) definition words.  E.g., a field offset is always added to an
 3039: address.  Instead of defining
 3040: 
 3041: @example
 3042: 2 cells constant offset-field1
 3043: @end example
 3044: 
 3045: and using this like
 3046: 
 3047: @example
 3048: ( addr ) offset-field1 +
 3049: @end example
 3050: 
 3051: you can define a definition word
 3052: 
 3053: @example
 3054: : simple-field ( n "name" -- )
 3055:   create ,
 3056: does> ( n1 -- n1+n )
 3057:   ( addr ) @@ + ;
 3058: @end example
 3059: 
 3060: Definition and use of field offsets now look like this:
 3061: 
 3062: @example
 3063: 2 cells simple-field field1
 3064: create mystruct 4 cells allot
 3065: mystruct .s field1 .s drop
 3066: @end example
 3067: 
 3068: If you want to do something with the word without performing the code
 3069: after the @code{does>}, you can access the body of a @code{create}d word
 3070: with @code{>body ( xt -- addr )}:
 3071: 
 3072: @example
 3073: : value ( n "name" -- )
 3074:   create ,
 3075: does> ( -- n1 )
 3076:   @@ ;
 3077: : to ( n "name" -- )
 3078:   ' >body ! ;
 3079: 
 3080: 5 value foo
 3081: foo .
 3082: 7 to foo
 3083: foo .
 3084: @end example
 3085: 
 3086: @quotation Assignment
 3087: Define @code{defer ( "name" -- )}, which creates a word that stores an
 3088: XT (at the start the XT of @code{abort}), and upon execution
 3089: @code{execute}s the XT.  Define @code{is ( xt "name" -- )} that stores
 3090: @code{xt} into @code{name}, a word defined with @code{defer}.  Indirect
 3091: recursion is one application of @code{defer}.
 3092: @end quotation
 3093: 
 3094: Reference: @ref{User-defined Defining Words}.
 3095: 
 3096: 
 3097: @node Arrays and Records Tutorial, POSTPONE Tutorial, Defining Words Tutorial, Tutorial
 3098: @section Arrays and Records
 3099: @cindex arrays tutorial
 3100: @cindex records tutorial
 3101: @cindex structs tutorial
 3102: 
 3103: Forth has no standard words for defining data structures such as arrays
 3104: and records (structs in C terminology), but you can build them yourself
 3105: based on address arithmetic.  You can also define words for defining
 3106: arrays and records (@pxref{Defining Words Tutorial,, Defining Words}).
 3107: 
 3108: One of the first projects a Forth newcomer sets out upon when learning
 3109: about defining words is an array defining word (possibly for
 3110: n-dimensional arrays).  Go ahead and do it, I did it, too; you will
 3111: learn something from it.  However, don't be disappointed when you later
 3112: learn that you have little use for these words (inappropriate use would
 3113: be even worse).  I have not found a set of useful array words yet;
 3114: the needs are just too diverse, and named, global arrays (the result of
 3115: naive use of defining words) are often not flexible enough (e.g.,
 3116: consider how to pass them as parameters).  Another such project is a set
 3117: of words to help dealing with strings.
 3118: 
 3119: On the other hand, there is a useful set of record words, and it has
 3120: been defined in @file{compat/struct.fs}; these words are predefined in
 3121: Gforth.  They are explained in depth elsewhere in this manual (see
 3122: @pxref{Structures}).  The @code{simple-field} example above is
 3123: simplified variant of fields in this package.
 3124: 
 3125: 
 3126: @node POSTPONE Tutorial, Literal Tutorial, Arrays and Records Tutorial, Tutorial
 3127: @section @code{POSTPONE}
 3128: @cindex postpone tutorial
 3129: 
 3130: You can compile the compilation semantics (instead of compiling the
 3131: interpretation semantics) of a word with @code{POSTPONE}:
 3132: 
 3133: @example
 3134: : MY-+ ( Compilation: -- ; Run-time of compiled code: n1 n2 -- n )
 3135:  POSTPONE + ; immediate
 3136: : foo ( n1 n2 -- n )
 3137:  MY-+ ;
 3138: 1 2 foo .
 3139: see foo
 3140: @end example
 3141: 
 3142: During the definition of @code{foo} the text interpreter performs the
 3143: compilation semantics of @code{MY-+}, which performs the compilation
 3144: semantics of @code{+}, i.e., it compiles @code{+} into @code{foo}.
 3145: 
 3146: This example also displays separate stack comments for the compilation
 3147: semantics and for the stack effect of the compiled code.  For words with
 3148: default compilation semantics these stack effects are usually not
 3149: displayed; the stack effect of the compilation semantics is always
 3150: @code{( -- )} for these words, the stack effect for the compiled code is
 3151: the stack effect of the interpretation semantics.
 3152: 
 3153: Note that the state of the interpreter does not come into play when
 3154: performing the compilation semantics in this way.  You can also perform
 3155: it interpretively, e.g.:
 3156: 
 3157: @example
 3158: : foo2 ( n1 n2 -- n )
 3159:  [ MY-+ ] ;
 3160: 1 2 foo .
 3161: see foo
 3162: @end example
 3163: 
 3164: However, there are some broken Forth systems where this does not always
 3165: work, and therefore this practice was been declared non-standard in
 3166: 1999.
 3167: @c !! repair.fs
 3168: 
 3169: Here is another example for using @code{POSTPONE}:
 3170: 
 3171: @example
 3172: : MY-- ( Compilation: -- ; Run-time of compiled code: n1 n2 -- n )
 3173:  POSTPONE negate POSTPONE + ; immediate compile-only
 3174: : bar ( n1 n2 -- n )
 3175:   MY-- ;
 3176: 2 1 bar .
 3177: see bar
 3178: @end example
 3179: 
 3180: You can define @code{ENDIF} in this way:
 3181: 
 3182: @example
 3183: : ENDIF ( Compilation: orig -- )
 3184:   POSTPONE then ; immediate
 3185: @end example
 3186: 
 3187: @quotation Assignment
 3188: Write @code{MY-2DUP} that has compilation semantics equivalent to
 3189: @code{2dup}, but compiles @code{over over}.
 3190: @end quotation
 3191: 
 3192: @c !! @xref{Macros} for reference
 3193: 
 3194: 
 3195: @node Literal Tutorial, Advanced macros Tutorial, POSTPONE Tutorial, Tutorial
 3196: @section @code{Literal}
 3197: @cindex literal tutorial
 3198: 
 3199: You cannot @code{POSTPONE} numbers:
 3200: 
 3201: @example
 3202: : [FOO] POSTPONE 500 ; immediate
 3203: @end example
 3204: 
 3205: Instead, you can use @code{LITERAL (compilation: n --; run-time: -- n )}:
 3206: 
 3207: @example
 3208: : [FOO] ( compilation: --; run-time: -- n )
 3209:   500 POSTPONE literal ; immediate
 3210: 
 3211: : flip [FOO] ;
 3212: flip .
 3213: see flip
 3214: @end example
 3215: 
 3216: @code{LITERAL} consumes a number at compile-time (when it's compilation
 3217: semantics are executed) and pushes it at run-time (when the code it
 3218: compiled is executed).  A frequent use of @code{LITERAL} is to compile a
 3219: number computed at compile time into the current word:
 3220: 
 3221: @example
 3222: : bar ( -- n )
 3223:   [ 2 2 + ] literal ;
 3224: see bar
 3225: @end example
 3226: 
 3227: @quotation Assignment
 3228: Write @code{]L} which allows writing the example above as @code{: bar (
 3229: -- n ) [ 2 2 + ]L ;}
 3230: @end quotation
 3231: 
 3232: @c !! @xref{Macros} for reference
 3233: 
 3234: 
 3235: @node Advanced macros Tutorial, Compilation Tokens Tutorial, Literal Tutorial, Tutorial
 3236: @section Advanced macros
 3237: @cindex macros, advanced tutorial
 3238: @cindex run-time code generation, tutorial
 3239: 
 3240: Reconsider @code{map-array} from @ref{Execution Tokens Tutorial,,
 3241: Execution Tokens}.  It frequently performs @code{execute}, a relatively
 3242: expensive operation in some Forth implementations.  You can use
 3243: @code{compile,} and @code{POSTPONE} to eliminate these @code{execute}s
 3244: and produce a word that contains the word to be performed directly:
 3245: 
 3246: @c use ]] ... [[
 3247: @example
 3248: : compile-map-array ( compilation: xt -- ; run-time: ... addr u -- ... )
 3249: \ at run-time, execute xt ( ... x -- ... ) for each element of the
 3250: \ array beginning at addr and containing u elements
 3251:   @{ xt @}
 3252:   POSTPONE cells POSTPONE over POSTPONE + POSTPONE swap POSTPONE ?do
 3253:     POSTPONE i POSTPONE @@ xt compile,
 3254:   1 cells POSTPONE literal POSTPONE +loop ;
 3255: 
 3256: : sum-array ( addr u -- n )
 3257:  0 rot rot [ ' + compile-map-array ] ;
 3258: see sum-array
 3259: a 5 sum-array .
 3260: @end example
 3261: 
 3262: You can use the full power of Forth for generating the code; here's an
 3263: example where the code is generated in a loop:
 3264: 
 3265: @example
 3266: : compile-vmul-step ( compilation: n --; run-time: n1 addr1 -- n2 addr2 )
 3267: \ n2=n1+(addr1)*n, addr2=addr1+cell
 3268:   POSTPONE tuck POSTPONE @@
 3269:   POSTPONE literal POSTPONE * POSTPONE +
 3270:   POSTPONE swap POSTPONE cell+ ;
 3271: 
 3272: : compile-vmul ( compilation: addr1 u -- ; run-time: addr2 -- n )
 3273: \ n=v1*v2 (inner product), where the v_i are represented as addr_i u
 3274:   0 postpone literal postpone swap
 3275:   [ ' compile-vmul-step compile-map-array ]
 3276:   postpone drop ;
 3277: see compile-vmul
 3278: 
 3279: : a-vmul ( addr -- n )
 3280: \ n=a*v, where v is a vector that's as long as a and starts at addr
 3281:  [ a 5 compile-vmul ] ;
 3282: see a-vmul
 3283: a a-vmul .
 3284: @end example
 3285: 
 3286: This example uses @code{compile-map-array} to show off, but you could
 3287: also use @code{map-array} instead (try it now!).
 3288: 
 3289: You can use this technique for efficient multiplication of large
 3290: matrices.  In matrix multiplication, you multiply every line of one
 3291: matrix with every column of the other matrix.  You can generate the code
 3292: for one line once, and use it for every column.  The only downside of
 3293: this technique is that it is cumbersome to recover the memory consumed
 3294: by the generated code when you are done (and in more complicated cases
 3295: it is not possible portably).
 3296: 
 3297: @c !! @xref{Macros} for reference
 3298: 
 3299: 
 3300: @node Compilation Tokens Tutorial, Wordlists and Search Order Tutorial, Advanced macros Tutorial, Tutorial
 3301: @section Compilation Tokens
 3302: @cindex compilation tokens, tutorial
 3303: @cindex CT, tutorial
 3304: 
 3305: This section is Gforth-specific.  You can skip it.
 3306: 
 3307: @code{' word compile,} compiles the interpretation semantics.  For words
 3308: with default compilation semantics this is the same as performing the
 3309: compilation semantics.  To represent the compilation semantics of other
 3310: words (e.g., words like @code{if} that have no interpretation
 3311: semantics), Gforth has the concept of a compilation token (CT,
 3312: consisting of two cells), and words @code{comp'} and @code{[comp']}.
 3313: You can perform the compilation semantics represented by a CT with
 3314: @code{execute}:
 3315: 
 3316: @example
 3317: : foo2 ( n1 n2 -- n )
 3318:    [ comp' + execute ] ;
 3319: see foo
 3320: @end example
 3321: 
 3322: You can compile the compilation semantics represented by a CT with
 3323: @code{postpone,}:
 3324: 
 3325: @example
 3326: : foo3 ( -- )
 3327:   [ comp' + postpone, ] ;
 3328: see foo3
 3329: @end example
 3330: 
 3331: @code{[ comp' word postpone, ]} is equivalent to @code{POSTPONE word}.
 3332: @code{comp'} is particularly useful for words that have no
 3333: interpretation semantics:
 3334: 
 3335: @example
 3336: ' if
 3337: comp' if .s 2drop
 3338: @end example
 3339: 
 3340: Reference: @ref{Tokens for Words}.
 3341: 
 3342: 
 3343: @node Wordlists and Search Order Tutorial,  , Compilation Tokens Tutorial, Tutorial
 3344: @section Wordlists and Search Order
 3345: @cindex wordlists tutorial
 3346: @cindex search order, tutorial
 3347: 
 3348: The dictionary is not just a memory area that allows you to allocate
 3349: memory with @code{allot}, it also contains the Forth words, arranged in
 3350: several wordlists.  When searching for a word in a wordlist,
 3351: conceptually you start searching at the youngest and proceed towards
 3352: older words (in reality most systems nowadays use hash-tables); i.e., if
 3353: you define a word with the same name as an older word, the new word
 3354: shadows the older word.
 3355: 
 3356: Which wordlists are searched in which order is determined by the search
 3357: order.  You can display the search order with @code{order}.  It displays
 3358: first the search order, starting with the wordlist searched first, then
 3359: it displays the wordlist that will contain newly defined words.
 3360: 
 3361: You can create a new, empty wordlist with @code{wordlist ( -- wid )}:
 3362: 
 3363: @example
 3364: wordlist constant mywords
 3365: @end example
 3366: 
 3367: @code{Set-current ( wid -- )} sets the wordlist that will contain newly
 3368: defined words (the @emph{current} wordlist):
 3369: 
 3370: @example
 3371: mywords set-current
 3372: order
 3373: @end example
 3374: 
 3375: Gforth does not display a name for the wordlist in @code{mywords}
 3376: because this wordlist was created anonymously with @code{wordlist}.
 3377: 
 3378: You can get the current wordlist with @code{get-current ( -- wid)}.  If
 3379: you want to put something into a specific wordlist without overall
 3380: effect on the current wordlist, this typically looks like this:
 3381: 
 3382: @example
 3383: get-current mywords set-current ( wid )
 3384: create someword
 3385: ( wid ) set-current
 3386: @end example
 3387: 
 3388: You can write the search order with @code{set-order ( wid1 .. widn n --
 3389: )} and read it with @code{get-order ( -- wid1 .. widn n )}.  The first
 3390: searched wordlist is topmost.
 3391: 
 3392: @example
 3393: get-order mywords swap 1+ set-order
 3394: order
 3395: @end example
 3396: 
 3397: Yes, the order of wordlists in the output of @code{order} is reversed
 3398: from stack comments and the output of @code{.s} and thus unintuitive.
 3399: 
 3400: @quotation Assignment
 3401: Define @code{>order ( wid -- )} with adds @code{wid} as first searched
 3402: wordlist to the search order.  Define @code{previous ( -- )}, which
 3403: removes the first searched wordlist from the search order.  Experiment
 3404: with boundary conditions (you will see some crashes or situations that
 3405: are hard or impossible to leave).
 3406: @end quotation
 3407: 
 3408: The search order is a powerful foundation for providing features similar
 3409: to Modula-2 modules and C++ namespaces.  However, trying to modularize
 3410: programs in this way has disadvantages for debugging and reuse/factoring
 3411: that overcome the advantages in my experience (I don't do huge projects,
 3412: though).  These disadvantages are not so clear in other
 3413: languages/programming environments, because these languages are not so
 3414: strong in debugging and reuse.
 3415: 
 3416: @c !! example
 3417: 
 3418: Reference: @ref{Word Lists}.
 3419: 
 3420: @c ******************************************************************
 3421: @node Introduction, Words, Tutorial, Top
 3422: @comment node-name,     next,           previous, up
 3423: @chapter An Introduction to ANS Forth
 3424: @cindex Forth - an introduction
 3425: 
 3426: The difference of this chapter from the Tutorial (@pxref{Tutorial}) is
 3427: that it is slower-paced in its examples, but uses them to dive deep into
 3428: explaining Forth internals (not covered by the Tutorial).  Apart from
 3429: that, this chapter covers far less material.  It is suitable for reading
 3430: without using a computer.
 3431: 
 3432: The primary purpose of this manual is to document Gforth. However, since
 3433: Forth is not a widely-known language and there is a lack of up-to-date
 3434: teaching material, it seems worthwhile to provide some introductory
 3435: material.  For other sources of Forth-related
 3436: information, see @ref{Forth-related information}.
 3437: 
 3438: The examples in this section should work on any ANS Forth; the
 3439: output shown was produced using Gforth. Each example attempts to
 3440: reproduce the exact output that Gforth produces. If you try out the
 3441: examples (and you should), what you should type is shown @kbd{like this}
 3442: and Gforth's response is shown @code{like this}. The single exception is
 3443: that, where the example shows @key{RET} it means that you should
 3444: press the ``carriage return'' key. Unfortunately, some output formats for
 3445: this manual cannot show the difference between @kbd{this} and
 3446: @code{this} which will make trying out the examples harder (but not
 3447: impossible).
 3448: 
 3449: Forth is an unusual language. It provides an interactive development
 3450: environment which includes both an interpreter and compiler. Forth
 3451: programming style encourages you to break a problem down into many
 3452: @cindex factoring
 3453: small fragments (@dfn{factoring}), and then to develop and test each
 3454: fragment interactively. Forth advocates assert that breaking the
 3455: edit-compile-test cycle used by conventional programming languages can
 3456: lead to great productivity improvements.
 3457: 
 3458: @menu
 3459: * Introducing the Text Interpreter::  
 3460: * Stacks and Postfix notation::  
 3461: * Your first definition::       
 3462: * How does that work?::         
 3463: * Forth is written in Forth::   
 3464: * Review - elements of a Forth system::  
 3465: * Where to go next::            
 3466: * Exercises::                   
 3467: @end menu
 3468: 
 3469: @comment ----------------------------------------------
 3470: @node Introducing the Text Interpreter, Stacks and Postfix notation, Introduction, Introduction
 3471: @section Introducing the Text Interpreter
 3472: @cindex text interpreter
 3473: @cindex outer interpreter
 3474: 
 3475: @c IMO this is too detailed and the pace is too slow for
 3476: @c an introduction.  If you know German, take a look at
 3477: @c http://www.complang.tuwien.ac.at/anton/lvas/skriptum-stack.html 
 3478: @c to see how I do it - anton 
 3479: 
 3480: @c nac-> Where I have accepted your comments 100% and modified the text
 3481: @c accordingly, I have deleted your comments. Elsewhere I have added a
 3482: @c response like this to attempt to rationalise what I have done. Of
 3483: @c course, this is a very clumsy mechanism for something that would be
 3484: @c done far more efficiently over a beer. Please delete any dialogue
 3485: @c you consider closed.
 3486: 
 3487: When you invoke the Forth image, you will see a startup banner printed
 3488: and nothing else (if you have Gforth installed on your system, try
 3489: invoking it now, by typing @kbd{gforth@key{RET}}). Forth is now running
 3490: its command line interpreter, which is called the @dfn{Text Interpreter}
 3491: (also known as the @dfn{Outer Interpreter}).  (You will learn a lot
 3492: about the text interpreter as you read through this chapter, for more
 3493: detail @pxref{The Text Interpreter}).
 3494: 
 3495: Although it's not obvious, Forth is actually waiting for your
 3496: input. Type a number and press the @key{RET} key:
 3497: 
 3498: @example
 3499: @kbd{45@key{RET}}  ok
 3500: @end example
 3501: 
 3502: Rather than give you a prompt to invite you to input something, the text
 3503: interpreter prints a status message @i{after} it has processed a line
 3504: of input. The status message in this case (``@code{ ok}'' followed by
 3505: carriage-return) indicates that the text interpreter was able to process
 3506: all of your input successfully. Now type something illegal:
 3507: 
 3508: @example
 3509: @kbd{qwer341@key{RET}}
 3510: *the terminal*:2: Undefined word
 3511: >>>qwer341<<<
 3512: Backtrace:
 3513: $2A95B42A20 throw 
 3514: $2A95B57FB8 no.extensions 
 3515: @end example
 3516: 
 3517: The exact text, other than the ``Undefined word'' may differ slightly
 3518: on your system, but the effect is the same; when the text interpreter
 3519: detects an error, it discards any remaining text on a line, resets
 3520: certain internal state and prints an error message. For a detailed
 3521: description of error messages see @ref{Error messages}.
 3522: 
 3523: The text interpreter waits for you to press carriage-return, and then
 3524: processes your input line. Starting at the beginning of the line, it
 3525: breaks the line into groups of characters separated by spaces. For each
 3526: group of characters in turn, it makes two attempts to do something:
 3527: 
 3528: @itemize @bullet
 3529: @item
 3530: @cindex name dictionary
 3531: It tries to treat it as a command. It does this by searching a @dfn{name
 3532: dictionary}. If the group of characters matches an entry in the name
 3533: dictionary, the name dictionary provides the text interpreter with
 3534: information that allows the text interpreter perform some actions. In
 3535: Forth jargon, we say that the group
 3536: @cindex word
 3537: @cindex definition
 3538: @cindex execution token
 3539: @cindex xt
 3540: of characters names a @dfn{word}, that the dictionary search returns an
 3541: @dfn{execution token (xt)} corresponding to the @dfn{definition} of the
 3542: word, and that the text interpreter executes the xt. Often, the terms
 3543: @dfn{word} and @dfn{definition} are used interchangeably.
 3544: @item
 3545: If the text interpreter fails to find a match in the name dictionary, it
 3546: tries to treat the group of characters as a number in the current number
 3547: base (when you start up Forth, the current number base is base 10). If
 3548: the group of characters legitimately represents a number, the text
 3549: interpreter pushes the number onto a stack (we'll learn more about that
 3550: in the next section).
 3551: @end itemize
 3552: 
 3553: If the text interpreter is unable to do either of these things with any
 3554: group of characters, it discards the group of characters and the rest of
 3555: the line, then prints an error message. If the text interpreter reaches
 3556: the end of the line without error, it prints the status message ``@code{ ok}''
 3557: followed by carriage-return.
 3558: 
 3559: This is the simplest command we can give to the text interpreter:
 3560: 
 3561: @example
 3562: @key{RET}  ok
 3563: @end example
 3564: 
 3565: The text interpreter did everything we asked it to do (nothing) without
 3566: an error, so it said that everything is ``@code{ ok}''. Try a slightly longer
 3567: command:
 3568: 
 3569: @example
 3570: @kbd{12 dup fred dup@key{RET}}
 3571: *the terminal*:3: Undefined word
 3572: 12 dup >>>fred<<< dup
 3573: Backtrace:
 3574: $2A95B42A20 throw 
 3575: $2A95B57FB8 no.extensions 
 3576: @end example
 3577: 
 3578: When you press the carriage-return key, the text interpreter starts to
 3579: work its way along the line:
 3580: 
 3581: @itemize @bullet
 3582: @item
 3583: When it gets to the space after the @code{2}, it takes the group of
 3584: characters @code{12} and looks them up in the name
 3585: dictionary@footnote{We can't tell if it found them or not, but assume
 3586: for now that it did not}. There is no match for this group of characters
 3587: in the name dictionary, so it tries to treat them as a number. It is
 3588: able to do this successfully, so it puts the number, 12, ``on the stack''
 3589: (whatever that means).
 3590: @item
 3591: The text interpreter resumes scanning the line and gets the next group
 3592: of characters, @code{dup}. It looks it up in the name dictionary and
 3593: (you'll have to take my word for this) finds it, and executes the word
 3594: @code{dup} (whatever that means).
 3595: @item
 3596: Once again, the text interpreter resumes scanning the line and gets the
 3597: group of characters @code{fred}. It looks them up in the name
 3598: dictionary, but can't find them. It tries to treat them as a number, but
 3599: they don't represent any legal number.
 3600: @end itemize
 3601: 
 3602: At this point, the text interpreter gives up and prints an error
 3603: message. The error message shows exactly how far the text interpreter
 3604: got in processing the line. In particular, it shows that the text
 3605: interpreter made no attempt to do anything with the final character
 3606: group, @code{dup}, even though we have good reason to believe that the
 3607: text interpreter would have no problem looking that word up and
 3608: executing it a second time.
 3609: 
 3610: 
 3611: @comment ----------------------------------------------
 3612: @node Stacks and Postfix notation, Your first definition, Introducing the Text Interpreter, Introduction
 3613: @section Stacks, postfix notation and parameter passing
 3614: @cindex text interpreter
 3615: @cindex outer interpreter
 3616: 
 3617: In procedural programming languages (like C and Pascal), the
 3618: building-block of programs is the @dfn{function} or @dfn{procedure}. These
 3619: functions or procedures are called with @dfn{explicit parameters}. For
 3620: example, in C we might write:
 3621: 
 3622: @example
 3623: total = total + new_volume(length,height,depth);
 3624: @end example
 3625: 
 3626: @noindent
 3627: where new_volume is a function-call to another piece of code, and total,
 3628: length, height and depth are all variables. length, height and depth are
 3629: parameters to the function-call.
 3630: 
 3631: In Forth, the equivalent of the function or procedure is the
 3632: @dfn{definition} and parameters are implicitly passed between
 3633: definitions using a shared stack that is visible to the
 3634: programmer. Although Forth does support variables, the existence of the
 3635: stack means that they are used far less often than in most other
 3636: programming languages. When the text interpreter encounters a number, it
 3637: will place (@dfn{push}) it on the stack. There are several stacks (the
 3638: actual number is implementation-dependent ...) and the particular stack
 3639: used for any operation is implied unambiguously by the operation being
 3640: performed. The stack used for all integer operations is called the @dfn{data
 3641: stack} and, since this is the stack used most commonly, references to
 3642: ``the data stack'' are often abbreviated to ``the stack''.
 3643: 
 3644: The stacks have a last-in, first-out (LIFO) organisation. If you type:
 3645: 
 3646: @example
 3647: @kbd{1 2 3@key{RET}}  ok
 3648: @end example
 3649: 
 3650: Then this instructs the text interpreter to placed three numbers on the
 3651: (data) stack. An analogy for the behaviour of the stack is to take a
 3652: pack of playing cards and deal out the ace (1), 2 and 3 into a pile on
 3653: the table. The 3 was the last card onto the pile (``last-in'') and if
 3654: you take a card off the pile then, unless you're prepared to fiddle a
 3655: bit, the card that you take off will be the 3 (``first-out''). The
 3656: number that will be first-out of the stack is called the @dfn{top of
 3657: stack}, which
 3658: @cindex TOS definition
 3659: is often abbreviated to @dfn{TOS}.
 3660: 
 3661: To understand how parameters are passed in Forth, consider the
 3662: behaviour of the definition @code{+} (pronounced ``plus''). You will not
 3663: be surprised to learn that this definition performs addition. More
 3664: precisely, it adds two number together and produces a result. Where does
 3665: it get the two numbers from? It takes the top two numbers off the
 3666: stack. Where does it place the result? On the stack. You can act-out the
 3667: behaviour of @code{+} with your playing cards like this:
 3668: 
 3669: @itemize @bullet
 3670: @item
 3671: Pick up two cards from the stack on the table
 3672: @item
 3673: Stare at them intently and ask yourself ``what @i{is} the sum of these two
 3674: numbers''
 3675: @item
 3676: Decide that the answer is 5
 3677: @item
 3678: Shuffle the two cards back into the pack and find a 5
 3679: @item
 3680: Put a 5 on the remaining ace that's on the table.
 3681: @end itemize
 3682: 
 3683: If you don't have a pack of cards handy but you do have Forth running,
 3684: you can use the definition @code{.s} to show the current state of the stack,
 3685: without affecting the stack. Type:
 3686: 
 3687: @example
 3688: @kbd{clearstacks 1 2 3@key{RET}} ok
 3689: @kbd{.s@key{RET}} <3> 1 2 3  ok
 3690: @end example
 3691: 
 3692: The text interpreter looks up the word @code{clearstacks} and executes
 3693: it; it tidies up the stacks and removes any entries that may have been
 3694: left on it by earlier examples. The text interpreter pushes each of the
 3695: three numbers in turn onto the stack. Finally, the text interpreter
 3696: looks up the word @code{.s} and executes it. The effect of executing
 3697: @code{.s} is to print the ``<3>'' (the total number of items on the stack)
 3698: followed by a list of all the items on the stack; the item on the far
 3699: right-hand side is the TOS.
 3700: 
 3701: You can now type:
 3702: 
 3703: @example
 3704: @kbd{+ .s@key{RET}} <2> 1 5  ok
 3705: @end example
 3706: 
 3707: @noindent
 3708: which is correct; there are now 2 items on the stack and the result of
 3709: the addition is 5.
 3710: 
 3711: If you're playing with cards, try doing a second addition: pick up the
 3712: two cards, work out that their sum is 6, shuffle them into the pack,
 3713: look for a 6 and place that on the table. You now have just one item on
 3714: the stack. What happens if you try to do a third addition? Pick up the
 3715: first card, pick up the second card -- ah! There is no second card. This
 3716: is called a @dfn{stack underflow} and consitutes an error. If you try to
 3717: do the same thing with Forth it often reports an error (probably a Stack
 3718: Underflow or an Invalid Memory Address error).
 3719: 
 3720: The opposite situation to a stack underflow is a @dfn{stack overflow},
 3721: which simply accepts that there is a finite amount of storage space
 3722: reserved for the stack. To stretch the playing card analogy, if you had
 3723: enough packs of cards and you piled the cards up on the table, you would
 3724: eventually be unable to add another card; you'd hit the ceiling. Gforth
 3725: allows you to set the maximum size of the stacks. In general, the only
 3726: time that you will get a stack overflow is because a definition has a
 3727: bug in it and is generating data on the stack uncontrollably.
 3728: 
 3729: There's one final use for the playing card analogy. If you model your
 3730: stack using a pack of playing cards, the maximum number of items on
 3731: your stack will be 52 (I assume you didn't use the Joker). The maximum
 3732: @i{value} of any item on the stack is 13 (the King). In fact, the only
 3733: possible numbers are positive integer numbers 1 through 13; you can't
 3734: have (for example) 0 or 27 or 3.52 or -2. If you change the way you
 3735: think about some of the cards, you can accommodate different
 3736: numbers. For example, you could think of the Jack as representing 0,
 3737: the Queen as representing -1 and the King as representing -2. Your
 3738: @i{range} remains unchanged (you can still only represent a total of 13
 3739: numbers) but the numbers that you can represent are -2 through 10.
 3740: 
 3741: In that analogy, the limit was the amount of information that a single
 3742: stack entry could hold, and Forth has a similar limit. In Forth, the
 3743: size of a stack entry is called a @dfn{cell}. The actual size of a cell is
 3744: implementation dependent and affects the maximum value that a stack
 3745: entry can hold. A Standard Forth provides a cell size of at least
 3746: 16-bits, and most desktop systems use a cell size of 32-bits.
 3747: 
 3748: Forth does not do any type checking for you, so you are free to
 3749: manipulate and combine stack items in any way you wish. A convenient way
 3750: of treating stack items is as 2's complement signed integers, and that
 3751: is what Standard words like @code{+} do. Therefore you can type:
 3752: 
 3753: @example
 3754: @kbd{-5 12 + .s@key{RET}} <1> 7  ok
 3755: @end example
 3756: 
 3757: If you use numbers and definitions like @code{+} in order to turn Forth
 3758: into a great big pocket calculator, you will realise that it's rather
 3759: different from a normal calculator. Rather than typing 2 + 3 = you had
 3760: to type 2 3 + (ignore the fact that you had to use @code{.s} to see the
 3761: result). The terminology used to describe this difference is to say that
 3762: your calculator uses @dfn{Infix Notation} (parameters and operators are
 3763: mixed) whilst Forth uses @dfn{Postfix Notation} (parameters and
 3764: operators are separate), also called @dfn{Reverse Polish Notation}.
 3765: 
 3766: Whilst postfix notation might look confusing to begin with, it has
 3767: several important advantages:
 3768: 
 3769: @itemize @bullet
 3770: @item
 3771: it is unambiguous
 3772: @item
 3773: it is more concise
 3774: @item
 3775: it fits naturally with a stack-based system
 3776: @end itemize
 3777: 
 3778: To examine these claims in more detail, consider these sums:
 3779: 
 3780: @example
 3781: 6 + 5 * 4 =
 3782: 4 * 5 + 6 =
 3783: @end example
 3784: 
 3785: If you're just learning maths or your maths is very rusty, you will
 3786: probably come up with the answer 44 for the first and 26 for the
 3787: second. If you are a bit of a whizz at maths you will remember the
 3788: @i{convention} that multiplication takes precendence over addition, and
 3789: you'd come up with the answer 26 both times. To explain the answer 26
 3790: to someone who got the answer 44, you'd probably rewrite the first sum
 3791: like this:
 3792: 
 3793: @example
 3794: 6 + (5 * 4) =
 3795: @end example
 3796: 
 3797: If what you really wanted was to perform the addition before the
 3798: multiplication, you would have to use parentheses to force it.
 3799: 
 3800: If you did the first two sums on a pocket calculator you would probably
 3801: get the right answers, unless you were very cautious and entered them using
 3802: these keystroke sequences:
 3803: 
 3804: 6 + 5 = * 4 =
 3805: 4 * 5 = + 6 =
 3806: 
 3807: Postfix notation is unambiguous because the order that the operators
 3808: are applied is always explicit; that also means that parentheses are
 3809: never required. The operators are @i{active} (the act of quoting the
 3810: operator makes the operation occur) which removes the need for ``=''.
 3811: 
 3812: The sum 6 + 5 * 4 can be written (in postfix notation) in two
 3813: equivalent ways:
 3814: 
 3815: @example
 3816: 6 5 4 * +      or:
 3817: 5 4 * 6 +
 3818: @end example
 3819: 
 3820: An important thing that you should notice about this notation is that
 3821: the @i{order} of the numbers does not change; if you want to subtract
 3822: 2 from 10 you type @code{10 2 -}.
 3823: 
 3824: The reason that Forth uses postfix notation is very simple to explain: it
 3825: makes the implementation extremely simple, and it follows naturally from
 3826: using the stack as a mechanism for passing parameters. Another way of
 3827: thinking about this is to realise that all Forth definitions are
 3828: @i{active}; they execute as they are encountered by the text
 3829: interpreter. The result of this is that the syntax of Forth is trivially
 3830: simple.
 3831: 
 3832: 
 3833: 
 3834: @comment ----------------------------------------------
 3835: @node Your first definition, How does that work?, Stacks and Postfix notation, Introduction
 3836: @section Your first Forth definition
 3837: @cindex first definition
 3838: 
 3839: Until now, the examples we've seen have been trivial; we've just been
 3840: using Forth as a bigger-than-pocket calculator. Also, each calculation
 3841: we've shown has been a ``one-off'' -- to repeat it we'd need to type it in
 3842: again@footnote{That's not quite true. If you press the up-arrow key on
 3843: your keyboard you should be able to scroll back to any earlier command,
 3844: edit it and re-enter it.} In this section we'll see how to add new
 3845: words to Forth's vocabulary.
 3846: 
 3847: The easiest way to create a new word is to use a @dfn{colon
 3848: definition}. We'll define a few and try them out before worrying too
 3849: much about how they work. Try typing in these examples; be careful to
 3850: copy the spaces accurately:
 3851: 
 3852: @example
 3853: : add-two 2 + . ;
 3854: : greet ." Hello and welcome" ;
 3855: : demo 5 add-two ;
 3856: @end example
 3857: 
 3858: @noindent
 3859: Now try them out:
 3860: 
 3861: @example
 3862: @kbd{greet@key{RET}} Hello and welcome  ok
 3863: @kbd{greet greet@key{RET}} Hello and welcomeHello and welcome  ok
 3864: @kbd{4 add-two@key{RET}} 6  ok
 3865: @kbd{demo@key{RET}} 7  ok
 3866: @kbd{9 greet demo add-two@key{RET}} Hello and welcome7 11  ok
 3867: @end example
 3868: 
 3869: The first new thing that we've introduced here is the pair of words
 3870: @code{:} and @code{;}. These are used to start and terminate a new
 3871: definition, respectively. The first word after the @code{:} is the name
 3872: for the new definition.
 3873: 
 3874: As you can see from the examples, a definition is built up of words that
 3875: have already been defined; Forth makes no distinction between
 3876: definitions that existed when you started the system up, and those that
 3877: you define yourself.
 3878: 
 3879: The examples also introduce the words @code{.} (dot), @code{."}
 3880: (dot-quote) and @code{dup} (dewp). Dot takes the value from the top of
 3881: the stack and displays it. It's like @code{.s} except that it only
 3882: displays the top item of the stack and it is destructive; after it has
 3883: executed, the number is no longer on the stack. There is always one
 3884: space printed after the number, and no spaces before it. Dot-quote
 3885: defines a string (a sequence of characters) that will be printed when
 3886: the word is executed. The string can contain any printable characters
 3887: except @code{"}. A @code{"} has a special function; it is not a Forth
 3888: word but it acts as a delimiter (the way that delimiters work is
 3889: described in the next section). Finally, @code{dup} duplicates the value
 3890: at the top of the stack. Try typing @code{5 dup .s} to see what it does.
 3891: 
 3892: We already know that the text interpreter searches through the
 3893: dictionary to locate names. If you've followed the examples earlier, you
 3894: will already have a definition called @code{add-two}. Lets try modifying
 3895: it by typing in a new definition:
 3896: 
 3897: @example
 3898: @kbd{: add-two dup . ." + 2 =" 2 + . ;@key{RET}} redefined add-two  ok
 3899: @end example
 3900: 
 3901: Forth recognised that we were defining a word that already exists, and
 3902: printed a message to warn us of that fact. Let's try out the new
 3903: definition:
 3904: 
 3905: @example
 3906: @kbd{9 add-two@key{RET}} 9 + 2 =11  ok
 3907: @end example
 3908: 
 3909: @noindent
 3910: All that we've actually done here, though, is to create a new
 3911: definition, with a particular name. The fact that there was already a
 3912: definition with the same name did not make any difference to the way
 3913: that the new definition was created (except that Forth printed a warning
 3914: message). The old definition of add-two still exists (try @code{demo}
 3915: again to see that this is true). Any new definition will use the new
 3916: definition of @code{add-two}, but old definitions continue to use the
 3917: version that already existed at the time that they were @code{compiled}.
 3918: 
 3919: Before you go on to the next section, try defining and redefining some
 3920: words of your own.
 3921: 
 3922: @comment ----------------------------------------------
 3923: @node How does that work?, Forth is written in Forth, Your first definition, Introduction
 3924: @section How does that work?
 3925: @cindex parsing words
 3926: 
 3927: @c That's pretty deep (IMO way too deep) for an introduction. - anton
 3928: 
 3929: @c Is it a good idea to talk about the interpretation semantics of a
 3930: @c number? We don't have an xt to go along with it. - anton
 3931: 
 3932: @c Now that I have eliminated execution semantics, I wonder if it would not
 3933: @c be better to keep them (or add run-time semantics), to make it easier to
 3934: @c explain what compilation semantics usually does. - anton
 3935: 
 3936: @c nac-> I removed the term ``default compilation sematics'' from the
 3937: @c introductory chapter. Removing ``execution semantics'' was making
 3938: @c everything simpler to explain, then I think the use of this term made
 3939: @c everything more complex again. I replaced it with ``default
 3940: @c semantics'' (which is used elsewhere in the manual) by which I mean
 3941: @c ``a definition that has neither the immediate nor the compile-only
 3942: @c flag set''.
 3943: 
 3944: @c anton: I have eliminated default semantics (except in one place where it
 3945: @c means "default interpretation and compilation semantics"), because it
 3946: @c makes no sense in the presence of combined words.  I reverted to
 3947: @c "execution semantics" where necessary.
 3948: 
 3949: @c nac-> I reworded big chunks of the ``how does that work''
 3950: @c section (and, unusually for me, I think I even made it shorter!).  See
 3951: @c what you think -- I know I have not addressed your primary concern
 3952: @c that it is too heavy-going for an introduction. From what I understood
 3953: @c of your course notes it looks as though they might be a good framework. 
 3954: @c Things that I've tried to capture here are some things that came as a
 3955: @c great revelation here when I first understood them. Also, I like the
 3956: @c fact that a very simple code example shows up almost all of the issues
 3957: @c that you need to understand to see how Forth works. That's unique and
 3958: @c worthwhile to emphasise.
 3959: 
 3960: @c anton: I think it's a good idea to present the details, especially those
 3961: @c that you found to be a revelation, and probably the tutorial tries to be
 3962: @c too superficial and does not get some of the things across that make
 3963: @c Forth special.  I do believe that most of the time these things should
 3964: @c be discussed at the end of a section or in separate sections instead of
 3965: @c in the middle of a section (e.g., the stuff you added in "User-defined
 3966: @c defining words" leads in a completely different direction from the rest
 3967: @c of the section).
 3968: 
 3969: Now we're going to take another look at the definition of @code{add-two}
 3970: from the previous section. From our knowledge of the way that the text
 3971: interpreter works, we would have expected this result when we tried to
 3972: define @code{add-two}:
 3973: 
 3974: @example
 3975: @kbd{: add-two 2 + . ;@key{RET}}
 3976: *the terminal*:4: Undefined word
 3977: : >>>add-two<<< 2 + . ;
 3978: @end example
 3979: 
 3980: The reason that this didn't happen is bound up in the way that @code{:}
 3981: works. The word @code{:} does two special things. The first special
 3982: thing that it does prevents the text interpreter from ever seeing the
 3983: characters @code{add-two}. The text interpreter uses a variable called
 3984: @cindex modifying >IN
 3985: @code{>IN} (pronounced ``to-in'') to keep track of where it is in the
 3986: input line. When it encounters the word @code{:} it behaves in exactly
 3987: the same way as it does for any other word; it looks it up in the name
 3988: dictionary, finds its xt and executes it. When @code{:} executes, it
 3989: looks at the input buffer, finds the word @code{add-two} and advances the
 3990: value of @code{>IN} to point past it. It then does some other stuff
 3991: associated with creating the new definition (including creating an entry
 3992: for @code{add-two} in the name dictionary). When the execution of @code{:}
 3993: completes, control returns to the text interpreter, which is oblivious
 3994: to the fact that it has been tricked into ignoring part of the input
 3995: line.
 3996: 
 3997: @cindex parsing words
 3998: Words like @code{:} -- words that advance the value of @code{>IN} and so
 3999: prevent the text interpreter from acting on the whole of the input line
 4000: -- are called @dfn{parsing words}.
 4001: 
 4002: @cindex @code{state} - effect on the text interpreter
 4003: @cindex text interpreter - effect of state
 4004: The second special thing that @code{:} does is change the value of a
 4005: variable called @code{state}, which affects the way that the text
 4006: interpreter behaves. When Gforth starts up, @code{state} has the value
 4007: 0, and the text interpreter is said to be @dfn{interpreting}. During a
 4008: colon definition (started with @code{:}), @code{state} is set to -1 and
 4009: the text interpreter is said to be @dfn{compiling}.
 4010: 
 4011: In this example, the text interpreter is compiling when it processes the
 4012: string ``@code{2 + . ;}''. It still breaks the string down into
 4013: character sequences in the same way. However, instead of pushing the
 4014: number @code{2} onto the stack, it lays down (@dfn{compiles}) some magic
 4015: into the definition of @code{add-two} that will make the number @code{2} get
 4016: pushed onto the stack when @code{add-two} is @dfn{executed}. Similarly,
 4017: the behaviours of @code{+} and @code{.} are also compiled into the
 4018: definition.
 4019: 
 4020: One category of words don't get compiled. These so-called @dfn{immediate
 4021: words} get executed (performed @i{now}) regardless of whether the text
 4022: interpreter is interpreting or compiling. The word @code{;} is an
 4023: immediate word. Rather than being compiled into the definition, it
 4024: executes. Its effect is to terminate the current definition, which
 4025: includes changing the value of @code{state} back to 0.
 4026: 
 4027: When you execute @code{add-two}, it has a @dfn{run-time effect} that is
 4028: exactly the same as if you had typed @code{2 + . @key{RET}} outside of a
 4029: definition.
 4030: 
 4031: In Forth, every word or number can be described in terms of two
 4032: properties:
 4033: 
 4034: @itemize @bullet
 4035: @item
 4036: @cindex interpretation semantics
 4037: Its @dfn{interpretation semantics} describe how it will behave when the
 4038: text interpreter encounters it in @dfn{interpret} state. The
 4039: interpretation semantics of a word are represented by an @dfn{execution
 4040: token}.
 4041: @item
 4042: @cindex compilation semantics
 4043: Its @dfn{compilation semantics} describe how it will behave when the
 4044: text interpreter encounters it in @dfn{compile} state. The compilation
 4045: semantics of a word are represented in an implementation-dependent way;
 4046: Gforth uses a @dfn{compilation token}.
 4047: @end itemize
 4048: 
 4049: @noindent
 4050: Numbers are always treated in a fixed way:
 4051: 
 4052: @itemize @bullet
 4053: @item
 4054: When the number is @dfn{interpreted}, its behaviour is to push the
 4055: number onto the stack.
 4056: @item
 4057: When the number is @dfn{compiled}, a piece of code is appended to the
 4058: current definition that pushes the number when it runs. (In other words,
 4059: the compilation semantics of a number are to postpone its interpretation
 4060: semantics until the run-time of the definition that it is being compiled
 4061: into.)
 4062: @end itemize
 4063: 
 4064: Words don't behave in such a regular way, but most have @i{default
 4065: semantics} which means that they behave like this:
 4066: 
 4067: @itemize @bullet
 4068: @item
 4069: The @dfn{interpretation semantics} of the word are to do something useful.
 4070: @item
 4071: The @dfn{compilation semantics} of the word are to append its
 4072: @dfn{interpretation semantics} to the current definition (so that its
 4073: run-time behaviour is to do something useful).
 4074: @end itemize
 4075: 
 4076: @cindex immediate words
 4077: The actual behaviour of any particular word can be controlled by using
 4078: the words @code{immediate} and @code{compile-only} when the word is
 4079: defined. These words set flags in the name dictionary entry of the most
 4080: recently defined word, and these flags are retrieved by the text
 4081: interpreter when it finds the word in the name dictionary.
 4082: 
 4083: A word that is marked as @dfn{immediate} has compilation semantics that
 4084: are identical to its interpretation semantics. In other words, it
 4085: behaves like this:
 4086: 
 4087: @itemize @bullet
 4088: @item
 4089: The @dfn{interpretation semantics} of the word are to do something useful.
 4090: @item
 4091: The @dfn{compilation semantics} of the word are to do something useful
 4092: (and actually the same thing); i.e., it is executed during compilation.
 4093: @end itemize
 4094: 
 4095: Marking a word as @dfn{compile-only} prohibits the text interpreter from
 4096: performing the interpretation semantics of the word directly; an attempt
 4097: to do so will generate an error. It is never necessary to use
 4098: @code{compile-only} (and it is not even part of ANS Forth, though it is
 4099: provided by many implementations) but it is good etiquette to apply it
 4100: to a word that will not behave correctly (and might have unexpected
 4101: side-effects) in interpret state. For example, it is only legal to use
 4102: the conditional word @code{IF} within a definition. If you forget this
 4103: and try to use it elsewhere, the fact that (in Gforth) it is marked as
 4104: @code{compile-only} allows the text interpreter to generate a helpful
 4105: error message rather than subjecting you to the consequences of your
 4106: folly.
 4107: 
 4108: This example shows the difference between an immediate and a
 4109: non-immediate word:
 4110: 
 4111: @example
 4112: : show-state state @@ . ;
 4113: : show-state-now show-state ; immediate
 4114: : word1 show-state ;
 4115: : word2 show-state-now ;
 4116: @end example
 4117: 
 4118: The word @code{immediate} after the definition of @code{show-state-now}
 4119: makes that word an immediate word. These definitions introduce a new
 4120: word: @code{@@} (pronounced ``fetch''). This word fetches the value of a
 4121: variable, and leaves it on the stack. Therefore, the behaviour of
 4122: @code{show-state} is to print a number that represents the current value
 4123: of @code{state}.
 4124: 
 4125: When you execute @code{word1}, it prints the number 0, indicating that
 4126: the system is interpreting. When the text interpreter compiled the
 4127: definition of @code{word1}, it encountered @code{show-state} whose
 4128: compilation semantics are to append its interpretation semantics to the
 4129: current definition. When you execute @code{word1}, it performs the
 4130: interpretation semantics of @code{show-state}.  At the time that @code{word1}
 4131: (and therefore @code{show-state}) are executed, the system is
 4132: interpreting.
 4133: 
 4134: When you pressed @key{RET} after entering the definition of @code{word2},
 4135: you should have seen the number -1 printed, followed by ``@code{
 4136: ok}''. When the text interpreter compiled the definition of
 4137: @code{word2}, it encountered @code{show-state-now}, an immediate word,
 4138: whose compilation semantics are therefore to perform its interpretation
 4139: semantics. It is executed straight away (even before the text
 4140: interpreter has moved on to process another group of characters; the
 4141: @code{;} in this example). The effect of executing it are to display the
 4142: value of @code{state} @i{at the time that the definition of}
 4143: @code{word2} @i{is being defined}. Printing -1 demonstrates that the
 4144: system is compiling at this time. If you execute @code{word2} it does
 4145: nothing at all.
 4146: 
 4147: @cindex @code{."}, how it works
 4148: Before leaving the subject of immediate words, consider the behaviour of
 4149: @code{."} in the definition of @code{greet}, in the previous
 4150: section. This word is both a parsing word and an immediate word. Notice
 4151: that there is a space between @code{."} and the start of the text
 4152: @code{Hello and welcome}, but that there is no space between the last
 4153: letter of @code{welcome} and the @code{"} character. The reason for this
 4154: is that @code{."} is a Forth word; it must have a space after it so that
 4155: the text interpreter can identify it. The @code{"} is not a Forth word;
 4156: it is a @dfn{delimiter}. The examples earlier show that, when the string
 4157: is displayed, there is neither a space before the @code{H} nor after the
 4158: @code{e}. Since @code{."} is an immediate word, it executes at the time
 4159: that @code{greet} is defined. When it executes, its behaviour is to
 4160: search forward in the input line looking for the delimiter. When it
 4161: finds the delimiter, it updates @code{>IN} to point past the
 4162: delimiter. It also compiles some magic code into the definition of
 4163: @code{greet}; the xt of a run-time routine that prints a text string. It
 4164: compiles the string @code{Hello and welcome} into memory so that it is
 4165: available to be printed later. When the text interpreter gains control,
 4166: the next word it finds in the input stream is @code{;} and so it
 4167: terminates the definition of @code{greet}.
 4168: 
 4169: 
 4170: @comment ----------------------------------------------
 4171: @node Forth is written in Forth, Review - elements of a Forth system, How does that work?, Introduction
 4172: @section Forth is written in Forth
 4173: @cindex structure of Forth programs
 4174: 
 4175: When you start up a Forth compiler, a large number of definitions
 4176: already exist. In Forth, you develop a new application using bottom-up
 4177: programming techniques to create new definitions that are defined in
 4178: terms of existing definitions. As you create each definition you can
 4179: test and debug it interactively.
 4180: 
 4181: If you have tried out the examples in this section, you will probably
 4182: have typed them in by hand; when you leave Gforth, your definitions will
 4183: be lost. You can avoid this by using a text editor to enter Forth source
 4184: code into a file, and then loading code from the file using
 4185: @code{include} (@pxref{Forth source files}). A Forth source file is
 4186: processed by the text interpreter, just as though you had typed it in by
 4187: hand@footnote{Actually, there are some subtle differences -- see
 4188: @ref{The Text Interpreter}.}.
 4189: 
 4190: Gforth also supports the traditional Forth alternative to using text
 4191: files for program entry (@pxref{Blocks}).
 4192: 
 4193: In common with many, if not most, Forth compilers, most of Gforth is
 4194: actually written in Forth. All of the @file{.fs} files in the
 4195: installation directory@footnote{For example,
 4196: @file{/usr/local/share/gforth...}} are Forth source files, which you can
 4197: study to see examples of Forth programming.
 4198: 
 4199: Gforth maintains a history file that records every line that you type to
 4200: the text interpreter. This file is preserved between sessions, and is
 4201: used to provide a command-line recall facility. If you enter long
 4202: definitions by hand, you can use a text editor to paste them out of the
 4203: history file into a Forth source file for reuse at a later time
 4204: (for more information @pxref{Command-line editing}).
 4205: 
 4206: 
 4207: @comment ----------------------------------------------
 4208: @node Review - elements of a Forth system, Where to go next, Forth is written in Forth, Introduction
 4209: @section Review - elements of a Forth system
 4210: @cindex elements of a Forth system
 4211: 
 4212: To summarise this chapter:
 4213: 
 4214: @itemize @bullet
 4215: @item
 4216: Forth programs use @dfn{factoring} to break a problem down into small
 4217: fragments called @dfn{words} or @dfn{definitions}.
 4218: @item
 4219: Forth program development is an interactive process.
 4220: @item
 4221: The main command loop that accepts input, and controls both
 4222: interpretation and compilation, is called the @dfn{text interpreter}
 4223: (also known as the @dfn{outer interpreter}).
 4224: @item
 4225: Forth has a very simple syntax, consisting of words and numbers
 4226: separated by spaces or carriage-return characters. Any additional syntax
 4227: is imposed by @dfn{parsing words}.
 4228: @item
 4229: Forth uses a stack to pass parameters between words. As a result, it
 4230: uses postfix notation.
 4231: @item
 4232: To use a word that has previously been defined, the text interpreter
 4233: searches for the word in the @dfn{name dictionary}.
 4234: @item
 4235: Words have @dfn{interpretation semantics} and @dfn{compilation semantics}.
 4236: @item
 4237: The text interpreter uses the value of @code{state} to select between
 4238: the use of the @dfn{interpretation semantics} and the  @dfn{compilation
 4239: semantics} of a word that it encounters.
 4240: @item
 4241: The relationship between the @dfn{interpretation semantics} and
 4242: @dfn{compilation semantics} for a word
 4243: depend upon the way in which the word was defined (for example, whether
 4244: it is an @dfn{immediate} word).
 4245: @item
 4246: Forth definitions can be implemented in Forth (called @dfn{high-level
 4247: definitions}) or in some other way (usually a lower-level language and
 4248: as a result often called @dfn{low-level definitions}, @dfn{code
 4249: definitions} or @dfn{primitives}).
 4250: @item
 4251: Many Forth systems are implemented mainly in Forth.
 4252: @end itemize
 4253: 
 4254: 
 4255: @comment ----------------------------------------------
 4256: @node Where to go next, Exercises, Review - elements of a Forth system, Introduction
 4257: @section Where To Go Next
 4258: @cindex where to go next
 4259: 
 4260: Amazing as it may seem, if you have read (and understood) this far, you
 4261: know almost all the fundamentals about the inner workings of a Forth
 4262: system. You certainly know enough to be able to read and understand the
 4263: rest of this manual and the ANS Forth document, to learn more about the
 4264: facilities that Forth in general and Gforth in particular provide. Even
 4265: scarier, you know almost enough to implement your own Forth system.
 4266: However, that's not a good idea just yet... better to try writing some
 4267: programs in Gforth.
 4268: 
 4269: Forth has such a rich vocabulary that it can be hard to know where to
 4270: start in learning it. This section suggests a few sets of words that are
 4271: enough to write small but useful programs. Use the word index in this
 4272: document to learn more about each word, then try it out and try to write
 4273: small definitions using it. Start by experimenting with these words:
 4274: 
 4275: @itemize @bullet
 4276: @item
 4277: Arithmetic: @code{+ - * / /MOD */ ABS INVERT}
 4278: @item
 4279: Comparison: @code{MIN MAX =}
 4280: @item
 4281: Logic: @code{AND OR XOR NOT}
 4282: @item
 4283: Stack manipulation: @code{DUP DROP SWAP OVER}
 4284: @item
 4285: Loops and decisions: @code{IF ELSE ENDIF ?DO I LOOP}
 4286: @item
 4287: Input/Output: @code{. ." EMIT CR KEY}
 4288: @item
 4289: Defining words: @code{: ; CREATE}
 4290: @item
 4291: Memory allocation words: @code{ALLOT ,}
 4292: @item
 4293: Tools: @code{SEE WORDS .S MARKER}
 4294: @end itemize
 4295: 
 4296: When you have mastered those, go on to:
 4297: 
 4298: @itemize @bullet
 4299: @item
 4300: More defining words: @code{VARIABLE CONSTANT VALUE TO CREATE DOES>}
 4301: @item
 4302: Memory access: @code{@@ !}
 4303: @end itemize
 4304: 
 4305: When you have mastered these, there's nothing for it but to read through
 4306: the whole of this manual and find out what you've missed.
 4307: 
 4308: @comment ----------------------------------------------
 4309: @node Exercises,  , Where to go next, Introduction
 4310: @section Exercises
 4311: @cindex exercises
 4312: 
 4313: TODO: provide a set of programming excercises linked into the stuff done
 4314: already and into other sections of the manual. Provide solutions to all
 4315: the exercises in a .fs file in the distribution.
 4316: 
 4317: @c Get some inspiration from Starting Forth and Kelly&Spies.
 4318: 
 4319: @c excercises:
 4320: @c 1. take inches and convert to feet and inches.
 4321: @c 2. take temperature and convert from fahrenheight to celcius;
 4322: @c    may need to care about symmetric vs floored??
 4323: @c 3. take input line and do character substitution
 4324: @c    to encipher or decipher
 4325: @c 4. as above but work on a file for in and out
 4326: @c 5. take input line and convert to pig-latin 
 4327: @c
 4328: @c thing of sets of things to exercise then come up with
 4329: @c problems that need those things.
 4330: 
 4331: 
 4332: @c ******************************************************************
 4333: @node Words, Error messages, Introduction, Top
 4334: @chapter Forth Words
 4335: @cindex words
 4336: 
 4337: @menu
 4338: * Notation::                    
 4339: * Case insensitivity::          
 4340: * Comments::                    
 4341: * Boolean Flags::               
 4342: * Arithmetic::                  
 4343: * Stack Manipulation::          
 4344: * Memory::                      
 4345: * Control Structures::          
 4346: * Defining Words::              
 4347: * Interpretation and Compilation Semantics::  
 4348: * Tokens for Words::            
 4349: * Compiling words::             
 4350: * The Text Interpreter::        
 4351: * The Input Stream::            
 4352: * Word Lists::                  
 4353: * Environmental Queries::       
 4354: * Files::                       
 4355: * Blocks::                      
 4356: * Other I/O::                   
 4357: * OS command line arguments::   
 4358: * Locals::                      
 4359: * Structures::                  
 4360: * Object-oriented Forth::       
 4361: * Programming Tools::           
 4362: * C Interface::                 
 4363: * Assembler and Code Words::    
 4364: * Threading Words::             
 4365: * Passing Commands to the OS::  
 4366: * Keeping track of Time::       
 4367: * Miscellaneous Words::         
 4368: @end menu
 4369: 
 4370: @node Notation, Case insensitivity, Words, Words
 4371: @section Notation
 4372: @cindex notation of glossary entries
 4373: @cindex format of glossary entries
 4374: @cindex glossary notation format
 4375: @cindex word glossary entry format
 4376: 
 4377: The Forth words are described in this section in the glossary notation
 4378: that has become a de-facto standard for Forth texts:
 4379: 
 4380: @format
 4381: @i{word}     @i{Stack effect}   @i{wordset}   @i{pronunciation}
 4382: @end format
 4383: @i{Description}
 4384: 
 4385: @table @var
 4386: @item word
 4387: The name of the word.
 4388: 
 4389: @item Stack effect
 4390: @cindex stack effect
 4391: The stack effect is written in the notation @code{@i{before} --
 4392: @i{after}}, where @i{before} and @i{after} describe the top of
 4393: stack entries before and after the execution of the word. The rest of
 4394: the stack is not touched by the word. The top of stack is rightmost,
 4395: i.e., a stack sequence is written as it is typed in. Note that Gforth
 4396: uses a separate floating point stack, but a unified stack
 4397: notation. Also, return stack effects are not shown in @i{stack
 4398: effect}, but in @i{Description}. The name of a stack item describes
 4399: the type and/or the function of the item. See below for a discussion of
 4400: the types.
 4401: 
 4402: All words have two stack effects: A compile-time stack effect and a
 4403: run-time stack effect. The compile-time stack-effect of most words is
 4404: @i{ -- }. If the compile-time stack-effect of a word deviates from
 4405: this standard behaviour, or the word does other unusual things at
 4406: compile time, both stack effects are shown; otherwise only the run-time
 4407: stack effect is shown.
 4408: 
 4409: @cindex pronounciation of words
 4410: @item pronunciation
 4411: How the word is pronounced.
 4412: 
 4413: @cindex wordset
 4414: @cindex environment wordset
 4415: @item wordset
 4416: The ANS Forth standard is divided into several word sets. A standard
 4417: system need not support all of them. Therefore, in theory, the fewer
 4418: word sets your program uses the more portable it will be. However, we
 4419: suspect that most ANS Forth systems on personal machines will feature
 4420: all word sets. Words that are not defined in ANS Forth have
 4421: @code{gforth} or @code{gforth-internal} as word set. @code{gforth}
 4422: describes words that will work in future releases of Gforth;
 4423: @code{gforth-internal} words are more volatile. Environmental query
 4424: strings are also displayed like words; you can recognize them by the
 4425: @code{environment} in the word set field.
 4426: 
 4427: @item Description
 4428: A description of the behaviour of the word.
 4429: @end table
 4430: 
 4431: @cindex types of stack items
 4432: @cindex stack item types
 4433: The type of a stack item is specified by the character(s) the name
 4434: starts with:
 4435: 
 4436: @table @code
 4437: @item f
 4438: @cindex @code{f}, stack item type
 4439: Boolean flags, i.e. @code{false} or @code{true}.
 4440: @item c
 4441: @cindex @code{c}, stack item type
 4442: Char
 4443: @item w
 4444: @cindex @code{w}, stack item type
 4445: Cell, can contain an integer or an address
 4446: @item n
 4447: @cindex @code{n}, stack item type
 4448: signed integer
 4449: @item u
 4450: @cindex @code{u}, stack item type
 4451: unsigned integer
 4452: @item d
 4453: @cindex @code{d}, stack item type
 4454: double sized signed integer
 4455: @item ud
 4456: @cindex @code{ud}, stack item type
 4457: double sized unsigned integer
 4458: @item r
 4459: @cindex @code{r}, stack item type
 4460: Float (on the FP stack)
 4461: @item a-
 4462: @cindex @code{a_}, stack item type
 4463: Cell-aligned address
 4464: @item c-
 4465: @cindex @code{c_}, stack item type
 4466: Char-aligned address (note that a Char may have two bytes in Windows NT)
 4467: @item f-
 4468: @cindex @code{f_}, stack item type
 4469: Float-aligned address
 4470: @item df-
 4471: @cindex @code{df_}, stack item type
 4472: Address aligned for IEEE double precision float
 4473: @item sf-
 4474: @cindex @code{sf_}, stack item type
 4475: Address aligned for IEEE single precision float
 4476: @item xt
 4477: @cindex @code{xt}, stack item type
 4478: Execution token, same size as Cell
 4479: @item wid
 4480: @cindex @code{wid}, stack item type
 4481: Word list ID, same size as Cell
 4482: @item ior, wior
 4483: @cindex ior type description
 4484: @cindex wior type description
 4485: I/O result code, cell-sized.  In Gforth, you can @code{throw} iors.
 4486: @item f83name
 4487: @cindex @code{f83name}, stack item type
 4488: Pointer to a name structure
 4489: @item "
 4490: @cindex @code{"}, stack item type
 4491: string in the input stream (not on the stack). The terminating character
 4492: is a blank by default. If it is not a blank, it is shown in @code{<>}
 4493: quotes.
 4494: @end table
 4495: 
 4496: @comment ----------------------------------------------
 4497: @node Case insensitivity, Comments, Notation, Words
 4498: @section Case insensitivity
 4499: @cindex case sensitivity
 4500: @cindex upper and lower case
 4501: 
 4502: Gforth is case-insensitive; you can enter definitions and invoke
 4503: Standard words using upper, lower or mixed case (however,
 4504: @pxref{core-idef, Implementation-defined options, Implementation-defined
 4505: options}).
 4506: 
 4507: ANS Forth only @i{requires} implementations to recognise Standard words
 4508: when they are typed entirely in upper case. Therefore, a Standard
 4509: program must use upper case for all Standard words. You can use whatever
 4510: case you like for words that you define, but in a Standard program you
 4511: have to use the words in the same case that you defined them.
 4512: 
 4513: Gforth supports case sensitivity through @code{table}s (case-sensitive
 4514: wordlists, @pxref{Word Lists}).
 4515: 
 4516: Two people have asked how to convert Gforth to be case-sensitive; while
 4517: we think this is a bad idea, you can change all wordlists into tables
 4518: like this:
 4519: 
 4520: @example
 4521: ' table-find forth-wordlist wordlist-map @ !
 4522: @end example
 4523: 
 4524: Note that you now have to type the predefined words in the same case
 4525: that we defined them, which are varying.  You may want to convert them
 4526: to your favourite case before doing this operation (I won't explain how,
 4527: because if you are even contemplating doing this, you'd better have
 4528: enough knowledge of Forth systems to know this already).
 4529: 
 4530: @node Comments, Boolean Flags, Case insensitivity, Words
 4531: @section Comments
 4532: @cindex comments
 4533: 
 4534: Forth supports two styles of comment; the traditional @i{in-line} comment,
 4535: @code{(} and its modern cousin, the @i{comment to end of line}; @code{\}.
 4536: 
 4537: 
 4538: doc-(
 4539: doc-\
 4540: doc-\G
 4541: 
 4542: 
 4543: @node Boolean Flags, Arithmetic, Comments, Words
 4544: @section Boolean Flags
 4545: @cindex Boolean flags
 4546: 
 4547: A Boolean flag is cell-sized. A cell with all bits clear represents the
 4548: flag @code{false} and a flag with all bits set represents the flag
 4549: @code{true}. Words that check a flag (for example, @code{IF}) will treat
 4550: a cell that has @i{any} bit set as @code{true}.
 4551: @c on and off to Memory? 
 4552: @c true and false to "Bitwise operations" or "Numeric comparison"?
 4553: 
 4554: doc-true
 4555: doc-false
 4556: doc-on
 4557: doc-off
 4558: 
 4559: 
 4560: @node Arithmetic, Stack Manipulation, Boolean Flags, Words
 4561: @section Arithmetic
 4562: @cindex arithmetic words
 4563: 
 4564: @cindex division with potentially negative operands
 4565: Forth arithmetic is not checked, i.e., you will not hear about integer
 4566: overflow on addition or multiplication, you may hear about division by
 4567: zero if you are lucky. The operator is written after the operands, but
 4568: the operands are still in the original order. I.e., the infix @code{2-1}
 4569: corresponds to @code{2 1 -}. Forth offers a variety of division
 4570: operators. If you perform division with potentially negative operands,
 4571: you do not want to use @code{/} or @code{/mod} with its undefined
 4572: behaviour, but rather @code{fm/mod} or @code{sm/mod} (probably the
 4573: former, @pxref{Mixed precision}).
 4574: @comment TODO discuss the different division forms and the std approach
 4575: 
 4576: @menu
 4577: * Single precision::            
 4578: * Double precision::            Double-cell integer arithmetic
 4579: * Bitwise operations::          
 4580: * Numeric comparison::          
 4581: * Mixed precision::             Operations with single and double-cell integers
 4582: * Floating Point::              
 4583: @end menu
 4584: 
 4585: @node Single precision, Double precision, Arithmetic, Arithmetic
 4586: @subsection Single precision
 4587: @cindex single precision arithmetic words
 4588: 
 4589: @c !! cell undefined
 4590: 
 4591: By default, numbers in Forth are single-precision integers that are one
 4592: cell in size. They can be signed or unsigned, depending upon how you
 4593: treat them. For the rules used by the text interpreter for recognising
 4594: single-precision integers see @ref{Number Conversion}.
 4595: 
 4596: These words are all defined for signed operands, but some of them also
 4597: work for unsigned numbers: @code{+}, @code{1+}, @code{-}, @code{1-},
 4598: @code{*}.
 4599: 
 4600: doc-+
 4601: doc-1+
 4602: doc-under+
 4603: doc--
 4604: doc-1-
 4605: doc-*
 4606: doc-/
 4607: doc-mod
 4608: doc-/mod
 4609: doc-negate
 4610: doc-abs
 4611: doc-min
 4612: doc-max
 4613: doc-floored
 4614: 
 4615: 
 4616: @node Double precision, Bitwise operations, Single precision, Arithmetic
 4617: @subsection Double precision
 4618: @cindex double precision arithmetic words
 4619: 
 4620: For the rules used by the text interpreter for
 4621: recognising double-precision integers, see @ref{Number Conversion}.
 4622: 
 4623: A double precision number is represented by a cell pair, with the most
 4624: significant cell at the TOS. It is trivial to convert an unsigned single
 4625: to a double: simply push a @code{0} onto the TOS. Since numbers are
 4626: represented by Gforth using 2's complement arithmetic, converting a
 4627: signed single to a (signed) double requires sign-extension across the
 4628: most significant cell. This can be achieved using @code{s>d}. The moral
 4629: of the story is that you cannot convert a number without knowing whether
 4630: it represents an unsigned or a signed number.
 4631: 
 4632: These words are all defined for signed operands, but some of them also
 4633: work for unsigned numbers: @code{d+}, @code{d-}.
 4634: 
 4635: doc-s>d
 4636: doc-d>s
 4637: doc-d+
 4638: doc-d-
 4639: doc-dnegate
 4640: doc-dabs
 4641: doc-dmin
 4642: doc-dmax
 4643: 
 4644: 
 4645: @node Bitwise operations, Numeric comparison, Double precision, Arithmetic
 4646: @subsection Bitwise operations
 4647: @cindex bitwise operation words
 4648: 
 4649: 
 4650: doc-and
 4651: doc-or
 4652: doc-xor
 4653: doc-invert
 4654: doc-lshift
 4655: doc-rshift
 4656: doc-2*
 4657: doc-d2*
 4658: doc-2/
 4659: doc-d2/
 4660: 
 4661: 
 4662: @node Numeric comparison, Mixed precision, Bitwise operations, Arithmetic
 4663: @subsection Numeric comparison
 4664: @cindex numeric comparison words
 4665: 
 4666: Note that the words that compare for equality (@code{= <> 0= 0<> d= d<>
 4667: d0= d0<>}) work for for both signed and unsigned numbers.
 4668: 
 4669: doc-<
 4670: doc-<=
 4671: doc-<>
 4672: doc-=
 4673: doc->
 4674: doc->=
 4675: 
 4676: doc-0<
 4677: doc-0<=
 4678: doc-0<>
 4679: doc-0=
 4680: doc-0>
 4681: doc-0>=
 4682: 
 4683: doc-u<
 4684: doc-u<=
 4685: @c u<> and u= exist but are the same as <> and =
 4686: @c doc-u<>
 4687: @c doc-u=
 4688: doc-u>
 4689: doc-u>=
 4690: 
 4691: doc-within
 4692: 
 4693: doc-d<
 4694: doc-d<=
 4695: doc-d<>
 4696: doc-d=
 4697: doc-d>
 4698: doc-d>=
 4699: 
 4700: doc-d0<
 4701: doc-d0<=
 4702: doc-d0<>
 4703: doc-d0=
 4704: doc-d0>
 4705: doc-d0>=
 4706: 
 4707: doc-du<
 4708: doc-du<=
 4709: @c du<> and du= exist but are the same as d<> and d=
 4710: @c doc-du<>
 4711: @c doc-du=
 4712: doc-du>
 4713: doc-du>=
 4714: 
 4715: 
 4716: @node Mixed precision, Floating Point, Numeric comparison, Arithmetic
 4717: @subsection Mixed precision
 4718: @cindex mixed precision arithmetic words
 4719: 
 4720: 
 4721: doc-m+
 4722: doc-*/
 4723: doc-*/mod
 4724: doc-m*
 4725: doc-um*
 4726: doc-m*/
 4727: doc-um/mod
 4728: doc-fm/mod
 4729: doc-sm/rem
 4730: 
 4731: 
 4732: @node Floating Point,  , Mixed precision, Arithmetic
 4733: @subsection Floating Point
 4734: @cindex floating point arithmetic words
 4735: 
 4736: For the rules used by the text interpreter for
 4737: recognising floating-point numbers see @ref{Number Conversion}.
 4738: 
 4739: Gforth has a separate floating point stack, but the documentation uses
 4740: the unified notation.@footnote{It's easy to generate the separate
 4741: notation from that by just separating the floating-point numbers out:
 4742: e.g. @code{( n r1 u r2 -- r3 )} becomes @code{( n u -- ) ( F: r1 r2 --
 4743: r3 )}.}
 4744: 
 4745: @cindex floating-point arithmetic, pitfalls
 4746: Floating point numbers have a number of unpleasant surprises for the
 4747: unwary (e.g., floating point addition is not associative) and even a
 4748: few for the wary. You should not use them unless you know what you are
 4749: doing or you don't care that the results you get are totally bogus. If
 4750: you want to learn about the problems of floating point numbers (and
 4751: how to avoid them), you might start with @cite{David Goldberg,
 4752: @uref{http://docs.sun.com/source/806-3568/ncg_goldberg.html,What Every
 4753: Computer Scientist Should Know About Floating-Point Arithmetic}, ACM
 4754: Computing Surveys 23(1):5@minus{}48, March 1991}.
 4755: 
 4756: 
 4757: doc-d>f
 4758: doc-f>d
 4759: doc-f+
 4760: doc-f-
 4761: doc-f*
 4762: doc-f/
 4763: doc-fnegate
 4764: doc-fabs
 4765: doc-fmax
 4766: doc-fmin
 4767: doc-floor
 4768: doc-fround
 4769: doc-f**
 4770: doc-fsqrt
 4771: doc-fexp
 4772: doc-fexpm1
 4773: doc-fln
 4774: doc-flnp1
 4775: doc-flog
 4776: doc-falog
 4777: doc-f2*
 4778: doc-f2/
 4779: doc-1/f
 4780: doc-precision
 4781: doc-set-precision
 4782: 
 4783: @cindex angles in trigonometric operations
 4784: @cindex trigonometric operations
 4785: Angles in floating point operations are given in radians (a full circle
 4786: has 2 pi radians).
 4787: 
 4788: doc-fsin
 4789: doc-fcos
 4790: doc-fsincos
 4791: doc-ftan
 4792: doc-fasin
 4793: doc-facos
 4794: doc-fatan
 4795: doc-fatan2
 4796: doc-fsinh
 4797: doc-fcosh
 4798: doc-ftanh
 4799: doc-fasinh
 4800: doc-facosh
 4801: doc-fatanh
 4802: doc-pi
 4803: 
 4804: @cindex equality of floats
 4805: @cindex floating-point comparisons
 4806: One particular problem with floating-point arithmetic is that comparison
 4807: for equality often fails when you would expect it to succeed.  For this
 4808: reason approximate equality is often preferred (but you still have to
 4809: know what you are doing).  Also note that IEEE NaNs may compare
 4810: differently from what you might expect.  The comparison words are:
 4811: 
 4812: doc-f~rel
 4813: doc-f~abs
 4814: doc-f~
 4815: doc-f=
 4816: doc-f<>
 4817: 
 4818: doc-f<
 4819: doc-f<=
 4820: doc-f>
 4821: doc-f>=
 4822: 
 4823: doc-f0<
 4824: doc-f0<=
 4825: doc-f0<>
 4826: doc-f0=
 4827: doc-f0>
 4828: doc-f0>=
 4829: 
 4830: 
 4831: @node Stack Manipulation, Memory, Arithmetic, Words
 4832: @section Stack Manipulation
 4833: @cindex stack manipulation words
 4834: 
 4835: @cindex floating-point stack in the standard
 4836: Gforth maintains a number of separate stacks:
 4837: 
 4838: @cindex data stack
 4839: @cindex parameter stack
 4840: @itemize @bullet
 4841: @item
 4842: A data stack (also known as the @dfn{parameter stack}) -- for
 4843: characters, cells, addresses, and double cells.
 4844: 
 4845: @cindex floating-point stack
 4846: @item
 4847: A floating point stack -- for holding floating point (FP) numbers.
 4848: 
 4849: @cindex return stack
 4850: @item
 4851: A return stack -- for holding the return addresses of colon
 4852: definitions and other (non-FP) data.
 4853: 
 4854: @cindex locals stack
 4855: @item
 4856: A locals stack -- for holding local variables.
 4857: @end itemize
 4858: 
 4859: @menu
 4860: * Data stack::                  
 4861: * Floating point stack::        
 4862: * Return stack::                
 4863: * Locals stack::                
 4864: * Stack pointer manipulation::  
 4865: @end menu
 4866: 
 4867: @node Data stack, Floating point stack, Stack Manipulation, Stack Manipulation
 4868: @subsection Data stack
 4869: @cindex data stack manipulation words
 4870: @cindex stack manipulations words, data stack
 4871: 
 4872: 
 4873: doc-drop
 4874: doc-nip
 4875: doc-dup
 4876: doc-over
 4877: doc-tuck
 4878: doc-swap
 4879: doc-pick
 4880: doc-rot
 4881: doc--rot
 4882: doc-?dup
 4883: doc-roll
 4884: doc-2drop
 4885: doc-2nip
 4886: doc-2dup
 4887: doc-2over
 4888: doc-2tuck
 4889: doc-2swap
 4890: doc-2rot
 4891: 
 4892: 
 4893: @node Floating point stack, Return stack, Data stack, Stack Manipulation
 4894: @subsection Floating point stack
 4895: @cindex floating-point stack manipulation words
 4896: @cindex stack manipulation words, floating-point stack
 4897: 
 4898: Whilst every sane Forth has a separate floating-point stack, it is not
 4899: strictly required; an ANS Forth system could theoretically keep
 4900: floating-point numbers on the data stack. As an additional difficulty,
 4901: you don't know how many cells a floating-point number takes. It is
 4902: reportedly possible to write words in a way that they work also for a
 4903: unified stack model, but we do not recommend trying it. Instead, just
 4904: say that your program has an environmental dependency on a separate
 4905: floating-point stack.
 4906: 
 4907: doc-floating-stack
 4908: 
 4909: doc-fdrop
 4910: doc-fnip
 4911: doc-fdup
 4912: doc-fover
 4913: doc-ftuck
 4914: doc-fswap
 4915: doc-fpick
 4916: doc-frot
 4917: 
 4918: 
 4919: @node Return stack, Locals stack, Floating point stack, Stack Manipulation
 4920: @subsection Return stack
 4921: @cindex return stack manipulation words
 4922: @cindex stack manipulation words, return stack
 4923: 
 4924: @cindex return stack and locals
 4925: @cindex locals and return stack
 4926: A Forth system is allowed to keep local variables on the
 4927: return stack. This is reasonable, as local variables usually eliminate
 4928: the need to use the return stack explicitly. So, if you want to produce
 4929: a standard compliant program and you are using local variables in a
 4930: word, forget about return stack manipulations in that word (refer to the
 4931: standard document for the exact rules).
 4932: 
 4933: doc->r
 4934: doc-r>
 4935: doc-r@
 4936: doc-rdrop
 4937: doc-2>r
 4938: doc-2r>
 4939: doc-2r@
 4940: doc-2rdrop
 4941: 
 4942: 
 4943: @node Locals stack, Stack pointer manipulation, Return stack, Stack Manipulation
 4944: @subsection Locals stack
 4945: 
 4946: Gforth uses an extra locals stack.  It is described, along with the
 4947: reasons for its existence, in @ref{Locals implementation}.
 4948: 
 4949: @node Stack pointer manipulation,  , Locals stack, Stack Manipulation
 4950: @subsection Stack pointer manipulation
 4951: @cindex stack pointer manipulation words
 4952: 
 4953: @c removed s0 r0 l0 -- they are obsolete aliases for sp0 rp0 lp0
 4954: doc-sp0
 4955: doc-sp@
 4956: doc-sp!
 4957: doc-fp0
 4958: doc-fp@
 4959: doc-fp!
 4960: doc-rp0
 4961: doc-rp@
 4962: doc-rp!
 4963: doc-lp0
 4964: doc-lp@
 4965: doc-lp!
 4966: 
 4967: 
 4968: @node Memory, Control Structures, Stack Manipulation, Words
 4969: @section Memory
 4970: @cindex memory words
 4971: 
 4972: @menu
 4973: * Memory model::                
 4974: * Dictionary allocation::       
 4975: * Heap Allocation::             
 4976: * Memory Access::               
 4977: * Address arithmetic::          
 4978: * Memory Blocks::               
 4979: @end menu
 4980: 
 4981: In addition to the standard Forth memory allocation words, there is also
 4982: a @uref{http://www.complang.tuwien.ac.at/forth/garbage-collection.zip,
 4983: garbage collector}.
 4984: 
 4985: @node Memory model, Dictionary allocation, Memory, Memory
 4986: @subsection ANS Forth and Gforth memory models
 4987: 
 4988: @c The ANS Forth description is a mess (e.g., is the heap part of
 4989: @c the dictionary?), so let's not stick to closely with it.
 4990: 
 4991: ANS Forth considers a Forth system as consisting of several address
 4992: spaces, of which only @dfn{data space} is managed and accessible with
 4993: the memory words.  Memory not necessarily in data space includes the
 4994: stacks, the code (called code space) and the headers (called name
 4995: space). In Gforth everything is in data space, but the code for the
 4996: primitives is usually read-only.
 4997: 
 4998: Data space is divided into a number of areas: The (data space portion of
 4999: the) dictionary@footnote{Sometimes, the term @dfn{dictionary} is used to
 5000: refer to the search data structure embodied in word lists and headers,
 5001: because it is used for looking up names, just as you would in a
 5002: conventional dictionary.}, the heap, and a number of system-allocated
 5003: buffers.
 5004: 
 5005: @cindex address arithmetic restrictions, ANS vs. Gforth
 5006: @cindex contiguous regions, ANS vs. Gforth
 5007: In ANS Forth data space is also divided into contiguous regions.  You
 5008: can only use address arithmetic within a contiguous region, not between
 5009: them.  Usually each allocation gives you one contiguous region, but the
 5010: dictionary allocation words have additional rules (@pxref{Dictionary
 5011: allocation}).
 5012: 
 5013: Gforth provides one big address space, and address arithmetic can be
 5014: performed between any addresses. However, in the dictionary headers or
 5015: code are interleaved with data, so almost the only contiguous data space
 5016: regions there are those described by ANS Forth as contiguous; but you
 5017: can be sure that the dictionary is allocated towards increasing
 5018: addresses even between contiguous regions.  The memory order of
 5019: allocations in the heap is platform-dependent (and possibly different
 5020: from one run to the next).
 5021: 
 5022: 
 5023: @node Dictionary allocation, Heap Allocation, Memory model, Memory
 5024: @subsection Dictionary allocation
 5025: @cindex reserving data space
 5026: @cindex data space - reserving some
 5027: 
 5028: Dictionary allocation is a stack-oriented allocation scheme, i.e., if
 5029: you want to deallocate X, you also deallocate everything
 5030: allocated after X.
 5031: 
 5032: @cindex contiguous regions in dictionary allocation
 5033: The allocations using the words below are contiguous and grow the region
 5034: towards increasing addresses.  Other words that allocate dictionary
 5035: memory of any kind (i.e., defining words including @code{:noname}) end
 5036: the contiguous region and start a new one.
 5037: 
 5038: In ANS Forth only @code{create}d words are guaranteed to produce an
 5039: address that is the start of the following contiguous region.  In
 5040: particular, the cell allocated by @code{variable} is not guaranteed to
 5041: be contiguous with following @code{allot}ed memory.
 5042: 
 5043: You can deallocate memory by using @code{allot} with a negative argument
 5044: (with some restrictions, see @code{allot}). For larger deallocations use
 5045: @code{marker}.
 5046: 
 5047: 
 5048: doc-here
 5049: doc-unused
 5050: doc-allot
 5051: doc-c,
 5052: doc-f,
 5053: doc-,
 5054: doc-2,
 5055: 
 5056: Memory accesses have to be aligned (@pxref{Address arithmetic}). So of
 5057: course you should allocate memory in an aligned way, too. I.e., before
 5058: allocating allocating a cell, @code{here} must be cell-aligned, etc.
 5059: The words below align @code{here} if it is not already.  Basically it is
 5060: only already aligned for a type, if the last allocation was a multiple
 5061: of the size of this type and if @code{here} was aligned for this type
 5062: before.
 5063: 
 5064: After freshly @code{create}ing a word, @code{here} is @code{align}ed in
 5065: ANS Forth (@code{maxalign}ed in Gforth).
 5066: 
 5067: doc-align
 5068: doc-falign
 5069: doc-sfalign
 5070: doc-dfalign
 5071: doc-maxalign
 5072: doc-cfalign
 5073: 
 5074: 
 5075: @node Heap Allocation, Memory Access, Dictionary allocation, Memory
 5076: @subsection Heap allocation
 5077: @cindex heap allocation
 5078: @cindex dynamic allocation of memory
 5079: @cindex memory-allocation word set
 5080: 
 5081: @cindex contiguous regions and heap allocation
 5082: Heap allocation supports deallocation of allocated memory in any
 5083: order. Dictionary allocation is not affected by it (i.e., it does not
 5084: end a contiguous region). In Gforth, these words are implemented using
 5085: the standard C library calls malloc(), free() and resize().
 5086: 
 5087: The memory region produced by one invocation of @code{allocate} or
 5088: @code{resize} is internally contiguous.  There is no contiguity between
 5089: such a region and any other region (including others allocated from the
 5090: heap).
 5091: 
 5092: doc-allocate
 5093: doc-free
 5094: doc-resize
 5095: 
 5096: 
 5097: @node Memory Access, Address arithmetic, Heap Allocation, Memory
 5098: @subsection Memory Access
 5099: @cindex memory access words
 5100: 
 5101: doc-@
 5102: doc-!
 5103: doc-+!
 5104: doc-c@
 5105: doc-c!
 5106: doc-2@
 5107: doc-2!
 5108: doc-f@
 5109: doc-f!
 5110: doc-sf@
 5111: doc-sf!
 5112: doc-df@
 5113: doc-df!
 5114: doc-sw@
 5115: doc-uw@
 5116: doc-w!
 5117: doc-sl@
 5118: doc-ul@
 5119: doc-l!
 5120: 
 5121: @node Address arithmetic, Memory Blocks, Memory Access, Memory
 5122: @subsection Address arithmetic
 5123: @cindex address arithmetic words
 5124: 
 5125: Address arithmetic is the foundation on which you can build data
 5126: structures like arrays, records (@pxref{Structures}) and objects
 5127: (@pxref{Object-oriented Forth}).
 5128: 
 5129: @cindex address unit
 5130: @cindex au (address unit)
 5131: ANS Forth does not specify the sizes of the data types. Instead, it
 5132: offers a number of words for computing sizes and doing address
 5133: arithmetic. Address arithmetic is performed in terms of address units
 5134: (aus); on most systems the address unit is one byte. Note that a
 5135: character may have more than one au, so @code{chars} is no noop (on
 5136: platforms where it is a noop, it compiles to nothing).
 5137: 
 5138: The basic address arithmetic words are @code{+} and @code{-}.  E.g., if
 5139: you have the address of a cell, perform @code{1 cells +}, and you will
 5140: have the address of the next cell.
 5141: 
 5142: @cindex contiguous regions and address arithmetic
 5143: In ANS Forth you can perform address arithmetic only within a contiguous
 5144: region, i.e., if you have an address into one region, you can only add
 5145: and subtract such that the result is still within the region; you can
 5146: only subtract or compare addresses from within the same contiguous
 5147: region.  Reasons: several contiguous regions can be arranged in memory
 5148: in any way; on segmented systems addresses may have unusual
 5149: representations, such that address arithmetic only works within a
 5150: region.  Gforth provides a few more guarantees (linear address space,
 5151: dictionary grows upwards), but in general I have found it easy to stay
 5152: within contiguous regions (exception: computing and comparing to the
 5153: address just beyond the end of an array).
 5154: 
 5155: @cindex alignment of addresses for types
 5156: ANS Forth also defines words for aligning addresses for specific
 5157: types. Many computers require that accesses to specific data types
 5158: must only occur at specific addresses; e.g., that cells may only be
 5159: accessed at addresses divisible by 4. Even if a machine allows unaligned
 5160: accesses, it can usually perform aligned accesses faster. 
 5161: 
 5162: For the performance-conscious: alignment operations are usually only
 5163: necessary during the definition of a data structure, not during the
 5164: (more frequent) accesses to it.
 5165: 
 5166: ANS Forth defines no words for character-aligning addresses. This is not
 5167: an oversight, but reflects the fact that addresses that are not
 5168: char-aligned have no use in the standard and therefore will not be
 5169: created.
 5170: 
 5171: @cindex @code{CREATE} and alignment
 5172: ANS Forth guarantees that addresses returned by @code{CREATE}d words
 5173: are cell-aligned; in addition, Gforth guarantees that these addresses
 5174: are aligned for all purposes.
 5175: 
 5176: Note that the ANS Forth word @code{char} has nothing to do with address
 5177: arithmetic.
 5178: 
 5179: 
 5180: doc-chars
 5181: doc-char+
 5182: doc-cells
 5183: doc-cell+
 5184: doc-cell
 5185: doc-aligned
 5186: doc-floats
 5187: doc-float+
 5188: doc-float
 5189: doc-faligned
 5190: doc-sfloats
 5191: doc-sfloat+
 5192: doc-sfaligned
 5193: doc-dfloats
 5194: doc-dfloat+
 5195: doc-dfaligned
 5196: doc-maxaligned
 5197: doc-cfaligned
 5198: doc-address-unit-bits
 5199: doc-/w
 5200: doc-/l
 5201: 
 5202: @node Memory Blocks,  , Address arithmetic, Memory
 5203: @subsection Memory Blocks
 5204: @cindex memory block words
 5205: @cindex character strings - moving and copying
 5206: 
 5207: Memory blocks often represent character strings; For ways of storing
 5208: character strings in memory see @ref{String Formats}.  For other
 5209: string-processing words see @ref{Displaying characters and strings}.
 5210: 
 5211: A few of these words work on address unit blocks.  In that case, you
 5212: usually have to insert @code{CHARS} before the word when working on
 5213: character strings.  Most words work on character blocks, and expect a
 5214: char-aligned address.
 5215: 
 5216: When copying characters between overlapping memory regions, use
 5217: @code{chars move} or choose carefully between @code{cmove} and
 5218: @code{cmove>}.
 5219: 
 5220: doc-move
 5221: doc-erase
 5222: doc-cmove
 5223: doc-cmove>
 5224: doc-fill
 5225: doc-blank
 5226: doc-compare
 5227: doc-str=
 5228: doc-str<
 5229: doc-string-prefix?
 5230: doc-search
 5231: doc--trailing
 5232: doc-/string
 5233: doc-bounds
 5234: doc-pad
 5235: 
 5236: @comment TODO examples
 5237: 
 5238: 
 5239: @node Control Structures, Defining Words, Memory, Words
 5240: @section Control Structures
 5241: @cindex control structures
 5242: 
 5243: Control structures in Forth cannot be used interpretively, only in a
 5244: colon definition@footnote{To be precise, they have no interpretation
 5245: semantics (@pxref{Interpretation and Compilation Semantics}).}. We do
 5246: not like this limitation, but have not seen a satisfying way around it
 5247: yet, although many schemes have been proposed.
 5248: 
 5249: @menu
 5250: * Selection::                   IF ... ELSE ... ENDIF
 5251: * Simple Loops::                BEGIN ...
 5252: * Counted Loops::               DO
 5253: * Arbitrary control structures::  
 5254: * Calls and returns::           
 5255: * Exception Handling::          
 5256: @end menu
 5257: 
 5258: @node Selection, Simple Loops, Control Structures, Control Structures
 5259: @subsection Selection
 5260: @cindex selection control structures
 5261: @cindex control structures for selection
 5262: 
 5263: @cindex @code{IF} control structure
 5264: @example
 5265: @i{flag}
 5266: IF
 5267:   @i{code}
 5268: ENDIF
 5269: @end example
 5270: @noindent
 5271: 
 5272: If @i{flag} is non-zero (as far as @code{IF} etc. are concerned, a cell
 5273: with any bit set represents truth) @i{code} is executed.
 5274: 
 5275: @example
 5276: @i{flag}
 5277: IF
 5278:   @i{code1}
 5279: ELSE
 5280:   @i{code2}
 5281: ENDIF
 5282: @end example
 5283: 
 5284: If @var{flag} is true, @i{code1} is executed, otherwise @i{code2} is
 5285: executed.
 5286: 
 5287: You can use @code{THEN} instead of @code{ENDIF}. Indeed, @code{THEN} is
 5288: standard, and @code{ENDIF} is not, although it is quite popular. We
 5289: recommend using @code{ENDIF}, because it is less confusing for people
 5290: who also know other languages (and is not prone to reinforcing negative
 5291: prejudices against Forth in these people). Adding @code{ENDIF} to a
 5292: system that only supplies @code{THEN} is simple:
 5293: @example
 5294: : ENDIF   POSTPONE then ; immediate
 5295: @end example
 5296: 
 5297: [According to @cite{Webster's New Encyclopedic Dictionary}, @dfn{then
 5298: (adv.)}  has the following meanings:
 5299: @quotation
 5300: ... 2b: following next after in order ... 3d: as a necessary consequence
 5301: (if you were there, then you saw them).
 5302: @end quotation
 5303: Forth's @code{THEN} has the meaning 2b, whereas @code{THEN} in Pascal
 5304: and many other programming languages has the meaning 3d.]
 5305: 
 5306: Gforth also provides the words @code{?DUP-IF} and @code{?DUP-0=-IF}, so
 5307: you can avoid using @code{?dup}. Using these alternatives is also more
 5308: efficient than using @code{?dup}. Definitions in ANS Forth
 5309: for @code{ENDIF}, @code{?DUP-IF} and @code{?DUP-0=-IF} are provided in
 5310: @file{compat/control.fs}.
 5311: 
 5312: @cindex @code{CASE} control structure
 5313: @example
 5314: @i{n}
 5315: CASE
 5316:   @i{n1} OF @i{code1} ENDOF
 5317:   @i{n2} OF @i{code2} ENDOF
 5318:   @dots{}
 5319:   ( n ) @i{default-code} ( n )
 5320: ENDCASE ( )
 5321: @end example
 5322: 
 5323: Executes the first @i{codei}, where the @i{ni} is equal to @i{n}.  If
 5324: no @i{ni} matches, the optional @i{default-code} is executed. The
 5325: optional default case can be added by simply writing the code after
 5326: the last @code{ENDOF}. It may use @i{n}, which is on top of the stack,
 5327: but must not consume it.  The value @i{n} is consumed by this
 5328: construction (either by a OF that matches, or by the ENDCASE, if no OF
 5329: matches).
 5330: 
 5331: @progstyle
 5332: To keep the code understandable, you should ensure that you change the
 5333: stack in the same way (wrt. number and types of stack items consumed
 5334: and pushed) on all paths through a selection construct.
 5335: 
 5336: @node Simple Loops, Counted Loops, Selection, Control Structures
 5337: @subsection Simple Loops
 5338: @cindex simple loops
 5339: @cindex loops without count 
 5340: 
 5341: @cindex @code{WHILE} loop
 5342: @example
 5343: BEGIN
 5344:   @i{code1}
 5345:   @i{flag}
 5346: WHILE
 5347:   @i{code2}
 5348: REPEAT
 5349: @end example
 5350: 
 5351: @i{code1} is executed and @i{flag} is computed. If it is true,
 5352: @i{code2} is executed and the loop is restarted; If @i{flag} is
 5353: false, execution continues after the @code{REPEAT}.
 5354: 
 5355: @cindex @code{UNTIL} loop
 5356: @example
 5357: BEGIN
 5358:   @i{code}
 5359:   @i{flag}
 5360: UNTIL
 5361: @end example
 5362: 
 5363: @i{code} is executed. The loop is restarted if @code{flag} is false.
 5364: 
 5365: @progstyle
 5366: To keep the code understandable, a complete iteration of the loop should
 5367: not change the number and types of the items on the stacks.
 5368: 
 5369: @cindex endless loop
 5370: @cindex loops, endless
 5371: @example
 5372: BEGIN
 5373:   @i{code}
 5374: AGAIN
 5375: @end example
 5376: 
 5377: This is an endless loop.
 5378: 
 5379: @node Counted Loops, Arbitrary control structures, Simple Loops, Control Structures
 5380: @subsection Counted Loops
 5381: @cindex counted loops
 5382: @cindex loops, counted
 5383: @cindex @code{DO} loops
 5384: 
 5385: The basic counted loop is:
 5386: @example
 5387: @i{limit} @i{start}
 5388: ?DO
 5389:   @i{body}
 5390: LOOP
 5391: @end example
 5392: 
 5393: This performs one iteration for every integer, starting from @i{start}
 5394: and up to, but excluding @i{limit}. The counter, or @i{index}, can be
 5395: accessed with @code{i}. For example, the loop:
 5396: @example
 5397: 10 0 ?DO
 5398:   i .
 5399: LOOP
 5400: @end example
 5401: @noindent
 5402: prints @code{0 1 2 3 4 5 6 7 8 9}
 5403: 
 5404: The index of the innermost loop can be accessed with @code{i}, the index
 5405: of the next loop with @code{j}, and the index of the third loop with
 5406: @code{k}.
 5407: 
 5408: 
 5409: doc-i
 5410: doc-j
 5411: doc-k
 5412: 
 5413: 
 5414: The loop control data are kept on the return stack, so there are some
 5415: restrictions on mixing return stack accesses and counted loop words. In
 5416: particuler, if you put values on the return stack outside the loop, you
 5417: cannot read them inside the loop@footnote{well, not in a way that is
 5418: portable.}. If you put values on the return stack within a loop, you
 5419: have to remove them before the end of the loop and before accessing the
 5420: index of the loop.
 5421: 
 5422: There are several variations on the counted loop:
 5423: 
 5424: @itemize @bullet
 5425: @item
 5426: @code{LEAVE} leaves the innermost counted loop immediately; execution
 5427: continues after the associated @code{LOOP} or @code{NEXT}. For example:
 5428: 
 5429: @example
 5430: 10 0 ?DO  i DUP . 3 = IF LEAVE THEN LOOP
 5431: @end example
 5432: prints @code{0 1 2 3}
 5433: 
 5434: 
 5435: @item
 5436: @code{UNLOOP} prepares for an abnormal loop exit, e.g., via
 5437: @code{EXIT}. @code{UNLOOP} removes the loop control parameters from the
 5438: return stack so @code{EXIT} can get to its return address. For example:
 5439: 
 5440: @example
 5441: : demo 10 0 ?DO i DUP . 3 = IF UNLOOP EXIT THEN LOOP ." Done" ;
 5442: @end example
 5443: prints @code{0 1 2 3}
 5444: 
 5445: 
 5446: @item
 5447: If @i{start} is greater than @i{limit}, a @code{?DO} loop is entered
 5448: (and @code{LOOP} iterates until they become equal by wrap-around
 5449: arithmetic). This behaviour is usually not what you want. Therefore,
 5450: Gforth offers @code{+DO} and @code{U+DO} (as replacements for
 5451: @code{?DO}), which do not enter the loop if @i{start} is greater than
 5452: @i{limit}; @code{+DO} is for signed loop parameters, @code{U+DO} for
 5453: unsigned loop parameters.
 5454: 
 5455: @item
 5456: @code{?DO} can be replaced by @code{DO}. @code{DO} always enters
 5457: the loop, independent of the loop parameters. Do not use @code{DO}, even
 5458: if you know that the loop is entered in any case. Such knowledge tends
 5459: to become invalid during maintenance of a program, and then the
 5460: @code{DO} will make trouble.
 5461: 
 5462: @item
 5463: @code{LOOP} can be replaced with @code{@i{n} +LOOP}; this updates the
 5464: index by @i{n} instead of by 1. The loop is terminated when the border
 5465: between @i{limit-1} and @i{limit} is crossed. E.g.:
 5466: 
 5467: @example
 5468: 4 0 +DO  i .  2 +LOOP
 5469: @end example
 5470: @noindent
 5471: prints @code{0 2}
 5472: 
 5473: @example
 5474: 4 1 +DO  i .  2 +LOOP
 5475: @end example
 5476: @noindent
 5477: prints @code{1 3}
 5478: 
 5479: @item
 5480: @cindex negative increment for counted loops
 5481: @cindex counted loops with negative increment
 5482: The behaviour of @code{@i{n} +LOOP} is peculiar when @i{n} is negative:
 5483: 
 5484: @example
 5485: -1 0 ?DO  i .  -1 +LOOP
 5486: @end example
 5487: @noindent
 5488: prints @code{0 -1}
 5489: 
 5490: @example
 5491: 0 0 ?DO  i .  -1 +LOOP
 5492: @end example
 5493: prints nothing.
 5494: 
 5495: Therefore we recommend avoiding @code{@i{n} +LOOP} with negative
 5496: @i{n}. One alternative is @code{@i{u} -LOOP}, which reduces the
 5497: index by @i{u} each iteration. The loop is terminated when the border
 5498: between @i{limit+1} and @i{limit} is crossed. Gforth also provides
 5499: @code{-DO} and @code{U-DO} for down-counting loops. E.g.:
 5500: 
 5501: @example
 5502: -2 0 -DO  i .  1 -LOOP
 5503: @end example
 5504: @noindent
 5505: prints @code{0 -1}
 5506: 
 5507: @example
 5508: -1 0 -DO  i .  1 -LOOP
 5509: @end example
 5510: @noindent
 5511: prints @code{0}
 5512: 
 5513: @example
 5514: 0 0 -DO  i .  1 -LOOP
 5515: @end example
 5516: @noindent
 5517: prints nothing.
 5518: 
 5519: @end itemize
 5520: 
 5521: Unfortunately, @code{+DO}, @code{U+DO}, @code{-DO}, @code{U-DO} and
 5522: @code{-LOOP} are not defined in ANS Forth. However, an implementation
 5523: for these words that uses only standard words is provided in
 5524: @file{compat/loops.fs}.
 5525: 
 5526: 
 5527: @cindex @code{FOR} loops
 5528: Another counted loop is:
 5529: @example
 5530: @i{n}
 5531: FOR
 5532:   @i{body}
 5533: NEXT
 5534: @end example
 5535: This is the preferred loop of native code compiler writers who are too
 5536: lazy to optimize @code{?DO} loops properly. This loop structure is not
 5537: defined in ANS Forth. In Gforth, this loop iterates @i{n+1} times;
 5538: @code{i} produces values starting with @i{n} and ending with 0. Other
 5539: Forth systems may behave differently, even if they support @code{FOR}
 5540: loops. To avoid problems, don't use @code{FOR} loops.
 5541: 
 5542: @node Arbitrary control structures, Calls and returns, Counted Loops, Control Structures
 5543: @subsection Arbitrary control structures
 5544: @cindex control structures, user-defined
 5545: 
 5546: @cindex control-flow stack
 5547: ANS Forth permits and supports using control structures in a non-nested
 5548: way. Information about incomplete control structures is stored on the
 5549: control-flow stack. This stack may be implemented on the Forth data
 5550: stack, and this is what we have done in Gforth.
 5551: 
 5552: @cindex @code{orig}, control-flow stack item
 5553: @cindex @code{dest}, control-flow stack item
 5554: An @i{orig} entry represents an unresolved forward branch, a @i{dest}
 5555: entry represents a backward branch target. A few words are the basis for
 5556: building any control structure possible (except control structures that
 5557: need storage, like calls, coroutines, and backtracking).
 5558: 
 5559: 
 5560: doc-if
 5561: doc-ahead
 5562: doc-then
 5563: doc-begin
 5564: doc-until
 5565: doc-again
 5566: doc-cs-pick
 5567: doc-cs-roll
 5568: 
 5569: 
 5570: The Standard words @code{CS-PICK} and @code{CS-ROLL} allow you to
 5571: manipulate the control-flow stack in a portable way. Without them, you
 5572: would need to know how many stack items are occupied by a control-flow
 5573: entry (many systems use one cell. In Gforth they currently take three,
 5574: but this may change in the future).
 5575: 
 5576: Some standard control structure words are built from these words:
 5577: 
 5578: 
 5579: doc-else
 5580: doc-while
 5581: doc-repeat
 5582: 
 5583: 
 5584: @noindent
 5585: Gforth adds some more control-structure words:
 5586: 
 5587: 
 5588: doc-endif
 5589: doc-?dup-if
 5590: doc-?dup-0=-if
 5591: 
 5592: 
 5593: @noindent
 5594: Counted loop words constitute a separate group of words:
 5595: 
 5596: 
 5597: doc-?do
 5598: doc-+do
 5599: doc-u+do
 5600: doc--do
 5601: doc-u-do
 5602: doc-do
 5603: doc-for
 5604: doc-loop
 5605: doc-+loop
 5606: doc--loop
 5607: doc-next
 5608: doc-leave
 5609: doc-?leave
 5610: doc-unloop
 5611: doc-done
 5612: 
 5613: 
 5614: The standard does not allow using @code{CS-PICK} and @code{CS-ROLL} on
 5615: @i{do-sys}. Gforth allows it, but it's your job to ensure that for
 5616: every @code{?DO} etc. there is exactly one @code{UNLOOP} on any path
 5617: through the definition (@code{LOOP} etc. compile an @code{UNLOOP} on the
 5618: fall-through path). Also, you have to ensure that all @code{LEAVE}s are
 5619: resolved (by using one of the loop-ending words or @code{DONE}).
 5620: 
 5621: @noindent
 5622: Another group of control structure words are:
 5623: 
 5624: 
 5625: doc-case
 5626: doc-endcase
 5627: doc-of
 5628: doc-endof
 5629: 
 5630: 
 5631: @i{case-sys} and @i{of-sys} cannot be processed using @code{CS-PICK} and
 5632: @code{CS-ROLL}.
 5633: 
 5634: @subsubsection Programming Style
 5635: @cindex control structures programming style
 5636: @cindex programming style, arbitrary control structures
 5637: 
 5638: In order to ensure readability we recommend that you do not create
 5639: arbitrary control structures directly, but define new control structure
 5640: words for the control structure you want and use these words in your
 5641: program. For example, instead of writing:
 5642: 
 5643: @example
 5644: BEGIN
 5645:   ...
 5646: IF [ 1 CS-ROLL ]
 5647:   ...
 5648: AGAIN THEN
 5649: @end example
 5650: 
 5651: @noindent
 5652: we recommend defining control structure words, e.g.,
 5653: 
 5654: @example
 5655: : WHILE ( DEST -- ORIG DEST )
 5656:  POSTPONE IF
 5657:  1 CS-ROLL ; immediate
 5658: 
 5659: : REPEAT ( orig dest -- )
 5660:  POSTPONE AGAIN
 5661:  POSTPONE THEN ; immediate
 5662: @end example
 5663: 
 5664: @noindent
 5665: and then using these to create the control structure:
 5666: 
 5667: @example
 5668: BEGIN
 5669:   ...
 5670: WHILE
 5671:   ...
 5672: REPEAT
 5673: @end example
 5674: 
 5675: That's much easier to read, isn't it? Of course, @code{REPEAT} and
 5676: @code{WHILE} are predefined, so in this example it would not be
 5677: necessary to define them.
 5678: 
 5679: @node Calls and returns, Exception Handling, Arbitrary control structures, Control Structures
 5680: @subsection Calls and returns
 5681: @cindex calling a definition
 5682: @cindex returning from a definition
 5683: 
 5684: @cindex recursive definitions
 5685: A definition can be called simply be writing the name of the definition
 5686: to be called. Normally a definition is invisible during its own
 5687: definition. If you want to write a directly recursive definition, you
 5688: can use @code{recursive} to make the current definition visible, or
 5689: @code{recurse} to call the current definition directly.
 5690: 
 5691: 
 5692: doc-recursive
 5693: doc-recurse
 5694: 
 5695: 
 5696: @comment TODO add example of the two recursion methods
 5697: @quotation
 5698: @progstyle
 5699: I prefer using @code{recursive} to @code{recurse}, because calling the
 5700: definition by name is more descriptive (if the name is well-chosen) than
 5701: the somewhat cryptic @code{recurse}.  E.g., in a quicksort
 5702: implementation, it is much better to read (and think) ``now sort the
 5703: partitions'' than to read ``now do a recursive call''.
 5704: @end quotation
 5705: 
 5706: For mutual recursion, use @code{Defer}red words, like this:
 5707: 
 5708: @example
 5709: Defer foo
 5710: 
 5711: : bar ( ... -- ... )
 5712:  ... foo ... ;
 5713: 
 5714: :noname ( ... -- ... )
 5715:  ... bar ... ;
 5716: IS foo
 5717: @end example
 5718: 
 5719: Deferred words are discussed in more detail in @ref{Deferred Words}.
 5720: 
 5721: The current definition returns control to the calling definition when
 5722: the end of the definition is reached or @code{EXIT} is encountered.
 5723: 
 5724: doc-exit
 5725: doc-;s
 5726: 
 5727: 
 5728: @node Exception Handling,  , Calls and returns, Control Structures
 5729: @subsection Exception Handling
 5730: @cindex exceptions
 5731: 
 5732: @c quit is a very bad idea for error handling, 
 5733: @c because it does not translate into a THROW
 5734: @c it also does not belong into this chapter
 5735: 
 5736: If a word detects an error condition that it cannot handle, it can
 5737: @code{throw} an exception.  In the simplest case, this will terminate
 5738: your program, and report an appropriate error.
 5739: 
 5740: doc-throw
 5741: 
 5742: @code{Throw} consumes a cell-sized error number on the stack. There are
 5743: some predefined error numbers in ANS Forth (see @file{errors.fs}).  In
 5744: Gforth (and most other systems) you can use the iors produced by various
 5745: words as error numbers (e.g., a typical use of @code{allocate} is
 5746: @code{allocate throw}).  Gforth also provides the word @code{exception}
 5747: to define your own error numbers (with decent error reporting); an ANS
 5748: Forth version of this word (but without the error messages) is available
 5749: in @code{compat/except.fs}.  And finally, you can use your own error
 5750: numbers (anything outside the range -4095..0), but won't get nice error
 5751: messages, only numbers.  For example, try:
 5752: 
 5753: @example
 5754: -10 throw                    \ ANS defined
 5755: -267 throw                   \ system defined
 5756: s" my error" exception throw \ user defined
 5757: 7 throw                      \ arbitrary number
 5758: @end example
 5759: 
 5760: doc---exception-exception
 5761: 
 5762: A common idiom to @code{THROW} a specific error if a flag is true is
 5763: this:
 5764: 
 5765: @example
 5766: @code{( flag ) 0<> @i{errno} and throw}
 5767: @end example
 5768: 
 5769: Your program can provide exception handlers to catch exceptions.  An
 5770: exception handler can be used to correct the problem, or to clean up
 5771: some data structures and just throw the exception to the next exception
 5772: handler.  Note that @code{throw} jumps to the dynamically innermost
 5773: exception handler.  The system's exception handler is outermost, and just
 5774: prints an error and restarts command-line interpretation (or, in batch
 5775: mode (i.e., while processing the shell command line), leaves Gforth).
 5776: 
 5777: The ANS Forth way to catch exceptions is @code{catch}:
 5778: 
 5779: doc-catch
 5780: doc-nothrow
 5781: 
 5782: The most common use of exception handlers is to clean up the state when
 5783: an error happens.  E.g.,
 5784: 
 5785: @example
 5786: base @ >r hex \ actually the hex should be inside foo, or we h
 5787: ['] foo catch ( nerror|0 )
 5788: r> base !
 5789: ( nerror|0 ) throw \ pass it on
 5790: @end example
 5791: 
 5792: A use of @code{catch} for handling the error @code{myerror} might look
 5793: like this:
 5794: 
 5795: @example
 5796: ['] foo catch
 5797: CASE
 5798:   myerror OF ... ( do something about it ) nothrow ENDOF
 5799:   dup throw \ default: pass other errors on, do nothing on non-errors
 5800: ENDCASE
 5801: @end example
 5802: 
 5803: Having to wrap the code into a separate word is often cumbersome,
 5804: therefore Gforth provides an alternative syntax:
 5805: 
 5806: @example
 5807: TRY
 5808:   @i{code1}
 5809:   IFERROR
 5810:     @i{code2}
 5811:   THEN
 5812:   @i{code3}
 5813: ENDTRY
 5814: @end example
 5815: 
 5816: This performs @i{code1}.  If @i{code1} completes normally, execution
 5817: continues with @i{code3}.  If @i{code1} or there is an exception
 5818: before @code{endtry}, the stacks are reset to the state during
 5819: @code{try}, the throw value is pushed on the data stack, and execution
 5820: constinues at @i{code2}, and finally falls through the @i{code3}.
 5821: 
 5822: doc-try
 5823: doc-endtry
 5824: doc-iferror
 5825: 
 5826: If you don't need @i{code2}, you can write @code{restore} instead of
 5827: @code{iferror then}:
 5828: 
 5829: @example
 5830: TRY
 5831:   @i{code1}
 5832: RESTORE
 5833:   @i{code3}
 5834: ENDTRY
 5835: @end example
 5836: 
 5837: @cindex unwind-protect
 5838: The cleanup example from above in this syntax:
 5839: 
 5840: @example
 5841: base @@ @{ oldbase @}
 5842: TRY
 5843:   hex foo \ now the hex is placed correctly
 5844:   0       \ value for throw
 5845: RESTORE
 5846:   oldbase base !
 5847: ENDTRY
 5848: throw
 5849: @end example
 5850: 
 5851: An additional advantage of this variant is that an exception between
 5852: @code{restore} and @code{endtry} (e.g., from the user pressing
 5853: @kbd{Ctrl-C}) restarts the execution of the code after @code{restore},
 5854: so the base will be restored under all circumstances.
 5855: 
 5856: However, you have to ensure that this code does not cause an exception
 5857: itself, otherwise the @code{iferror}/@code{restore} code will loop.
 5858: Moreover, you should also make sure that the stack contents needed by
 5859: the @code{iferror}/@code{restore} code exist everywhere between
 5860: @code{try} and @code{endtry}; in our example this is achived by
 5861: putting the data in a local before the @code{try} (you cannot use the
 5862: return stack because the exception frame (@i{sys1}) is in the way
 5863: there).
 5864: 
 5865: This kind of usage corresponds to Lisp's @code{unwind-protect}.
 5866: 
 5867: @cindex @code{recover} (old Gforth versions)
 5868: If you do not want this exception-restarting behaviour, you achieve
 5869: this as follows:
 5870: 
 5871: @example
 5872: TRY
 5873:   @i{code1}
 5874: ENDTRY-IFERROR
 5875:   @i{code2}
 5876: THEN
 5877: @end example
 5878: 
 5879: If there is an exception in @i{code1}, then @i{code2} is executed,
 5880: otherwise execution continues behind the @code{then} (or in a possible
 5881: @code{else} branch).  This corresponds to the construct
 5882: 
 5883: @example
 5884: TRY
 5885:   @i{code1}
 5886: RECOVER
 5887:   @i{code2}
 5888: ENDTRY
 5889: @end example
 5890: 
 5891: in Gforth before version 0.7.  So you can directly replace
 5892: @code{recover}-using code; however, we recommend that you check if it
 5893: would not be better to use one of the other @code{try} variants while
 5894: you are at it.
 5895: 
 5896: To ease the transition, Gforth provides two compatibility files:
 5897: @file{endtry-iferror.fs} provides the @code{try ... endtry-iferror
 5898: ... then} syntax (but not @code{iferror} or @code{restore}) for old
 5899: systems; @file{recover-endtry.fs} provides the @code{try ... recover
 5900: ... endtry} syntax on new systems, so you can use that file as a
 5901: stopgap to run old programs.  Both files work on any system (they just
 5902: do nothing if the system already has the syntax it implements), so you
 5903: can unconditionally @code{require} one of these files, even if you use
 5904: a mix old and new systems.
 5905: 
 5906: doc-restore
 5907: doc-endtry-iferror
 5908: 
 5909: Here's the error handling example:
 5910: 
 5911: @example
 5912: TRY
 5913:   foo
 5914: ENDTRY-IFERROR
 5915:   CASE
 5916:     myerror OF ... ( do something about it ) nothrow ENDOF
 5917:     throw \ pass other errors on
 5918:   ENDCASE
 5919: THEN
 5920: @end example
 5921: 
 5922: @progstyle
 5923: As usual, you should ensure that the stack depth is statically known at
 5924: the end: either after the @code{throw} for passing on errors, or after
 5925: the @code{ENDTRY} (or, if you use @code{catch}, after the end of the
 5926: selection construct for handling the error).
 5927: 
 5928: There are two alternatives to @code{throw}: @code{Abort"} is conditional
 5929: and you can provide an error message.  @code{Abort} just produces an
 5930: ``Aborted'' error.
 5931: 
 5932: The problem with these words is that exception handlers cannot
 5933: differentiate between different @code{abort"}s; they just look like
 5934: @code{-2 throw} to them (the error message cannot be accessed by
 5935: standard programs).  Similar @code{abort} looks like @code{-1 throw} to
 5936: exception handlers.
 5937: 
 5938: doc-abort"
 5939: doc-abort
 5940: 
 5941: 
 5942: 
 5943: @c -------------------------------------------------------------
 5944: @node Defining Words, Interpretation and Compilation Semantics, Control Structures, Words
 5945: @section Defining Words
 5946: @cindex defining words
 5947: 
 5948: Defining words are used to extend Forth by creating new entries in the dictionary.
 5949: 
 5950: @menu
 5951: * CREATE::                      
 5952: * Variables::                   Variables and user variables
 5953: * Constants::                   
 5954: * Values::                      Initialised variables
 5955: * Colon Definitions::           
 5956: * Anonymous Definitions::       Definitions without names
 5957: * Supplying names::             Passing definition names as strings
 5958: * User-defined Defining Words::  
 5959: * Deferred Words::              Allow forward references
 5960: * Aliases::                     
 5961: @end menu
 5962: 
 5963: @node CREATE, Variables, Defining Words, Defining Words
 5964: @subsection @code{CREATE}
 5965: @cindex simple defining words
 5966: @cindex defining words, simple
 5967: 
 5968: Defining words are used to create new entries in the dictionary. The
 5969: simplest defining word is @code{CREATE}. @code{CREATE} is used like
 5970: this:
 5971: 
 5972: @example
 5973: CREATE new-word1
 5974: @end example
 5975: 
 5976: @code{CREATE} is a parsing word, i.e., it takes an argument from the
 5977: input stream (@code{new-word1} in our example).  It generates a
 5978: dictionary entry for @code{new-word1}. When @code{new-word1} is
 5979: executed, all that it does is leave an address on the stack. The address
 5980: represents the value of the data space pointer (@code{HERE}) at the time
 5981: that @code{new-word1} was defined. Therefore, @code{CREATE} is a way of
 5982: associating a name with the address of a region of memory.
 5983: 
 5984: doc-create
 5985: 
 5986: Note that in ANS Forth guarantees only for @code{create} that its body
 5987: is in dictionary data space (i.e., where @code{here}, @code{allot}
 5988: etc. work, @pxref{Dictionary allocation}).  Also, in ANS Forth only
 5989: @code{create}d words can be modified with @code{does>}
 5990: (@pxref{User-defined Defining Words}).  And in ANS Forth @code{>body}
 5991: can only be applied to @code{create}d words.
 5992: 
 5993: By extending this example to reserve some memory in data space, we end
 5994: up with something like a @i{variable}. Here are two different ways to do
 5995: it:
 5996: 
 5997: @example
 5998: CREATE new-word2 1 cells allot  \ reserve 1 cell - initial value undefined
 5999: CREATE new-word3 4 ,            \ reserve 1 cell and initialise it (to 4)
 6000: @end example
 6001: 
 6002: The variable can be examined and modified using @code{@@} (``fetch'') and
 6003: @code{!} (``store'') like this:
 6004: 
 6005: @example
 6006: new-word2 @@ .      \ get address, fetch from it and display
 6007: 1234 new-word2 !   \ new value, get address, store to it
 6008: @end example
 6009: 
 6010: @cindex arrays
 6011: A similar mechanism can be used to create arrays. For example, an
 6012: 80-character text input buffer:
 6013: 
 6014: @example
 6015: CREATE text-buf 80 chars allot
 6016: 
 6017: text-buf 0 chars + c@@ \ the 1st character (offset 0)
 6018: text-buf 3 chars + c@@ \ the 4th character (offset 3)
 6019: @end example
 6020: 
 6021: You can build arbitrarily complex data structures by allocating
 6022: appropriate areas of memory. For further discussions of this, and to
 6023: learn about some Gforth tools that make it easier,
 6024: @xref{Structures}.
 6025: 
 6026: 
 6027: @node Variables, Constants, CREATE, Defining Words
 6028: @subsection Variables
 6029: @cindex variables
 6030: 
 6031: The previous section showed how a sequence of commands could be used to
 6032: generate a variable.  As a final refinement, the whole code sequence can
 6033: be wrapped up in a defining word (pre-empting the subject of the next
 6034: section), making it easier to create new variables:
 6035: 
 6036: @example
 6037: : myvariableX ( "name" -- a-addr ) CREATE 1 cells allot ;
 6038: : myvariable0 ( "name" -- a-addr ) CREATE 0 , ;
 6039: 
 6040: myvariableX foo \ variable foo starts off with an unknown value
 6041: myvariable0 joe \ whilst joe is initialised to 0
 6042: 
 6043: 45 3 * foo !   \ set foo to 135
 6044: 1234 joe !     \ set joe to 1234
 6045: 3 joe +!       \ increment joe by 3.. to 1237
 6046: @end example
 6047: 
 6048: Not surprisingly, there is no need to define @code{myvariable}, since
 6049: Forth already has a definition @code{Variable}. ANS Forth does not
 6050: guarantee that a @code{Variable} is initialised when it is created
 6051: (i.e., it may behave like @code{myvariableX}). In contrast, Gforth's
 6052: @code{Variable} initialises the variable to 0 (i.e., it behaves exactly
 6053: like @code{myvariable0}). Forth also provides @code{2Variable} and
 6054: @code{fvariable} for double and floating-point variables, respectively
 6055: -- they are initialised to 0. and 0e in Gforth. If you use a @code{Variable} to
 6056: store a boolean, you can use @code{on} and @code{off} to toggle its
 6057: state.
 6058: 
 6059: doc-variable
 6060: doc-2variable
 6061: doc-fvariable
 6062: 
 6063: @cindex user variables
 6064: @cindex user space
 6065: The defining word @code{User} behaves in the same way as @code{Variable}.
 6066: The difference is that it reserves space in @i{user (data) space} rather
 6067: than normal data space. In a Forth system that has a multi-tasker, each
 6068: task has its own set of user variables.
 6069: 
 6070: doc-user
 6071: @c doc-udp
 6072: @c doc-uallot
 6073: 
 6074: @comment TODO is that stuff about user variables strictly correct? Is it
 6075: @comment just terminal tasks that have user variables?
 6076: @comment should document tasker.fs (with some examples) elsewhere
 6077: @comment in this manual, then expand on user space and user variables.
 6078: 
 6079: @node Constants, Values, Variables, Defining Words
 6080: @subsection Constants
 6081: @cindex constants
 6082: 
 6083: @code{Constant} allows you to declare a fixed value and refer to it by
 6084: name. For example:
 6085: 
 6086: @example
 6087: 12 Constant INCHES-PER-FOOT
 6088: 3E+08 fconstant SPEED-O-LIGHT
 6089: @end example
 6090: 
 6091: A @code{Variable} can be both read and written, so its run-time
 6092: behaviour is to supply an address through which its current value can be
 6093: manipulated. In contrast, the value of a @code{Constant} cannot be
 6094: changed once it has been declared@footnote{Well, often it can be -- but
 6095: not in a Standard, portable way. It's safer to use a @code{Value} (read
 6096: on).} so it's not necessary to supply the address -- it is more
 6097: efficient to return the value of the constant directly. That's exactly
 6098: what happens; the run-time effect of a constant is to put its value on
 6099: the top of the stack (You can find one
 6100: way of implementing @code{Constant} in @ref{User-defined Defining Words}).
 6101: 
 6102: Forth also provides @code{2Constant} and @code{fconstant} for defining
 6103: double and floating-point constants, respectively.
 6104: 
 6105: doc-constant
 6106: doc-2constant
 6107: doc-fconstant
 6108: 
 6109: @c that's too deep, and it's not necessarily true for all ANS Forths. - anton
 6110: @c nac-> How could that not be true in an ANS Forth? You can't define a
 6111: @c constant, use it and then delete the definition of the constant..
 6112: 
 6113: @c anton->An ANS Forth system can compile a constant to a literal; On
 6114: @c decompilation you would see only the number, just as if it had been used
 6115: @c in the first place.  The word will stay, of course, but it will only be
 6116: @c used by the text interpreter (no run-time duties, except when it is 
 6117: @c POSTPONEd or somesuch).
 6118: 
 6119: @c nac:
 6120: @c I agree that it's rather deep, but IMO it is an important difference
 6121: @c relative to other programming languages.. often it's annoying: it
 6122: @c certainly changes my programming style relative to C.
 6123: 
 6124: @c anton: In what way?
 6125: 
 6126: Constants in Forth behave differently from their equivalents in other
 6127: programming languages. In other languages, a constant (such as an EQU in
 6128: assembler or a #define in C) only exists at compile-time; in the
 6129: executable program the constant has been translated into an absolute
 6130: number and, unless you are using a symbolic debugger, it's impossible to
 6131: know what abstract thing that number represents. In Forth a constant has
 6132: an entry in the header space and remains there after the code that uses
 6133: it has been defined. In fact, it must remain in the dictionary since it
 6134: has run-time duties to perform. For example:
 6135: 
 6136: @example
 6137: 12 Constant INCHES-PER-FOOT
 6138: : FEET-TO-INCHES ( n1 -- n2 ) INCHES-PER-FOOT * ;
 6139: @end example
 6140: 
 6141: @cindex in-lining of constants
 6142: When @code{FEET-TO-INCHES} is executed, it will in turn execute the xt
 6143: associated with the constant @code{INCHES-PER-FOOT}. If you use
 6144: @code{see} to decompile the definition of @code{FEET-TO-INCHES}, you can
 6145: see that it makes a call to @code{INCHES-PER-FOOT}. Some Forth compilers
 6146: attempt to optimise constants by in-lining them where they are used. You
 6147: can force Gforth to in-line a constant like this:
 6148: 
 6149: @example
 6150: : FEET-TO-INCHES ( n1 -- n2 ) [ INCHES-PER-FOOT ] LITERAL * ;
 6151: @end example
 6152: 
 6153: If you use @code{see} to decompile @i{this} version of
 6154: @code{FEET-TO-INCHES}, you can see that @code{INCHES-PER-FOOT} is no
 6155: longer present. To understand how this works, read
 6156: @ref{Interpret/Compile states}, and @ref{Literals}.
 6157: 
 6158: In-lining constants in this way might improve execution time
 6159: fractionally, and can ensure that a constant is now only referenced at
 6160: compile-time. However, the definition of the constant still remains in
 6161: the dictionary. Some Forth compilers provide a mechanism for controlling
 6162: a second dictionary for holding transient words such that this second
 6163: dictionary can be deleted later in order to recover memory
 6164: space. However, there is no standard way of doing this.
 6165: 
 6166: 
 6167: @node Values, Colon Definitions, Constants, Defining Words
 6168: @subsection Values
 6169: @cindex values
 6170: 
 6171: A @code{Value} behaves like a @code{Constant}, but it can be changed.
 6172: @code{TO} is a parsing word that changes a @code{Values}.  In Gforth
 6173: (not in ANS Forth) you can access (and change) a @code{value} also with
 6174: @code{>body}.
 6175: 
 6176: Here are some
 6177: examples:
 6178: 
 6179: @example
 6180: 12 Value APPLES     \ Define APPLES with an initial value of 12
 6181: 34 TO APPLES        \ Change the value of APPLES. TO is a parsing word
 6182: 1 ' APPLES >body +! \ Increment APPLES.  Non-standard usage.
 6183: APPLES              \ puts 35 on the top of the stack.
 6184: @end example
 6185: 
 6186: doc-value
 6187: doc-to
 6188: 
 6189: 
 6190: 
 6191: @node Colon Definitions, Anonymous Definitions, Values, Defining Words
 6192: @subsection Colon Definitions
 6193: @cindex colon definitions
 6194: 
 6195: @example
 6196: : name ( ... -- ... )
 6197:     word1 word2 word3 ;
 6198: @end example
 6199: 
 6200: @noindent
 6201: Creates a word called @code{name} that, upon execution, executes
 6202: @code{word1 word2 word3}. @code{name} is a @dfn{(colon) definition}.
 6203: 
 6204: The explanation above is somewhat superficial. For simple examples of
 6205: colon definitions see @ref{Your first definition}.  For an in-depth
 6206: discussion of some of the issues involved, @xref{Interpretation and
 6207: Compilation Semantics}.
 6208: 
 6209: doc-:
 6210: doc-;
 6211: 
 6212: 
 6213: @node Anonymous Definitions, Supplying names, Colon Definitions, Defining Words
 6214: @subsection Anonymous Definitions
 6215: @cindex colon definitions
 6216: @cindex defining words without name
 6217: 
 6218: Sometimes you want to define an @dfn{anonymous word}; a word without a
 6219: name. You can do this with:
 6220: 
 6221: doc-:noname
 6222: 
 6223: This leaves the execution token for the word on the stack after the
 6224: closing @code{;}. Here's an example in which a deferred word is
 6225: initialised with an @code{xt} from an anonymous colon definition:
 6226: 
 6227: @example
 6228: Defer deferred
 6229: :noname ( ... -- ... )
 6230:   ... ;
 6231: IS deferred
 6232: @end example
 6233: 
 6234: @noindent
 6235: Gforth provides an alternative way of doing this, using two separate
 6236: words:
 6237: 
 6238: doc-noname
 6239: @cindex execution token of last defined word
 6240: doc-latestxt
 6241: 
 6242: @noindent
 6243: The previous example can be rewritten using @code{noname} and
 6244: @code{latestxt}:
 6245: 
 6246: @example
 6247: Defer deferred
 6248: noname : ( ... -- ... )
 6249:   ... ;
 6250: latestxt IS deferred
 6251: @end example
 6252: 
 6253: @noindent
 6254: @code{noname} works with any defining word, not just @code{:}.
 6255: 
 6256: @code{latestxt} also works when the last word was not defined as
 6257: @code{noname}.  It does not work for combined words, though.  It also has
 6258: the useful property that is is valid as soon as the header for a
 6259: definition has been built. Thus:
 6260: 
 6261: @example
 6262: latestxt . : foo [ latestxt . ] ; ' foo .
 6263: @end example
 6264: 
 6265: @noindent
 6266: prints 3 numbers; the last two are the same.
 6267: 
 6268: @node Supplying names, User-defined Defining Words, Anonymous Definitions, Defining Words
 6269: @subsection Supplying the name of a defined word
 6270: @cindex names for defined words
 6271: @cindex defining words, name given in a string
 6272: 
 6273: By default, a defining word takes the name for the defined word from the
 6274: input stream. Sometimes you want to supply the name from a string. You
 6275: can do this with:
 6276: 
 6277: doc-nextname
 6278: 
 6279: For example:
 6280: 
 6281: @example
 6282: s" foo" nextname create
 6283: @end example
 6284: 
 6285: @noindent
 6286: is equivalent to:
 6287: 
 6288: @example
 6289: create foo
 6290: @end example
 6291: 
 6292: @noindent
 6293: @code{nextname} works with any defining word.
 6294: 
 6295: 
 6296: @node User-defined Defining Words, Deferred Words, Supplying names, Defining Words
 6297: @subsection User-defined Defining Words
 6298: @cindex user-defined defining words
 6299: @cindex defining words, user-defined
 6300: 
 6301: You can create a new defining word by wrapping defining-time code around
 6302: an existing defining word and putting the sequence in a colon
 6303: definition. 
 6304: 
 6305: @c anton: This example is very complex and leads in a quite different
 6306: @c direction from the CREATE-DOES> stuff that follows.  It should probably
 6307: @c be done elsewhere, or as a subsubsection of this subsection (or as a
 6308: @c subsection of Defining Words)
 6309: 
 6310: For example, suppose that you have a word @code{stats} that
 6311: gathers statistics about colon definitions given the @i{xt} of the
 6312: definition, and you want every colon definition in your application to
 6313: make a call to @code{stats}. You can define and use a new version of
 6314: @code{:} like this:
 6315: 
 6316: @example
 6317: : stats ( xt -- ) DUP ." (Gathering statistics for " . ." )"
 6318:   ... ;  \ other code
 6319: 
 6320: : my: : latestxt postpone literal ['] stats compile, ;
 6321: 
 6322: my: foo + - ;
 6323: @end example
 6324: 
 6325: When @code{foo} is defined using @code{my:} these steps occur:
 6326: 
 6327: @itemize @bullet
 6328: @item
 6329: @code{my:} is executed.
 6330: @item
 6331: The @code{:} within the definition (the one between @code{my:} and
 6332: @code{latestxt}) is executed, and does just what it always does; it parses
 6333: the input stream for a name, builds a dictionary header for the name
 6334: @code{foo} and switches @code{state} from interpret to compile.
 6335: @item
 6336: The word @code{latestxt} is executed. It puts the @i{xt} for the word that is
 6337: being defined -- @code{foo} -- onto the stack.
 6338: @item
 6339: The code that was produced by @code{postpone literal} is executed; this
 6340: causes the value on the stack to be compiled as a literal in the code
 6341: area of @code{foo}.
 6342: @item
 6343: The code @code{['] stats} compiles a literal into the definition of
 6344: @code{my:}. When @code{compile,} is executed, that literal -- the
 6345: execution token for @code{stats} -- is layed down in the code area of
 6346: @code{foo} , following the literal@footnote{Strictly speaking, the
 6347: mechanism that @code{compile,} uses to convert an @i{xt} into something
 6348: in the code area is implementation-dependent. A threaded implementation
 6349: might spit out the execution token directly whilst another
 6350: implementation might spit out a native code sequence.}.
 6351: @item
 6352: At this point, the execution of @code{my:} is complete, and control
 6353: returns to the text interpreter. The text interpreter is in compile
 6354: state, so subsequent text @code{+ -} is compiled into the definition of
 6355: @code{foo} and the @code{;} terminates the definition as always.
 6356: @end itemize
 6357: 
 6358: You can use @code{see} to decompile a word that was defined using
 6359: @code{my:} and see how it is different from a normal @code{:}
 6360: definition. For example:
 6361: 
 6362: @example
 6363: : bar + - ;  \ like foo but using : rather than my:
 6364: see bar
 6365: : bar
 6366:   + - ;
 6367: see foo
 6368: : foo
 6369:   107645672 stats + - ;
 6370: 
 6371: \ use ' foo . to show that 107645672 is the xt for foo
 6372: @end example
 6373: 
 6374: You can use techniques like this to make new defining words in terms of
 6375: @i{any} existing defining word.
 6376: 
 6377: 
 6378: @cindex defining defining words
 6379: @cindex @code{CREATE} ... @code{DOES>}
 6380: If you want the words defined with your defining words to behave
 6381: differently from words defined with standard defining words, you can
 6382: write your defining word like this:
 6383: 
 6384: @example
 6385: : def-word ( "name" -- )
 6386:     CREATE @i{code1}
 6387: DOES> ( ... -- ... )
 6388:     @i{code2} ;
 6389: 
 6390: def-word name
 6391: @end example
 6392: 
 6393: @cindex child words
 6394: This fragment defines a @dfn{defining word} @code{def-word} and then
 6395: executes it.  When @code{def-word} executes, it @code{CREATE}s a new
 6396: word, @code{name}, and executes the code @i{code1}. The code @i{code2}
 6397: is not executed at this time. The word @code{name} is sometimes called a
 6398: @dfn{child} of @code{def-word}.
 6399: 
 6400: When you execute @code{name}, the address of the body of @code{name} is
 6401: put on the data stack and @i{code2} is executed (the address of the body
 6402: of @code{name} is the address @code{HERE} returns immediately after the
 6403: @code{CREATE}, i.e., the address a @code{create}d word returns by
 6404: default).
 6405: 
 6406: @c anton:
 6407: @c www.dictionary.com says:
 6408: @c at·a·vism: 1.The reappearance of a characteristic in an organism after
 6409: @c several generations of absence, usually caused by the chance
 6410: @c recombination of genes.  2.An individual or a part that exhibits
 6411: @c atavism. Also called throwback.  3.The return of a trait or recurrence
 6412: @c of previous behavior after a period of absence.
 6413: @c
 6414: @c Doesn't seem to fit.
 6415: 
 6416: @c @cindex atavism in child words
 6417: You can use @code{def-word} to define a set of child words that behave
 6418: similarly; they all have a common run-time behaviour determined by
 6419: @i{code2}. Typically, the @i{code1} sequence builds a data area in the
 6420: body of the child word. The structure of the data is common to all
 6421: children of @code{def-word}, but the data values are specific -- and
 6422: private -- to each child word. When a child word is executed, the
 6423: address of its private data area is passed as a parameter on TOS to be
 6424: used and manipulated@footnote{It is legitimate both to read and write to
 6425: this data area.} by @i{code2}.
 6426: 
 6427: The two fragments of code that make up the defining words act (are
 6428: executed) at two completely separate times:
 6429: 
 6430: @itemize @bullet
 6431: @item
 6432: At @i{define time}, the defining word executes @i{code1} to generate a
 6433: child word
 6434: @item
 6435: At @i{child execution time}, when a child word is invoked, @i{code2}
 6436: is executed, using parameters (data) that are private and specific to
 6437: the child word.
 6438: @end itemize
 6439: 
 6440: Another way of understanding the behaviour of @code{def-word} and
 6441: @code{name} is to say that, if you make the following definitions:
 6442: @example
 6443: : def-word1 ( "name" -- )
 6444:     CREATE @i{code1} ;
 6445: 
 6446: : action1 ( ... -- ... )
 6447:     @i{code2} ;
 6448: 
 6449: def-word1 name1
 6450: @end example
 6451: 
 6452: @noindent
 6453: Then using @code{name1 action1} is equivalent to using @code{name}.
 6454: 
 6455: The classic example is that you can define @code{CONSTANT} in this way:
 6456: 
 6457: @example
 6458: : CONSTANT ( w "name" -- )
 6459:     CREATE ,
 6460: DOES> ( -- w )
 6461:     @@ ;
 6462: @end example
 6463: 
 6464: @comment There is a beautiful description of how this works and what
 6465: @comment it does in the Forthwrite 100th edition.. as well as an elegant
 6466: @comment commentary on the Counting Fruits problem.
 6467: 
 6468: When you create a constant with @code{5 CONSTANT five}, a set of
 6469: define-time actions take place; first a new word @code{five} is created,
 6470: then the value 5 is laid down in the body of @code{five} with
 6471: @code{,}. When @code{five} is executed, the address of the body is put on
 6472: the stack, and @code{@@} retrieves the value 5. The word @code{five} has
 6473: no code of its own; it simply contains a data field and a pointer to the
 6474: code that follows @code{DOES>} in its defining word. That makes words
 6475: created in this way very compact.
 6476: 
 6477: The final example in this section is intended to remind you that space
 6478: reserved in @code{CREATE}d words is @i{data} space and therefore can be
 6479: both read and written by a Standard program@footnote{Exercise: use this
 6480: example as a starting point for your own implementation of @code{Value}
 6481: and @code{TO} -- if you get stuck, investigate the behaviour of @code{'} and
 6482: @code{[']}.}:
 6483: 
 6484: @example
 6485: : foo ( "name" -- )
 6486:     CREATE -1 ,
 6487: DOES> ( -- )
 6488:     @@ . ;
 6489: 
 6490: foo first-word
 6491: foo second-word
 6492: 
 6493: 123 ' first-word >BODY !
 6494: @end example
 6495: 
 6496: If @code{first-word} had been a @code{CREATE}d word, we could simply
 6497: have executed it to get the address of its data field. However, since it
 6498: was defined to have @code{DOES>} actions, its execution semantics are to
 6499: perform those @code{DOES>} actions. To get the address of its data field
 6500: it's necessary to use @code{'} to get its xt, then @code{>BODY} to
 6501: translate the xt into the address of the data field.  When you execute
 6502: @code{first-word}, it will display @code{123}. When you execute
 6503: @code{second-word} it will display @code{-1}.
 6504: 
 6505: @cindex stack effect of @code{DOES>}-parts
 6506: @cindex @code{DOES>}-parts, stack effect
 6507: In the examples above the stack comment after the @code{DOES>} specifies
 6508: the stack effect of the defined words, not the stack effect of the
 6509: following code (the following code expects the address of the body on
 6510: the top of stack, which is not reflected in the stack comment). This is
 6511: the convention that I use and recommend (it clashes a bit with using
 6512: locals declarations for stack effect specification, though).
 6513: 
 6514: @menu
 6515: * CREATE..DOES> applications::  
 6516: * CREATE..DOES> details::       
 6517: * Advanced does> usage example::  
 6518: * Const-does>::                 
 6519: @end menu
 6520: 
 6521: @node CREATE..DOES> applications, CREATE..DOES> details, User-defined Defining Words, User-defined Defining Words
 6522: @subsubsection Applications of @code{CREATE..DOES>}
 6523: @cindex @code{CREATE} ... @code{DOES>}, applications
 6524: 
 6525: You may wonder how to use this feature. Here are some usage patterns:
 6526: 
 6527: @cindex factoring similar colon definitions
 6528: When you see a sequence of code occurring several times, and you can
 6529: identify a meaning, you will factor it out as a colon definition. When
 6530: you see similar colon definitions, you can factor them using
 6531: @code{CREATE..DOES>}. E.g., an assembler usually defines several words
 6532: that look very similar:
 6533: @example
 6534: : ori, ( reg-target reg-source n -- )
 6535:     0 asm-reg-reg-imm ;
 6536: : andi, ( reg-target reg-source n -- )
 6537:     1 asm-reg-reg-imm ;
 6538: @end example
 6539: 
 6540: @noindent
 6541: This could be factored with:
 6542: @example
 6543: : reg-reg-imm ( op-code -- )
 6544:     CREATE ,
 6545: DOES> ( reg-target reg-source n -- )
 6546:     @@ asm-reg-reg-imm ;
 6547: 
 6548: 0 reg-reg-imm ori,
 6549: 1 reg-reg-imm andi,
 6550: @end example
 6551: 
 6552: @cindex currying
 6553: Another view of @code{CREATE..DOES>} is to consider it as a crude way to
 6554: supply a part of the parameters for a word (known as @dfn{currying} in
 6555: the functional language community). E.g., @code{+} needs two
 6556: parameters. Creating versions of @code{+} with one parameter fixed can
 6557: be done like this:
 6558: 
 6559: @example
 6560: : curry+ ( n1 "name" -- )
 6561:     CREATE ,
 6562: DOES> ( n2 -- n1+n2 )
 6563:     @@ + ;
 6564: 
 6565:  3 curry+ 3+
 6566: -2 curry+ 2-
 6567: @end example
 6568: 
 6569: 
 6570: @node CREATE..DOES> details, Advanced does> usage example, CREATE..DOES> applications, User-defined Defining Words
 6571: @subsubsection The gory details of @code{CREATE..DOES>}
 6572: @cindex @code{CREATE} ... @code{DOES>}, details
 6573: 
 6574: doc-does>
 6575: 
 6576: @cindex @code{DOES>} in a separate definition
 6577: This means that you need not use @code{CREATE} and @code{DOES>} in the
 6578: same definition; you can put the @code{DOES>}-part in a separate
 6579: definition. This allows us to, e.g., select among different @code{DOES>}-parts:
 6580: @example
 6581: : does1 
 6582: DOES> ( ... -- ... )
 6583:     ... ;
 6584: 
 6585: : does2
 6586: DOES> ( ... -- ... )
 6587:     ... ;
 6588: 
 6589: : def-word ( ... -- ... )
 6590:     create ...
 6591:     IF
 6592:        does1
 6593:     ELSE
 6594:        does2
 6595:     ENDIF ;
 6596: @end example
 6597: 
 6598: In this example, the selection of whether to use @code{does1} or
 6599: @code{does2} is made at definition-time; at the time that the child word is
 6600: @code{CREATE}d.
 6601: 
 6602: @cindex @code{DOES>} in interpretation state
 6603: In a standard program you can apply a @code{DOES>}-part only if the last
 6604: word was defined with @code{CREATE}. In Gforth, the @code{DOES>}-part
 6605: will override the behaviour of the last word defined in any case. In a
 6606: standard program, you can use @code{DOES>} only in a colon
 6607: definition. In Gforth, you can also use it in interpretation state, in a
 6608: kind of one-shot mode; for example:
 6609: @example
 6610: CREATE name ( ... -- ... )
 6611:   @i{initialization}
 6612: DOES>
 6613:   @i{code} ;
 6614: @end example
 6615: 
 6616: @noindent
 6617: is equivalent to the standard:
 6618: @example
 6619: :noname
 6620: DOES>
 6621:     @i{code} ;
 6622: CREATE name EXECUTE ( ... -- ... )
 6623:     @i{initialization}
 6624: @end example
 6625: 
 6626: doc->body
 6627: 
 6628: @node Advanced does> usage example, Const-does>, CREATE..DOES> details, User-defined Defining Words
 6629: @subsubsection Advanced does> usage example
 6630: 
 6631: The MIPS disassembler (@file{arch/mips/disasm.fs}) contains many words
 6632: for disassembling instructions, that follow a very repetetive scheme:
 6633: 
 6634: @example
 6635: :noname @var{disasm-operands} s" @var{inst-name}" type ;
 6636: @var{entry-num} cells @var{table} + !
 6637: @end example
 6638: 
 6639: Of course, this inspires the idea to factor out the commonalities to
 6640: allow a definition like
 6641: 
 6642: @example
 6643: @var{disasm-operands} @var{entry-num} @var{table} define-inst @var{inst-name}
 6644: @end example
 6645: 
 6646: The parameters @var{disasm-operands} and @var{table} are usually
 6647: correlated.  Moreover, before I wrote the disassembler, there already
 6648: existed code that defines instructions like this:
 6649: 
 6650: @example
 6651: @var{entry-num} @var{inst-format} @var{inst-name}
 6652: @end example
 6653: 
 6654: This code comes from the assembler and resides in
 6655: @file{arch/mips/insts.fs}.
 6656: 
 6657: So I had to define the @var{inst-format} words that performed the scheme
 6658: above when executed.  At first I chose to use run-time code-generation:
 6659: 
 6660: @example
 6661: : @var{inst-format} ( entry-num "name" -- ; compiled code: addr w -- )
 6662:   :noname Postpone @var{disasm-operands}
 6663:   name Postpone sliteral Postpone type Postpone ;
 6664:   swap cells @var{table} + ! ;
 6665: @end example
 6666: 
 6667: Note that this supplies the other two parameters of the scheme above.
 6668: 
 6669: An alternative would have been to write this using
 6670: @code{create}/@code{does>}:
 6671: 
 6672: @example
 6673: : @var{inst-format} ( entry-num "name" -- )
 6674:   here name string, ( entry-num c-addr ) \ parse and save "name"
 6675:   noname create , ( entry-num )
 6676:   latestxt swap cells @var{table} + !
 6677: does> ( addr w -- )
 6678:   \ disassemble instruction w at addr
 6679:   @@ >r 
 6680:   @var{disasm-operands}
 6681:   r> count type ;
 6682: @end example
 6683: 
 6684: Somehow the first solution is simpler, mainly because it's simpler to
 6685: shift a string from definition-time to use-time with @code{sliteral}
 6686: than with @code{string,} and friends.
 6687: 
 6688: I wrote a lot of words following this scheme and soon thought about
 6689: factoring out the commonalities among them.  Note that this uses a
 6690: two-level defining word, i.e., a word that defines ordinary defining
 6691: words.
 6692: 
 6693: This time a solution involving @code{postpone} and friends seemed more
 6694: difficult (try it as an exercise), so I decided to use a
 6695: @code{create}/@code{does>} word; since I was already at it, I also used
 6696: @code{create}/@code{does>} for the lower level (try using
 6697: @code{postpone} etc. as an exercise), resulting in the following
 6698: definition:
 6699: 
 6700: @example
 6701: : define-format ( disasm-xt table-xt -- )
 6702:     \ define an instruction format that uses disasm-xt for
 6703:     \ disassembling and enters the defined instructions into table
 6704:     \ table-xt
 6705:     create 2,
 6706: does> ( u "inst" -- )
 6707:     \ defines an anonymous word for disassembling instruction inst,
 6708:     \ and enters it as u-th entry into table-xt
 6709:     2@@ swap here name string, ( u table-xt disasm-xt c-addr ) \ remember string
 6710:     noname create 2,      \ define anonymous word
 6711:     execute latestxt swap ! \ enter xt of defined word into table-xt
 6712: does> ( addr w -- )
 6713:     \ disassemble instruction w at addr
 6714:     2@@ >r ( addr w disasm-xt R: c-addr )
 6715:     execute ( R: c-addr ) \ disassemble operands
 6716:     r> count type ; \ print name 
 6717: @end example
 6718: 
 6719: Note that the tables here (in contrast to above) do the @code{cells +}
 6720: by themselves (that's why you have to pass an xt).  This word is used in
 6721: the following way:
 6722: 
 6723: @example
 6724: ' @var{disasm-operands} ' @var{table} define-format @var{inst-format}
 6725: @end example
 6726: 
 6727: As shown above, the defined instruction format is then used like this:
 6728: 
 6729: @example
 6730: @var{entry-num} @var{inst-format} @var{inst-name}
 6731: @end example
 6732: 
 6733: In terms of currying, this kind of two-level defining word provides the
 6734: parameters in three stages: first @var{disasm-operands} and @var{table},
 6735: then @var{entry-num} and @var{inst-name}, finally @code{addr w}, i.e.,
 6736: the instruction to be disassembled.  
 6737: 
 6738: Of course this did not quite fit all the instruction format names used
 6739: in @file{insts.fs}, so I had to define a few wrappers that conditioned
 6740: the parameters into the right form.
 6741: 
 6742: If you have trouble following this section, don't worry.  First, this is
 6743: involved and takes time (and probably some playing around) to
 6744: understand; second, this is the first two-level
 6745: @code{create}/@code{does>} word I have written in seventeen years of
 6746: Forth; and if I did not have @file{insts.fs} to start with, I may well
 6747: have elected to use just a one-level defining word (with some repeating
 6748: of parameters when using the defining word). So it is not necessary to
 6749: understand this, but it may improve your understanding of Forth.
 6750: 
 6751: 
 6752: @node Const-does>,  , Advanced does> usage example, User-defined Defining Words
 6753: @subsubsection @code{Const-does>}
 6754: 
 6755: A frequent use of @code{create}...@code{does>} is for transferring some
 6756: values from definition-time to run-time.  Gforth supports this use with
 6757: 
 6758: doc-const-does>
 6759: 
 6760: A typical use of this word is:
 6761: 
 6762: @example
 6763: : curry+ ( n1 "name" -- )
 6764: 1 0 CONST-DOES> ( n2 -- n1+n2 )
 6765:     + ;
 6766: 
 6767: 3 curry+ 3+
 6768: @end example
 6769: 
 6770: Here the @code{1 0} means that 1 cell and 0 floats are transferred from
 6771: definition to run-time.
 6772: 
 6773: The advantages of using @code{const-does>} are:
 6774: 
 6775: @itemize
 6776: 
 6777: @item
 6778: You don't have to deal with storing and retrieving the values, i.e.,
 6779: your program becomes more writable and readable.
 6780: 
 6781: @item
 6782: When using @code{does>}, you have to introduce a @code{@@} that cannot
 6783: be optimized away (because you could change the data using
 6784: @code{>body}...@code{!}); @code{const-does>} avoids this problem.
 6785: 
 6786: @end itemize
 6787: 
 6788: An ANS Forth implementation of @code{const-does>} is available in
 6789: @file{compat/const-does.fs}.
 6790: 
 6791: 
 6792: @node Deferred Words, Aliases, User-defined Defining Words, Defining Words
 6793: @subsection Deferred Words
 6794: @cindex deferred words
 6795: 
 6796: The defining word @code{Defer} allows you to define a word by name
 6797: without defining its behaviour; the definition of its behaviour is
 6798: deferred. Here are two situation where this can be useful:
 6799: 
 6800: @itemize @bullet
 6801: @item
 6802: Where you want to allow the behaviour of a word to be altered later, and
 6803: for all precompiled references to the word to change when its behaviour
 6804: is changed.
 6805: @item
 6806: For mutual recursion; @xref{Calls and returns}.
 6807: @end itemize
 6808: 
 6809: In the following example, @code{foo} always invokes the version of
 6810: @code{greet} that prints ``@code{Good morning}'' whilst @code{bar}
 6811: always invokes the version that prints ``@code{Hello}''. There is no way
 6812: of getting @code{foo} to use the later version without re-ordering the
 6813: source code and recompiling it.
 6814: 
 6815: @example
 6816: : greet ." Good morning" ;
 6817: : foo ... greet ... ;
 6818: : greet ." Hello" ;
 6819: : bar ... greet ... ;
 6820: @end example
 6821: 
 6822: This problem can be solved by defining @code{greet} as a @code{Defer}red
 6823: word. The behaviour of a @code{Defer}red word can be defined and
 6824: redefined at any time by using @code{IS} to associate the xt of a
 6825: previously-defined word with it. The previous example becomes:
 6826: 
 6827: @example
 6828: Defer greet ( -- )
 6829: : foo ... greet ... ;
 6830: : bar ... greet ... ;
 6831: : greet1 ( -- ) ." Good morning" ;
 6832: : greet2 ( -- ) ." Hello" ;
 6833: ' greet2 IS greet  \ make greet behave like greet2
 6834: @end example
 6835: 
 6836: @progstyle
 6837: You should write a stack comment for every deferred word, and put only
 6838: XTs into deferred words that conform to this stack effect.  Otherwise
 6839: it's too difficult to use the deferred word.
 6840: 
 6841: A deferred word can be used to improve the statistics-gathering example
 6842: from @ref{User-defined Defining Words}; rather than edit the
 6843: application's source code to change every @code{:} to a @code{my:}, do
 6844: this:
 6845: 
 6846: @example
 6847: : real: : ;     \ retain access to the original
 6848: defer :         \ redefine as a deferred word
 6849: ' my: IS :      \ use special version of :
 6850: \
 6851: \ load application here
 6852: \
 6853: ' real: IS :    \ go back to the original
 6854: @end example
 6855: 
 6856: 
 6857: One thing to note is that @code{IS} has special compilation semantics,
 6858: such that it parses the name at compile time (like @code{TO}):
 6859: 
 6860: @example
 6861: : set-greet ( xt -- )
 6862:   IS greet ;
 6863: 
 6864: ' greet1 set-greet
 6865: @end example
 6866: 
 6867: In situations where @code{IS} does not fit, use @code{defer!} instead.
 6868: 
 6869: A deferred word can only inherit execution semantics from the xt
 6870: (because that is all that an xt can represent -- for more discussion of
 6871: this @pxref{Tokens for Words}); by default it will have default
 6872: interpretation and compilation semantics deriving from this execution
 6873: semantics.  However, you can change the interpretation and compilation
 6874: semantics of the deferred word in the usual ways:
 6875: 
 6876: @example
 6877: : bar .... ; immediate
 6878: Defer fred immediate
 6879: Defer jim
 6880: 
 6881: ' bar IS jim  \ jim has default semantics
 6882: ' bar IS fred \ fred is immediate
 6883: @end example
 6884: 
 6885: doc-defer
 6886: doc-defer!
 6887: doc-is
 6888: doc-defer@
 6889: doc-action-of
 6890: @comment TODO document these: what's defers [is]
 6891: doc-defers
 6892: 
 6893: @c Use @code{words-deferred} to see a list of deferred words.
 6894: 
 6895: Definitions of these words (except @code{defers}) in ANS Forth are
 6896: provided in @file{compat/defer.fs}.
 6897: 
 6898: 
 6899: @node Aliases,  , Deferred Words, Defining Words
 6900: @subsection Aliases
 6901: @cindex aliases
 6902: 
 6903: The defining word @code{Alias} allows you to define a word by name that
 6904: has the same behaviour as some other word. Here are two situation where
 6905: this can be useful:
 6906: 
 6907: @itemize @bullet
 6908: @item
 6909: When you want access to a word's definition from a different word list
 6910: (for an example of this, see the definition of the @code{Root} word list
 6911: in the Gforth source).
 6912: @item
 6913: When you want to create a synonym; a definition that can be known by
 6914: either of two names (for example, @code{THEN} and @code{ENDIF} are
 6915: aliases).
 6916: @end itemize
 6917: 
 6918: Like deferred words, an alias has default compilation and interpretation
 6919: semantics at the beginning (not the modifications of the other word),
 6920: but you can change them in the usual ways (@code{immediate},
 6921: @code{compile-only}). For example:
 6922: 
 6923: @example
 6924: : foo ... ; immediate
 6925: 
 6926: ' foo Alias bar \ bar is not an immediate word
 6927: ' foo Alias fooby immediate \ fooby is an immediate word
 6928: @end example
 6929: 
 6930: Words that are aliases have the same xt, different headers in the
 6931: dictionary, and consequently different name tokens (@pxref{Tokens for
 6932: Words}) and possibly different immediate flags.  An alias can only have
 6933: default or immediate compilation semantics; you can define aliases for
 6934: combined words with @code{interpret/compile:} -- see @ref{Combined words}.
 6935: 
 6936: doc-alias
 6937: 
 6938: 
 6939: @node Interpretation and Compilation Semantics, Tokens for Words, Defining Words, Words
 6940: @section Interpretation and Compilation Semantics
 6941: @cindex semantics, interpretation and compilation
 6942: 
 6943: @c !! state and ' are used without explanation
 6944: @c example for immediate/compile-only? or is the tutorial enough
 6945: 
 6946: @cindex interpretation semantics
 6947: The @dfn{interpretation semantics} of a (named) word are what the text
 6948: interpreter does when it encounters the word in interpret state. It also
 6949: appears in some other contexts, e.g., the execution token returned by
 6950: @code{' @i{word}} identifies the interpretation semantics of @i{word}
 6951: (in other words, @code{' @i{word} execute} is equivalent to
 6952: interpret-state text interpretation of @code{@i{word}}).
 6953: 
 6954: @cindex compilation semantics
 6955: The @dfn{compilation semantics} of a (named) word are what the text
 6956: interpreter does when it encounters the word in compile state. It also
 6957: appears in other contexts, e.g, @code{POSTPONE @i{word}}
 6958: compiles@footnote{In standard terminology, ``appends to the current
 6959: definition''.} the compilation semantics of @i{word}.
 6960: 
 6961: @cindex execution semantics
 6962: The standard also talks about @dfn{execution semantics}. They are used
 6963: only for defining the interpretation and compilation semantics of many
 6964: words. By default, the interpretation semantics of a word are to
 6965: @code{execute} its execution semantics, and the compilation semantics of
 6966: a word are to @code{compile,} its execution semantics.@footnote{In
 6967: standard terminology: The default interpretation semantics are its
 6968: execution semantics; the default compilation semantics are to append its
 6969: execution semantics to the execution semantics of the current
 6970: definition.}
 6971: 
 6972: Unnamed words (@pxref{Anonymous Definitions}) cannot be encountered by
 6973: the text interpreter, ticked, or @code{postpone}d, so they have no
 6974: interpretation or compilation semantics.  Their behaviour is represented
 6975: by their XT (@pxref{Tokens for Words}), and we call it execution
 6976: semantics, too.
 6977: 
 6978: @comment TODO expand, make it co-operate with new sections on text interpreter.
 6979: 
 6980: @cindex immediate words
 6981: @cindex compile-only words
 6982: You can change the semantics of the most-recently defined word:
 6983: 
 6984: 
 6985: doc-immediate
 6986: doc-compile-only
 6987: doc-restrict
 6988: 
 6989: By convention, words with non-default compilation semantics (e.g.,
 6990: immediate words) often have names surrounded with brackets (e.g.,
 6991: @code{[']}, @pxref{Execution token}).
 6992: 
 6993: Note that ticking (@code{'}) a compile-only word gives an error
 6994: (``Interpreting a compile-only word'').
 6995: 
 6996: @menu
 6997: * Combined words::              
 6998: @end menu
 6999: 
 7000: 
 7001: @node Combined words,  , Interpretation and Compilation Semantics, Interpretation and Compilation Semantics
 7002: @subsection Combined Words
 7003: @cindex combined words
 7004: 
 7005: Gforth allows you to define @dfn{combined words} -- words that have an
 7006: arbitrary combination of interpretation and compilation semantics.
 7007: 
 7008: doc-interpret/compile:
 7009: 
 7010: This feature was introduced for implementing @code{TO} and @code{S"}. I
 7011: recommend that you do not define such words, as cute as they may be:
 7012: they make it hard to get at both parts of the word in some contexts.
 7013: E.g., assume you want to get an execution token for the compilation
 7014: part. Instead, define two words, one that embodies the interpretation
 7015: part, and one that embodies the compilation part.  Once you have done
 7016: that, you can define a combined word with @code{interpret/compile:} for
 7017: the convenience of your users.
 7018: 
 7019: You might try to use this feature to provide an optimizing
 7020: implementation of the default compilation semantics of a word. For
 7021: example, by defining:
 7022: @example
 7023: :noname
 7024:    foo bar ;
 7025: :noname
 7026:    POSTPONE foo POSTPONE bar ;
 7027: interpret/compile: opti-foobar
 7028: @end example
 7029: 
 7030: @noindent
 7031: as an optimizing version of:
 7032: 
 7033: @example
 7034: : foobar
 7035:     foo bar ;
 7036: @end example
 7037: 
 7038: Unfortunately, this does not work correctly with @code{[compile]},
 7039: because @code{[compile]} assumes that the compilation semantics of all
 7040: @code{interpret/compile:} words are non-default. I.e., @code{[compile]
 7041: opti-foobar} would compile compilation semantics, whereas
 7042: @code{[compile] foobar} would compile interpretation semantics.
 7043: 
 7044: @cindex state-smart words (are a bad idea)
 7045: @anchor{state-smartness}
 7046: Some people try to use @dfn{state-smart} words to emulate the feature provided
 7047: by @code{interpret/compile:} (words are state-smart if they check
 7048: @code{STATE} during execution). E.g., they would try to code
 7049: @code{foobar} like this:
 7050: 
 7051: @example
 7052: : foobar
 7053:   STATE @@
 7054:   IF ( compilation state )
 7055:     POSTPONE foo POSTPONE bar
 7056:   ELSE
 7057:     foo bar
 7058:   ENDIF ; immediate
 7059: @end example
 7060: 
 7061: Although this works if @code{foobar} is only processed by the text
 7062: interpreter, it does not work in other contexts (like @code{'} or
 7063: @code{POSTPONE}). E.g., @code{' foobar} will produce an execution token
 7064: for a state-smart word, not for the interpretation semantics of the
 7065: original @code{foobar}; when you execute this execution token (directly
 7066: with @code{EXECUTE} or indirectly through @code{COMPILE,}) in compile
 7067: state, the result will not be what you expected (i.e., it will not
 7068: perform @code{foo bar}). State-smart words are a bad idea. Simply don't
 7069: write them@footnote{For a more detailed discussion of this topic, see
 7070: M. Anton Ertl,
 7071: @cite{@uref{http://www.complang.tuwien.ac.at/papers/ertl98.ps.gz,@code{State}-smartness---Why
 7072: it is Evil and How to Exorcise it}}, EuroForth '98.}!
 7073: 
 7074: @cindex defining words with arbitrary semantics combinations
 7075: It is also possible to write defining words that define words with
 7076: arbitrary combinations of interpretation and compilation semantics. In
 7077: general, they look like this:
 7078: 
 7079: @example
 7080: : def-word
 7081:     create-interpret/compile
 7082:     @i{code1}
 7083: interpretation>
 7084:     @i{code2}
 7085: <interpretation
 7086: compilation>
 7087:     @i{code3}
 7088: <compilation ;
 7089: @end example
 7090: 
 7091: For a @i{word} defined with @code{def-word}, the interpretation
 7092: semantics are to push the address of the body of @i{word} and perform
 7093: @i{code2}, and the compilation semantics are to push the address of
 7094: the body of @i{word} and perform @i{code3}. E.g., @code{constant}
 7095: can also be defined like this (except that the defined constants don't
 7096: behave correctly when @code{[compile]}d):
 7097: 
 7098: @example
 7099: : constant ( n "name" -- )
 7100:     create-interpret/compile
 7101:     ,
 7102: interpretation> ( -- n )
 7103:     @@
 7104: <interpretation
 7105: compilation> ( compilation. -- ; run-time. -- n )
 7106:     @@ postpone literal
 7107: <compilation ;
 7108: @end example
 7109: 
 7110: 
 7111: doc-create-interpret/compile
 7112: doc-interpretation>
 7113: doc-<interpretation
 7114: doc-compilation>
 7115: doc-<compilation
 7116: 
 7117: 
 7118: Words defined with @code{interpret/compile:} and
 7119: @code{create-interpret/compile} have an extended header structure that
 7120: differs from other words; however, unless you try to access them with
 7121: plain address arithmetic, you should not notice this. Words for
 7122: accessing the header structure usually know how to deal with this; e.g.,
 7123: @code{'} @i{word} @code{>body} also gives you the body of a word created
 7124: with @code{create-interpret/compile}.
 7125: 
 7126: 
 7127: @c -------------------------------------------------------------
 7128: @node Tokens for Words, Compiling words, Interpretation and Compilation Semantics, Words
 7129: @section Tokens for Words
 7130: @cindex tokens for words
 7131: 
 7132: This section describes the creation and use of tokens that represent
 7133: words.
 7134: 
 7135: @menu
 7136: * Execution token::             represents execution/interpretation semantics
 7137: * Compilation token::           represents compilation semantics
 7138: * Name token::                  represents named words
 7139: @end menu
 7140: 
 7141: @node Execution token, Compilation token, Tokens for Words, Tokens for Words
 7142: @subsection Execution token
 7143: 
 7144: @cindex xt
 7145: @cindex execution token
 7146: An @dfn{execution token} (@i{XT}) represents some behaviour of a word.
 7147: You can use @code{execute} to invoke this behaviour.
 7148: 
 7149: @cindex tick (')
 7150: You can use @code{'} to get an execution token that represents the
 7151: interpretation semantics of a named word:
 7152: 
 7153: @example
 7154: 5 ' .   ( n xt ) 
 7155: execute ( )      \ execute the xt (i.e., ".")
 7156: @end example
 7157: 
 7158: doc-'
 7159: 
 7160: @code{'} parses at run-time; there is also a word @code{[']} that parses
 7161: when it is compiled, and compiles the resulting XT:
 7162: 
 7163: @example
 7164: : foo ['] . execute ;
 7165: 5 foo
 7166: : bar ' execute ; \ by contrast,
 7167: 5 bar .           \ ' parses "." when bar executes
 7168: @end example
 7169: 
 7170: doc-[']
 7171: 
 7172: If you want the execution token of @i{word}, write @code{['] @i{word}}
 7173: in compiled code and @code{' @i{word}} in interpreted code.  Gforth's
 7174: @code{'} and @code{[']} behave somewhat unusually by complaining about
 7175: compile-only words (because these words have no interpretation
 7176: semantics).  You might get what you want by using @code{COMP' @i{word}
 7177: DROP} or @code{[COMP'] @i{word} DROP} (for details @pxref{Compilation
 7178: token}).
 7179: 
 7180: Another way to get an XT is @code{:noname} or @code{latestxt}
 7181: (@pxref{Anonymous Definitions}).  For anonymous words this gives an xt
 7182: for the only behaviour the word has (the execution semantics).  For
 7183: named words, @code{latestxt} produces an XT for the same behaviour it
 7184: would produce if the word was defined anonymously.
 7185: 
 7186: @example
 7187: :noname ." hello" ;
 7188: execute
 7189: @end example
 7190: 
 7191: An XT occupies one cell and can be manipulated like any other cell.
 7192: 
 7193: @cindex code field address
 7194: @cindex CFA
 7195: In ANS Forth the XT is just an abstract data type (i.e., defined by the
 7196: operations that produce or consume it).  For old hands: In Gforth, the
 7197: XT is implemented as a code field address (CFA).
 7198: 
 7199: doc-execute
 7200: doc-perform
 7201: 
 7202: @node Compilation token, Name token, Execution token, Tokens for Words
 7203: @subsection Compilation token
 7204: 
 7205: @cindex compilation token
 7206: @cindex CT (compilation token)
 7207: Gforth represents the compilation semantics of a named word by a
 7208: @dfn{compilation token} consisting of two cells: @i{w xt}. The top cell
 7209: @i{xt} is an execution token. The compilation semantics represented by
 7210: the compilation token can be performed with @code{execute}, which
 7211: consumes the whole compilation token, with an additional stack effect
 7212: determined by the represented compilation semantics.
 7213: 
 7214: At present, the @i{w} part of a compilation token is an execution token,
 7215: and the @i{xt} part represents either @code{execute} or
 7216: @code{compile,}@footnote{Depending upon the compilation semantics of the
 7217: word. If the word has default compilation semantics, the @i{xt} will
 7218: represent @code{compile,}. Otherwise (e.g., for immediate words), the
 7219: @i{xt} will represent @code{execute}.}. However, don't rely on that
 7220: knowledge, unless necessary; future versions of Gforth may introduce
 7221: unusual compilation tokens (e.g., a compilation token that represents
 7222: the compilation semantics of a literal).
 7223: 
 7224: You can perform the compilation semantics represented by the compilation
 7225: token with @code{execute}.  You can compile the compilation semantics
 7226: with @code{postpone,}. I.e., @code{COMP' @i{word} postpone,} is
 7227: equivalent to @code{postpone @i{word}}.
 7228: 
 7229: doc-[comp']
 7230: doc-comp'
 7231: doc-postpone,
 7232: 
 7233: @node Name token,  , Compilation token, Tokens for Words
 7234: @subsection Name token
 7235: 
 7236: @cindex name token
 7237: Gforth represents named words by the @dfn{name token}, (@i{nt}).  Name
 7238: token is an abstract data type that occurs as argument or result of the
 7239: words below.
 7240: 
 7241: @c !! put this elswhere?
 7242: @cindex name field address
 7243: @cindex NFA
 7244: The closest thing to the nt in older Forth systems is the name field
 7245: address (NFA), but there are significant differences: in older Forth
 7246: systems each word had a unique NFA, LFA, CFA and PFA (in this order, or
 7247: LFA, NFA, CFA, PFA) and there were words for getting from one to the
 7248: next.  In contrast, in Gforth 0@dots{}n nts correspond to one xt; there
 7249: is a link field in the structure identified by the name token, but
 7250: searching usually uses a hash table external to these structures; the
 7251: name in Gforth has a cell-wide count-and-flags field, and the nt is not
 7252: implemented as the address of that count field.
 7253: 
 7254: doc-find-name
 7255: doc-latest
 7256: doc->name
 7257: doc-name>int
 7258: doc-name?int
 7259: doc-name>comp
 7260: doc-name>string
 7261: doc-id.
 7262: doc-.name
 7263: doc-.id
 7264: 
 7265: @c ----------------------------------------------------------
 7266: @node Compiling words, The Text Interpreter, Tokens for Words, Words
 7267: @section Compiling words
 7268: @cindex compiling words
 7269: @cindex macros
 7270: 
 7271: In contrast to most other languages, Forth has no strict boundary
 7272: between compilation and run-time.  E.g., you can run arbitrary code
 7273: between defining words (or for computing data used by defining words
 7274: like @code{constant}). Moreover, @code{Immediate} (@pxref{Interpretation
 7275: and Compilation Semantics} and @code{[}...@code{]} (see below) allow
 7276: running arbitrary code while compiling a colon definition (exception:
 7277: you must not allot dictionary space).
 7278: 
 7279: @menu
 7280: * Literals::                    Compiling data values
 7281: * Macros::                      Compiling words
 7282: @end menu
 7283: 
 7284: @node Literals, Macros, Compiling words, Compiling words
 7285: @subsection Literals
 7286: @cindex Literals
 7287: 
 7288: The simplest and most frequent example is to compute a literal during
 7289: compilation.  E.g., the following definition prints an array of strings,
 7290: one string per line:
 7291: 
 7292: @example
 7293: : .strings ( addr u -- ) \ gforth
 7294:     2* cells bounds U+DO
 7295: 	cr i 2@@ type
 7296:     2 cells +LOOP ;  
 7297: @end example
 7298: 
 7299: With a simple-minded compiler like Gforth's, this computes @code{2
 7300: cells} on every loop iteration.  You can compute this value once and for
 7301: all at compile time and compile it into the definition like this:
 7302: 
 7303: @example
 7304: : .strings ( addr u -- ) \ gforth
 7305:     2* cells bounds U+DO
 7306: 	cr i 2@@ type
 7307:     [ 2 cells ] literal +LOOP ;  
 7308: @end example
 7309: 
 7310: @code{[} switches the text interpreter to interpret state (you will get
 7311: an @code{ok} prompt if you type this example interactively and insert a
 7312: newline between @code{[} and @code{]}), so it performs the
 7313: interpretation semantics of @code{2 cells}; this computes a number.
 7314: @code{]} switches the text interpreter back into compile state.  It then
 7315: performs @code{Literal}'s compilation semantics, which are to compile
 7316: this number into the current word.  You can decompile the word with
 7317: @code{see .strings} to see the effect on the compiled code.
 7318: 
 7319: You can also optimize the @code{2* cells} into @code{[ 2 cells ] literal
 7320: *} in this way.
 7321: 
 7322: doc-[
 7323: doc-]
 7324: doc-literal
 7325: doc-]L
 7326: 
 7327: There are also words for compiling other data types than single cells as
 7328: literals:
 7329: 
 7330: doc-2literal
 7331: doc-fliteral
 7332: doc-sliteral
 7333: 
 7334: @cindex colon-sys, passing data across @code{:}
 7335: @cindex @code{:}, passing data across
 7336: You might be tempted to pass data from outside a colon definition to the
 7337: inside on the data stack.  This does not work, because @code{:} puhes a
 7338: colon-sys, making stuff below unaccessible.  E.g., this does not work:
 7339: 
 7340: @example
 7341: 5 : foo literal ; \ error: "unstructured"
 7342: @end example
 7343: 
 7344: Instead, you have to pass the value in some other way, e.g., through a
 7345: variable:
 7346: 
 7347: @example
 7348: variable temp
 7349: 5 temp !
 7350: : foo [ temp @@ ] literal ;
 7351: @end example
 7352: 
 7353: 
 7354: @node Macros,  , Literals, Compiling words
 7355: @subsection Macros
 7356: @cindex Macros
 7357: @cindex compiling compilation semantics
 7358: 
 7359: @code{Literal} and friends compile data values into the current
 7360: definition.  You can also write words that compile other words into the
 7361: current definition.  E.g.,
 7362: 
 7363: @example
 7364: : compile-+ ( -- ) \ compiled code: ( n1 n2 -- n )
 7365:   POSTPONE + ;
 7366: 
 7367: : foo ( n1 n2 -- n )
 7368:   [ compile-+ ] ;
 7369: 1 2 foo .
 7370: @end example
 7371: 
 7372: This is equivalent to @code{: foo + ;} (@code{see foo} to check this).
 7373: What happens in this example?  @code{Postpone} compiles the compilation
 7374: semantics of @code{+} into @code{compile-+}; later the text interpreter
 7375: executes @code{compile-+} and thus the compilation semantics of +, which
 7376: compile (the execution semantics of) @code{+} into
 7377: @code{foo}.@footnote{A recent RFI answer requires that compiling words
 7378: should only be executed in compile state, so this example is not
 7379: guaranteed to work on all standard systems, but on any decent system it
 7380: will work.}
 7381: 
 7382: doc-postpone
 7383: doc-[compile]
 7384: 
 7385: Compiling words like @code{compile-+} are usually immediate (or similar)
 7386: so you do not have to switch to interpret state to execute them;
 7387: mopifying the last example accordingly produces:
 7388: 
 7389: @example
 7390: : [compile-+] ( compilation: --; interpretation: -- )
 7391:   \ compiled code: ( n1 n2 -- n )
 7392:   POSTPONE + ; immediate
 7393: 
 7394: : foo ( n1 n2 -- n )
 7395:   [compile-+] ;
 7396: 1 2 foo .
 7397: @end example
 7398: 
 7399: Immediate compiling words are similar to macros in other languages (in
 7400: particular, Lisp).  The important differences to macros in, e.g., C are:
 7401: 
 7402: @itemize @bullet
 7403: 
 7404: @item
 7405: You use the same language for defining and processing macros, not a
 7406: separate preprocessing language and processor.
 7407: 
 7408: @item
 7409: Consequently, the full power of Forth is available in macro definitions.
 7410: E.g., you can perform arbitrarily complex computations, or generate
 7411: different code conditionally or in a loop (e.g., @pxref{Advanced macros
 7412: Tutorial}).  This power is very useful when writing a parser generators
 7413: or other code-generating software.
 7414: 
 7415: @item
 7416: Macros defined using @code{postpone} etc. deal with the language at a
 7417: higher level than strings; name binding happens at macro definition
 7418: time, so you can avoid the pitfalls of name collisions that can happen
 7419: in C macros.  Of course, Forth is a liberal language and also allows to
 7420: shoot yourself in the foot with text-interpreted macros like
 7421: 
 7422: @example
 7423: : [compile-+] s" +" evaluate ; immediate
 7424: @end example
 7425: 
 7426: Apart from binding the name at macro use time, using @code{evaluate}
 7427: also makes your definition @code{state}-smart (@pxref{state-smartness}).
 7428: @end itemize
 7429: 
 7430: You may want the macro to compile a number into a word.  The word to do
 7431: it is @code{literal}, but you have to @code{postpone} it, so its
 7432: compilation semantics take effect when the macro is executed, not when
 7433: it is compiled:
 7434: 
 7435: @example
 7436: : [compile-5] ( -- ) \ compiled code: ( -- n )
 7437:   5 POSTPONE literal ; immediate
 7438: 
 7439: : foo [compile-5] ;
 7440: foo .
 7441: @end example
 7442: 
 7443: You may want to pass parameters to a macro, that the macro should
 7444: compile into the current definition.  If the parameter is a number, then
 7445: you can use @code{postpone literal} (similar for other values).
 7446: 
 7447: If you want to pass a word that is to be compiled, the usual way is to
 7448: pass an execution token and @code{compile,} it:
 7449: 
 7450: @example
 7451: : twice1 ( xt -- ) \ compiled code: ... -- ...
 7452:   dup compile, compile, ;
 7453: 
 7454: : 2+ ( n1 -- n2 )
 7455:   [ ' 1+ twice1 ] ;
 7456: @end example
 7457: 
 7458: doc-compile,
 7459: 
 7460: An alternative available in Gforth, that allows you to pass compile-only
 7461: words as parameters is to use the compilation token (@pxref{Compilation
 7462: token}).  The same example in this technique:
 7463: 
 7464: @example
 7465: : twice ( ... ct -- ... ) \ compiled code: ... -- ...
 7466:   2dup 2>r execute 2r> execute ;
 7467: 
 7468: : 2+ ( n1 -- n2 )
 7469:   [ comp' 1+ twice ] ;
 7470: @end example
 7471: 
 7472: In the example above @code{2>r} and @code{2r>} ensure that @code{twice}
 7473: works even if the executed compilation semantics has an effect on the
 7474: data stack.
 7475: 
 7476: You can also define complete definitions with these words; this provides
 7477: an alternative to using @code{does>} (@pxref{User-defined Defining
 7478: Words}).  E.g., instead of
 7479: 
 7480: @example
 7481: : curry+ ( n1 "name" -- )
 7482:     CREATE ,
 7483: DOES> ( n2 -- n1+n2 )
 7484:     @@ + ;
 7485: @end example
 7486: 
 7487: you could define
 7488: 
 7489: @example
 7490: : curry+ ( n1 "name" -- )
 7491:   \ name execution: ( n2 -- n1+n2 )
 7492:   >r : r> POSTPONE literal POSTPONE + POSTPONE ; ;
 7493: 
 7494: -3 curry+ 3-
 7495: see 3-
 7496: @end example
 7497: 
 7498: The sequence @code{>r : r>} is necessary, because @code{:} puts a
 7499: colon-sys on the data stack that makes everything below it unaccessible.
 7500: 
 7501: This way of writing defining words is sometimes more, sometimes less
 7502: convenient than using @code{does>} (@pxref{Advanced does> usage
 7503: example}).  One advantage of this method is that it can be optimized
 7504: better, because the compiler knows that the value compiled with
 7505: @code{literal} is fixed, whereas the data associated with a
 7506: @code{create}d word can be changed.
 7507: 
 7508: @c ----------------------------------------------------------
 7509: @node The Text Interpreter, The Input Stream, Compiling words, Words
 7510: @section  The Text Interpreter
 7511: @cindex interpreter - outer
 7512: @cindex text interpreter
 7513: @cindex outer interpreter
 7514: 
 7515: @c Should we really describe all these ugly details?  IMO the text
 7516: @c interpreter should be much cleaner, but that may not be possible within
 7517: @c ANS Forth. - anton
 7518: @c nac-> I wanted to explain how it works to show how you can exploit
 7519: @c it in your own programs. When I was writing a cross-compiler, figuring out
 7520: @c some of these gory details was very helpful to me. None of the textbooks
 7521: @c I've seen cover it, and the most modern Forth textbook -- Forth Inc's,
 7522: @c seems to positively avoid going into too much detail for some of
 7523: @c the internals.
 7524: 
 7525: @c anton: ok.  I wonder, though, if this is the right place; for some stuff
 7526: @c it is; for the ugly details, I would prefer another place.  I wonder
 7527: @c whether we should have a chapter before "Words" that describes some
 7528: @c basic concepts referred to in words, and a chapter after "Words" that
 7529: @c describes implementation details.
 7530: 
 7531: The text interpreter@footnote{This is an expanded version of the
 7532: material in @ref{Introducing the Text Interpreter}.} is an endless loop
 7533: that processes input from the current input device. It is also called
 7534: the outer interpreter, in contrast to the inner interpreter
 7535: (@pxref{Engine}) which executes the compiled Forth code on interpretive
 7536: implementations.
 7537: 
 7538: @cindex interpret state
 7539: @cindex compile state
 7540: The text interpreter operates in one of two states: @dfn{interpret
 7541: state} and @dfn{compile state}. The current state is defined by the
 7542: aptly-named variable @code{state}.
 7543: 
 7544: This section starts by describing how the text interpreter behaves when
 7545: it is in interpret state, processing input from the user input device --
 7546: the keyboard. This is the mode that a Forth system is in after it starts
 7547: up.
 7548: 
 7549: @cindex input buffer
 7550: @cindex terminal input buffer
 7551: The text interpreter works from an area of memory called the @dfn{input
 7552: buffer}@footnote{When the text interpreter is processing input from the
 7553: keyboard, this area of memory is called the @dfn{terminal input buffer}
 7554: (TIB) and is addressed by the (obsolescent) words @code{TIB} and
 7555: @code{#TIB}.}, which stores your keyboard input when you press the
 7556: @key{RET} key. Starting at the beginning of the input buffer, it skips
 7557: leading spaces (called @dfn{delimiters}) then parses a string (a
 7558: sequence of non-space characters) until it reaches either a space
 7559: character or the end of the buffer. Having parsed a string, it makes two
 7560: attempts to process it:
 7561: 
 7562: @cindex dictionary
 7563: @itemize @bullet
 7564: @item
 7565: It looks for the string in a @dfn{dictionary} of definitions. If the
 7566: string is found, the string names a @dfn{definition} (also known as a
 7567: @dfn{word}) and the dictionary search returns information that allows
 7568: the text interpreter to perform the word's @dfn{interpretation
 7569: semantics}. In most cases, this simply means that the word will be
 7570: executed.
 7571: @item
 7572: If the string is not found in the dictionary, the text interpreter
 7573: attempts to treat it as a number, using the rules described in
 7574: @ref{Number Conversion}. If the string represents a legal number in the
 7575: current radix, the number is pushed onto a parameter stack (the data
 7576: stack for integers, the floating-point stack for floating-point
 7577: numbers).
 7578: @end itemize
 7579: 
 7580: If both attempts fail, or if the word is found in the dictionary but has
 7581: no interpretation semantics@footnote{This happens if the word was
 7582: defined as @code{COMPILE-ONLY}.} the text interpreter discards the
 7583: remainder of the input buffer, issues an error message and waits for
 7584: more input. If one of the attempts succeeds, the text interpreter
 7585: repeats the parsing process until the whole of the input buffer has been
 7586: processed, at which point it prints the status message ``@code{ ok}''
 7587: and waits for more input.
 7588: 
 7589: @c anton: this should be in the input stream subsection (or below it)
 7590: 
 7591: @cindex parse area
 7592: The text interpreter keeps track of its position in the input buffer by
 7593: updating a variable called @code{>IN} (pronounced ``to-in''). The value
 7594: of @code{>IN} starts out as 0, indicating an offset of 0 from the start
 7595: of the input buffer. The region from offset @code{>IN @@} to the end of
 7596: the input buffer is called the @dfn{parse area}@footnote{In other words,
 7597: the text interpreter processes the contents of the input buffer by
 7598: parsing strings from the parse area until the parse area is empty.}.
 7599: This example shows how @code{>IN} changes as the text interpreter parses
 7600: the input buffer:
 7601: 
 7602: @example
 7603: : remaining >IN @@ SOURCE 2 PICK - -ROT + SWAP
 7604:   CR ." ->" TYPE ." <-" ; IMMEDIATE 
 7605: 
 7606: 1 2 3 remaining + remaining . 
 7607: 
 7608: : foo 1 2 3 remaining SWAP remaining ;
 7609: @end example
 7610: 
 7611: @noindent
 7612: The result is:
 7613: 
 7614: @example
 7615: ->+ remaining .<-
 7616: ->.<-5  ok
 7617: 
 7618: ->SWAP remaining ;-<
 7619: ->;<-  ok
 7620: @end example
 7621: 
 7622: @cindex parsing words
 7623: The value of @code{>IN} can also be modified by a word in the input
 7624: buffer that is executed by the text interpreter.  This means that a word
 7625: can ``trick'' the text interpreter into either skipping a section of the
 7626: input buffer@footnote{This is how parsing words work.} or into parsing a
 7627: section twice. For example:
 7628: 
 7629: @example
 7630: : lat ." <<foo>>" ;
 7631: : flat ." <<bar>>" >IN DUP @@ 3 - SWAP ! ;
 7632: @end example
 7633: 
 7634: @noindent
 7635: When @code{flat} is executed, this output is produced@footnote{Exercise
 7636: for the reader: what would happen if the @code{3} were replaced with
 7637: @code{4}?}:
 7638: 
 7639: @example
 7640: <<bar>><<foo>>
 7641: @end example
 7642: 
 7643: This technique can be used to work around some of the interoperability
 7644: problems of parsing words.  Of course, it's better to avoid parsing
 7645: words where possible.
 7646: 
 7647: @noindent
 7648: Two important notes about the behaviour of the text interpreter:
 7649: 
 7650: @itemize @bullet
 7651: @item
 7652: It processes each input string to completion before parsing additional
 7653: characters from the input buffer.
 7654: @item
 7655: It treats the input buffer as a read-only region (and so must your code).
 7656: @end itemize
 7657: 
 7658: @noindent
 7659: When the text interpreter is in compile state, its behaviour changes in
 7660: these ways:
 7661: 
 7662: @itemize @bullet
 7663: @item
 7664: If a parsed string is found in the dictionary, the text interpreter will
 7665: perform the word's @dfn{compilation semantics}. In most cases, this
 7666: simply means that the execution semantics of the word will be appended
 7667: to the current definition.
 7668: @item
 7669: When a number is encountered, it is compiled into the current definition
 7670: (as a literal) rather than being pushed onto a parameter stack.
 7671: @item
 7672: If an error occurs, @code{state} is modified to put the text interpreter
 7673: back into interpret state.
 7674: @item
 7675: Each time a line is entered from the keyboard, Gforth prints
 7676: ``@code{ compiled}'' rather than `` @code{ok}''.
 7677: @end itemize
 7678: 
 7679: @cindex text interpreter - input sources
 7680: When the text interpreter is using an input device other than the
 7681: keyboard, its behaviour changes in these ways:
 7682: 
 7683: @itemize @bullet
 7684: @item
 7685: When the parse area is empty, the text interpreter attempts to refill
 7686: the input buffer from the input source. When the input source is
 7687: exhausted, the input source is set back to the previous input source.
 7688: @item
 7689: It doesn't print out ``@code{ ok}'' or ``@code{ compiled}'' messages each
 7690: time the parse area is emptied.
 7691: @item
 7692: If an error occurs, the input source is set back to the user input
 7693: device.
 7694: @end itemize
 7695: 
 7696: You can read about this in more detail in @ref{Input Sources}.
 7697: 
 7698: doc->in
 7699: doc-source
 7700: 
 7701: doc-tib
 7702: doc-#tib
 7703: 
 7704: 
 7705: @menu
 7706: * Input Sources::               
 7707: * Number Conversion::           
 7708: * Interpret/Compile states::    
 7709: * Interpreter Directives::      
 7710: @end menu
 7711: 
 7712: @node Input Sources, Number Conversion, The Text Interpreter, The Text Interpreter
 7713: @subsection Input Sources
 7714: @cindex input sources
 7715: @cindex text interpreter - input sources
 7716: 
 7717: By default, the text interpreter processes input from the user input
 7718: device (the keyboard) when Forth starts up. The text interpreter can
 7719: process input from any of these sources:
 7720: 
 7721: @itemize @bullet
 7722: @item
 7723: The user input device -- the keyboard.
 7724: @item
 7725: A file, using the words described in @ref{Forth source files}.
 7726: @item
 7727: A block, using the words described in @ref{Blocks}.
 7728: @item
 7729: A text string, using @code{evaluate}.
 7730: @end itemize
 7731: 
 7732: A program can identify the current input device from the values of
 7733: @code{source-id} and @code{blk}.
 7734: 
 7735: 
 7736: doc-source-id
 7737: doc-blk
 7738: 
 7739: doc-save-input
 7740: doc-restore-input
 7741: 
 7742: doc-evaluate
 7743: doc-query
 7744: 
 7745: 
 7746: 
 7747: @node Number Conversion, Interpret/Compile states, Input Sources, The Text Interpreter
 7748: @subsection Number Conversion
 7749: @cindex number conversion
 7750: @cindex double-cell numbers, input format
 7751: @cindex input format for double-cell numbers
 7752: @cindex single-cell numbers, input format
 7753: @cindex input format for single-cell numbers
 7754: @cindex floating-point numbers, input format
 7755: @cindex input format for floating-point numbers
 7756: 
 7757: This section describes the rules that the text interpreter uses when it
 7758: tries to convert a string into a number.
 7759: 
 7760: Let <digit> represent any character that is a legal digit in the current
 7761: number base@footnote{For example, 0-9 when the number base is decimal or
 7762: 0-9, A-F when the number base is hexadecimal.}.
 7763: 
 7764: Let <decimal digit> represent any character in the range 0-9.
 7765: 
 7766: Let @{@i{a b}@} represent the @i{optional} presence of any of the characters
 7767: in the braces (@i{a} or @i{b} or neither).
 7768: 
 7769: Let * represent any number of instances of the previous character
 7770: (including none).
 7771: 
 7772: Let any other character represent itself.
 7773: 
 7774: @noindent
 7775: Now, the conversion rules are:
 7776: 
 7777: @itemize @bullet
 7778: @item
 7779: A string of the form <digit><digit>* is treated as a single-precision
 7780: (cell-sized) positive integer. Examples are 0 123 6784532 32343212343456 42
 7781: @item
 7782: A string of the form -<digit><digit>* is treated as a single-precision
 7783: (cell-sized) negative integer, and is represented using 2's-complement
 7784: arithmetic. Examples are -45 -5681 -0
 7785: @item
 7786: A string of the form <digit><digit>*.<digit>* is treated as a double-precision
 7787: (double-cell-sized) positive integer. Examples are 3465. 3.465 34.65
 7788: (all three of these represent the same number).
 7789: @item
 7790: A string of the form -<digit><digit>*.<digit>* is treated as a
 7791: double-precision (double-cell-sized) negative integer, and is
 7792: represented using 2's-complement arithmetic. Examples are -3465. -3.465
 7793: -34.65 (all three of these represent the same number).
 7794: @item
 7795: A string of the form @{+ -@}<decimal digit>@{.@}<decimal digit>*@{e
 7796: E@}@{+ -@}<decimal digit><decimal digit>* is treated as a floating-point
 7797: number. Examples are 1e 1e0 1.e 1.e0 +1e+0 (which all represent the same
 7798: number) +12.E-4
 7799: @end itemize
 7800: 
 7801: By default, the number base used for integer number conversion is
 7802: given by the contents of the variable @code{base}.  Note that a lot of
 7803: confusion can result from unexpected values of @code{base}.  If you
 7804: change @code{base} anywhere, make sure to save the old value and
 7805: restore it afterwards; better yet, use @code{base-execute}, which does
 7806: this for you.  In general I recommend keeping @code{base} decimal, and
 7807: using the prefixes described below for the popular non-decimal bases.
 7808: 
 7809: doc-dpl
 7810: doc-base-execute
 7811: doc-base
 7812: doc-hex
 7813: doc-decimal
 7814: 
 7815: @cindex '-prefix for character strings
 7816: @cindex &-prefix for decimal numbers
 7817: @cindex #-prefix for decimal numbers
 7818: @cindex %-prefix for binary numbers
 7819: @cindex $-prefix for hexadecimal numbers
 7820: @cindex 0x-prefix for hexadecimal numbers
 7821: Gforth allows you to override the value of @code{base} by using a
 7822: prefix@footnote{Some Forth implementations provide a similar scheme by
 7823: implementing @code{$} etc. as parsing words that process the subsequent
 7824: number in the input stream and push it onto the stack. For example, see
 7825: @cite{Number Conversion and Literals}, by Wil Baden; Forth Dimensions
 7826: 20(3) pages 26--27. In such implementations, unlike in Gforth, a space
 7827: is required between the prefix and the number.} before the first digit
 7828: of an (integer) number. The following prefixes are supported:
 7829: 
 7830: @itemize @bullet
 7831: @item
 7832: @code{&} -- decimal
 7833: @item
 7834: @code{#} -- decimal
 7835: @item
 7836: @code{%} -- binary
 7837: @item
 7838: @code{$} -- hexadecimal
 7839: @item
 7840: @code{0x} -- hexadecimal, if base<33.
 7841: @item
 7842: @code{'} -- numeric value (e.g., ASCII code) of next character; an
 7843: optional @code{'} may be present after the character.
 7844: @end itemize
 7845: 
 7846: Here are some examples, with the equivalent decimal number shown after
 7847: in braces:
 7848: 
 7849: -$41 (-65), %1001101 (205), %1001.0001 (145 - a double-precision number),
 7850: 'A (65),
 7851: -'a' (-97),
 7852: &905 (905), $abc (2478), $ABC (2478).
 7853: 
 7854: @cindex number conversion - traps for the unwary
 7855: @noindent
 7856: Number conversion has a number of traps for the unwary:
 7857: 
 7858: @itemize @bullet
 7859: @item
 7860: You cannot determine the current number base using the code sequence
 7861: @code{base @@ .} -- the number base is always 10 in the current number
 7862: base. Instead, use something like @code{base @@ dec.}
 7863: @item
 7864: If the number base is set to a value greater than 14 (for example,
 7865: hexadecimal), the number 123E4 is ambiguous; the conversion rules allow
 7866: it to be intepreted as either a single-precision integer or a
 7867: floating-point number (Gforth treats it as an integer). The ambiguity
 7868: can be resolved by explicitly stating the sign of the mantissa and/or
 7869: exponent: 123E+4 or +123E4 -- if the number base is decimal, no
 7870: ambiguity arises; either representation will be treated as a
 7871: floating-point number.
 7872: @item
 7873: There is a word @code{bin} but it does @i{not} set the number base!
 7874: It is used to specify file types.
 7875: @item
 7876: ANS Forth requires the @code{.} of a double-precision number to be the
 7877: final character in the string.  Gforth allows the @code{.} to be
 7878: anywhere after the first digit.
 7879: @item
 7880: The number conversion process does not check for overflow.
 7881: @item
 7882: In an ANS Forth program @code{base} is required to be decimal when
 7883: converting floating-point numbers.  In Gforth, number conversion to
 7884: floating-point numbers always uses base &10, irrespective of the value
 7885: of @code{base}.
 7886: @end itemize
 7887: 
 7888: You can read numbers into your programs with the words described in
 7889: @ref{Line input and conversion}.
 7890: 
 7891: @node Interpret/Compile states, Interpreter Directives, Number Conversion, The Text Interpreter
 7892: @subsection Interpret/Compile states
 7893: @cindex Interpret/Compile states
 7894: 
 7895: A standard program is not permitted to change @code{state}
 7896: explicitly. However, it can change @code{state} implicitly, using the
 7897: words @code{[} and @code{]}. When @code{[} is executed it switches
 7898: @code{state} to interpret state, and therefore the text interpreter
 7899: starts interpreting. When @code{]} is executed it switches @code{state}
 7900: to compile state and therefore the text interpreter starts
 7901: compiling. The most common usage for these words is for switching into
 7902: interpret state and back from within a colon definition; this technique
 7903: can be used to compile a literal (for an example, @pxref{Literals}) or
 7904: for conditional compilation (for an example, @pxref{Interpreter
 7905: Directives}).
 7906: 
 7907: 
 7908: @c This is a bad example: It's non-standard, and it's not necessary.
 7909: @c However, I can't think of a good example for switching into compile
 7910: @c state when there is no current word (@code{state}-smart words are not a
 7911: @c good reason).  So maybe we should use an example for switching into
 7912: @c interpret @code{state} in a colon def. - anton
 7913: @c nac-> I agree. I started out by putting in the example, then realised
 7914: @c that it was non-ANS, so wrote more words around it. I hope this
 7915: @c re-written version is acceptable to you. I do want to keep the example
 7916: @c as it is helpful for showing what is and what is not portable, particularly
 7917: @c where it outlaws a style in common use.
 7918: 
 7919: @c anton: it's more important to show what's portable.  After we have done
 7920: @c that, we can also show what's not.  In any case, I have written a
 7921: @c section Compiling Words which also deals with [ ].
 7922: 
 7923: @c  !! The following example does not work in Gforth 0.5.9 or later.
 7924: 
 7925: @c  @code{[} and @code{]} also give you the ability to switch into compile
 7926: @c  state and back, but we cannot think of any useful Standard application
 7927: @c  for this ability. Pre-ANS Forth textbooks have examples like this:
 7928: 
 7929: @c  @example
 7930: @c  : AA ." this is A" ;
 7931: @c  : BB ." this is B" ;
 7932: @c  : CC ." this is C" ;
 7933: 
 7934: @c  create table ] aa bb cc [
 7935: 
 7936: @c  : go ( n -- ) \ n is offset into table.. 0 for 1st entry
 7937: @c    cells table + @@ execute ;
 7938: @c  @end example
 7939: 
 7940: @c  This example builds a jump table; @code{0 go} will display ``@code{this
 7941: @c  is A}''. Using @code{[} and @code{]} in this example is equivalent to
 7942: @c  defining @code{table} like this:
 7943: 
 7944: @c  @example
 7945: @c  create table ' aa COMPILE, ' bb COMPILE, ' cc COMPILE,
 7946: @c  @end example
 7947: 
 7948: @c  The problem with this code is that the definition of @code{table} is not
 7949: @c  portable -- it @i{compile}s execution tokens into code space. Whilst it
 7950: @c  @i{may} work on systems where code space and data space co-incide, the
 7951: @c  Standard only allows data space to be assigned for a @code{CREATE}d
 7952: @c  word. In addition, the Standard only allows @code{@@} to access data
 7953: @c  space, whilst this example is using it to access code space. The only
 7954: @c  portable, Standard way to build this table is to build it in data space,
 7955: @c  like this:
 7956: 
 7957: @c  @example
 7958: @c  create table ' aa , ' bb , ' cc ,
 7959: @c  @end example
 7960: 
 7961: @c  doc-state
 7962: 
 7963: 
 7964: @node Interpreter Directives,  , Interpret/Compile states, The Text Interpreter
 7965: @subsection Interpreter Directives
 7966: @cindex interpreter directives
 7967: @cindex conditional compilation
 7968: 
 7969: These words are usually used in interpret state; typically to control
 7970: which parts of a source file are processed by the text
 7971: interpreter. There are only a few ANS Forth Standard words, but Gforth
 7972: supplements these with a rich set of immediate control structure words
 7973: to compensate for the fact that the non-immediate versions can only be
 7974: used in compile state (@pxref{Control Structures}). Typical usages:
 7975: 
 7976: @example
 7977: FALSE Constant HAVE-ASSEMBLER
 7978: .
 7979: .
 7980: HAVE-ASSEMBLER [IF]
 7981: : ASSEMBLER-FEATURE
 7982:   ...
 7983: ;
 7984: [ENDIF]
 7985: .
 7986: .
 7987: : SEE
 7988:   ... \ general-purpose SEE code
 7989:   [ HAVE-ASSEMBLER [IF] ]
 7990:   ... \ assembler-specific SEE code
 7991:   [ [ENDIF] ]
 7992: ;
 7993: @end example
 7994: 
 7995: 
 7996: doc-[IF]
 7997: doc-[ELSE]
 7998: doc-[THEN]
 7999: doc-[ENDIF]
 8000: 
 8001: doc-[IFDEF]
 8002: doc-[IFUNDEF]
 8003: 
 8004: doc-[?DO]
 8005: doc-[DO]
 8006: doc-[FOR]
 8007: doc-[LOOP]
 8008: doc-[+LOOP]
 8009: doc-[NEXT]
 8010: 
 8011: doc-[BEGIN]
 8012: doc-[UNTIL]
 8013: doc-[AGAIN]
 8014: doc-[WHILE]
 8015: doc-[REPEAT]
 8016: 
 8017: 
 8018: @c -------------------------------------------------------------
 8019: @node The Input Stream, Word Lists, The Text Interpreter, Words
 8020: @section The Input Stream
 8021: @cindex input stream
 8022: 
 8023: @c !! integrate this better with the "Text Interpreter" section
 8024: The text interpreter reads from the input stream, which can come from
 8025: several sources (@pxref{Input Sources}).  Some words, in particular
 8026: defining words, but also words like @code{'}, read parameters from the
 8027: input stream instead of from the stack.
 8028: 
 8029: Such words are called parsing words, because they parse the input
 8030: stream.  Parsing words are hard to use in other words, because it is
 8031: hard to pass program-generated parameters through the input stream.
 8032: They also usually have an unintuitive combination of interpretation and
 8033: compilation semantics when implemented naively, leading to various
 8034: approaches that try to produce a more intuitive behaviour
 8035: (@pxref{Combined words}).
 8036: 
 8037: It should be obvious by now that parsing words are a bad idea.  If you
 8038: want to implement a parsing word for convenience, also provide a factor
 8039: of the word that does not parse, but takes the parameters on the stack.
 8040: To implement the parsing word on top if it, you can use the following
 8041: words:
 8042: 
 8043: @c anton: these belong in the input stream section
 8044: doc-parse
 8045: doc-parse-name
 8046: doc-parse-word
 8047: doc-name
 8048: doc-word
 8049: doc-refill
 8050: 
 8051: Conversely, if you have the bad luck (or lack of foresight) to have to
 8052: deal with parsing words without having such factors, how do you pass a
 8053: string that is not in the input stream to it?
 8054: 
 8055: doc-execute-parsing
 8056: 
 8057: A definition of this word in ANS Forth is provided in
 8058: @file{compat/execute-parsing.fs}.
 8059: 
 8060: If you want to run a parsing word on a file, the following word should
 8061: help:
 8062: 
 8063: doc-execute-parsing-file
 8064: 
 8065: @c -------------------------------------------------------------
 8066: @node Word Lists, Environmental Queries, The Input Stream, Words
 8067: @section Word Lists
 8068: @cindex word lists
 8069: @cindex header space
 8070: 
 8071: A wordlist is a list of named words; you can add new words and look up
 8072: words by name (and you can remove words in a restricted way with
 8073: markers).  Every named (and @code{reveal}ed) word is in one wordlist.
 8074: 
 8075: @cindex search order stack
 8076: The text interpreter searches the wordlists present in the search order
 8077: (a stack of wordlists), from the top to the bottom.  Within each
 8078: wordlist, the search starts conceptually at the newest word; i.e., if
 8079: two words in a wordlist have the same name, the newer word is found.
 8080: 
 8081: @cindex compilation word list
 8082: New words are added to the @dfn{compilation wordlist} (aka current
 8083: wordlist).
 8084: 
 8085: @cindex wid
 8086: A word list is identified by a cell-sized word list identifier (@i{wid})
 8087: in much the same way as a file is identified by a file handle. The
 8088: numerical value of the wid has no (portable) meaning, and might change
 8089: from session to session.
 8090: 
 8091: The ANS Forth ``Search order'' word set is intended to provide a set of
 8092: low-level tools that allow various different schemes to be
 8093: implemented. Gforth also provides @code{vocabulary}, a traditional Forth
 8094: word.  @file{compat/vocabulary.fs} provides an implementation in ANS
 8095: Forth.
 8096: 
 8097: @comment TODO: locals section refers to here, saying that every word list (aka
 8098: @comment vocabulary) has its own methods for searching etc. Need to document that.
 8099: @c anton: but better in a separate subsection on wordlist internals
 8100: 
 8101: @comment TODO: document markers, reveal, tables, mappedwordlist
 8102: 
 8103: @comment the gforthman- prefix is used to pick out the true definition of a
 8104: @comment word from the source files, rather than some alias.
 8105: 
 8106: doc-forth-wordlist
 8107: doc-definitions
 8108: doc-get-current
 8109: doc-set-current
 8110: doc-get-order
 8111: doc-set-order
 8112: doc-wordlist
 8113: doc-table
 8114: doc->order
 8115: doc-previous
 8116: doc-also
 8117: doc-forth
 8118: doc-only
 8119: doc-order
 8120: 
 8121: doc-find
 8122: doc-search-wordlist
 8123: 
 8124: doc-words
 8125: doc-vlist
 8126: @c doc-words-deferred
 8127: 
 8128: @c doc-mappedwordlist @c map-structure undefined, implemantation-specific
 8129: doc-root
 8130: doc-vocabulary
 8131: doc-seal
 8132: doc-vocs
 8133: doc-current
 8134: doc-context
 8135: 
 8136: 
 8137: @menu
 8138: * Vocabularies::                
 8139: * Why use word lists?::         
 8140: * Word list example::           
 8141: @end menu
 8142: 
 8143: @node Vocabularies, Why use word lists?, Word Lists, Word Lists
 8144: @subsection Vocabularies
 8145: @cindex Vocabularies, detailed explanation
 8146: 
 8147: Here is an example of creating and using a new wordlist using ANS
 8148: Forth words:
 8149: 
 8150: @example
 8151: wordlist constant my-new-words-wordlist
 8152: : my-new-words get-order nip my-new-words-wordlist swap set-order ;
 8153: 
 8154: \ add it to the search order
 8155: also my-new-words
 8156: 
 8157: \ alternatively, add it to the search order and make it
 8158: \ the compilation word list
 8159: also my-new-words definitions
 8160: \ type "order" to see the problem
 8161: @end example
 8162: 
 8163: The problem with this example is that @code{order} has no way to
 8164: associate the name @code{my-new-words} with the wid of the word list (in
 8165: Gforth, @code{order} and @code{vocs} will display @code{???}  for a wid
 8166: that has no associated name). There is no Standard way of associating a
 8167: name with a wid.
 8168: 
 8169: In Gforth, this example can be re-coded using @code{vocabulary}, which
 8170: associates a name with a wid:
 8171: 
 8172: @example
 8173: vocabulary my-new-words
 8174: 
 8175: \ add it to the search order
 8176: also my-new-words
 8177: 
 8178: \ alternatively, add it to the search order and make it
 8179: \ the compilation word list
 8180: my-new-words definitions
 8181: \ type "order" to see that the problem is solved
 8182: @end example
 8183: 
 8184: 
 8185: @node Why use word lists?, Word list example, Vocabularies, Word Lists
 8186: @subsection Why use word lists?
 8187: @cindex word lists - why use them?
 8188: 
 8189: Here are some reasons why people use wordlists:
 8190: 
 8191: @itemize @bullet
 8192: 
 8193: @c anton: Gforth's hashing implementation makes the search speed
 8194: @c independent from the number of words.  But it is linear with the number
 8195: @c of wordlists that have to be searched, so in effect using more wordlists
 8196: @c actually slows down compilation.
 8197: 
 8198: @c @item
 8199: @c To improve compilation speed by reducing the number of header space
 8200: @c entries that must be searched. This is achieved by creating a new
 8201: @c word list that contains all of the definitions that are used in the
 8202: @c definition of a Forth system but which would not usually be used by
 8203: @c programs running on that system. That word list would be on the search
 8204: @c list when the Forth system was compiled but would be removed from the
 8205: @c search list for normal operation. This can be a useful technique for
 8206: @c low-performance systems (for example, 8-bit processors in embedded
 8207: @c systems) but is unlikely to be necessary in high-performance desktop
 8208: @c systems.
 8209: 
 8210: @item
 8211: To prevent a set of words from being used outside the context in which
 8212: they are valid. Two classic examples of this are an integrated editor
 8213: (all of the edit commands are defined in a separate word list; the
 8214: search order is set to the editor word list when the editor is invoked;
 8215: the old search order is restored when the editor is terminated) and an
 8216: integrated assembler (the op-codes for the machine are defined in a
 8217: separate word list which is used when a @code{CODE} word is defined).
 8218: 
 8219: @item
 8220: To organize the words of an application or library into a user-visible
 8221: set (in @code{forth-wordlist} or some other common wordlist) and a set
 8222: of helper words used just for the implementation (hidden in a separate
 8223: wordlist).  This keeps @code{words}' output smaller, separates
 8224: implementation and interface, and reduces the chance of name conflicts
 8225: within the common wordlist.
 8226: 
 8227: @item
 8228: To prevent a name-space clash between multiple definitions with the same
 8229: name. For example, when building a cross-compiler you might have a word
 8230: @code{IF} that generates conditional code for your target system. By
 8231: placing this definition in a different word list you can control whether
 8232: the host system's @code{IF} or the target system's @code{IF} get used in
 8233: any particular context by controlling the order of the word lists on the
 8234: search order stack.
 8235: 
 8236: @end itemize
 8237: 
 8238: The downsides of using wordlists are:
 8239: 
 8240: @itemize
 8241: 
 8242: @item
 8243: Debugging becomes more cumbersome.
 8244: 
 8245: @item
 8246: Name conflicts worked around with wordlists are still there, and you
 8247: have to arrange the search order carefully to get the desired results;
 8248: if you forget to do that, you get hard-to-find errors (as in any case
 8249: where you read the code differently from the compiler; @code{see} can
 8250: help seeing which of several possible words the name resolves to in such
 8251: cases).  @code{See} displays just the name of the words, not what
 8252: wordlist they belong to, so it might be misleading.  Using unique names
 8253: is a better approach to avoid name conflicts.
 8254: 
 8255: @item
 8256: You have to explicitly undo any changes to the search order.  In many
 8257: cases it would be more convenient if this happened implicitly.  Gforth
 8258: currently does not provide such a feature, but it may do so in the
 8259: future.
 8260: @end itemize
 8261: 
 8262: 
 8263: @node Word list example,  , Why use word lists?, Word Lists
 8264: @subsection Word list example
 8265: @cindex word lists - example
 8266: 
 8267: The following example is from the
 8268: @uref{http://www.complang.tuwien.ac.at/forth/garbage-collection.zip,
 8269: garbage collector} and uses wordlists to separate public words from
 8270: helper words:
 8271: 
 8272: @example
 8273: get-current ( wid )
 8274: vocabulary garbage-collector also garbage-collector definitions
 8275: ... \ define helper words
 8276: ( wid ) set-current \ restore original (i.e., public) compilation wordlist
 8277: ... \ define the public (i.e., API) words
 8278:     \ they can refer to the helper words
 8279: previous \ restore original search order (helper words become invisible)
 8280: @end example
 8281: 
 8282: @c -------------------------------------------------------------
 8283: @node Environmental Queries, Files, Word Lists, Words
 8284: @section Environmental Queries
 8285: @cindex environmental queries
 8286: 
 8287: ANS Forth introduced the idea of ``environmental queries'' as a way
 8288: for a program running on a system to determine certain characteristics of the system.
 8289: The Standard specifies a number of strings that might be recognised by a system.
 8290: 
 8291: The Standard requires that the header space used for environmental queries
 8292: be distinct from the header space used for definitions.
 8293: 
 8294: Typically, environmental queries are supported by creating a set of
 8295: definitions in a word list that is @i{only} used during environmental
 8296: queries; that is what Gforth does. There is no Standard way of adding
 8297: definitions to the set of recognised environmental queries, but any
 8298: implementation that supports the loading of optional word sets must have
 8299: some mechanism for doing this (after loading the word set, the
 8300: associated environmental query string must return @code{true}). In
 8301: Gforth, the word list used to honour environmental queries can be
 8302: manipulated just like any other word list.
 8303: 
 8304: 
 8305: doc-environment?
 8306: doc-environment-wordlist
 8307: 
 8308: doc-gforth
 8309: doc-os-class
 8310: 
 8311: 
 8312: Note that, whilst the documentation for (e.g.) @code{gforth} shows it
 8313: returning two items on the stack, querying it using @code{environment?}
 8314: will return an additional item; the @code{true} flag that shows that the
 8315: string was recognised.
 8316: 
 8317: @comment TODO Document the standard strings or note where they are documented herein
 8318: 
 8319: Here are some examples of using environmental queries:
 8320: 
 8321: @example
 8322: s" address-unit-bits" environment? 0=
 8323: [IF]
 8324:      cr .( environmental attribute address-units-bits unknown... ) cr
 8325: [ELSE]
 8326:      drop \ ensure balanced stack effect
 8327: [THEN]
 8328: 
 8329: \ this might occur in the prelude of a standard program that uses THROW
 8330: s" exception" environment? [IF]
 8331:    0= [IF]
 8332:       : throw abort" exception thrown" ;
 8333:    [THEN]
 8334: [ELSE] \ we don't know, so make sure
 8335:    : throw abort" exception thrown" ;
 8336: [THEN]
 8337: 
 8338: s" gforth" environment? [IF] .( Gforth version ) TYPE
 8339:                         [ELSE] .( Not Gforth..) [THEN]
 8340: 
 8341: \ a program using v*
 8342: s" gforth" environment? [IF]
 8343:   s" 0.5.0" compare 0< [IF] \ v* is a primitive since 0.5.0
 8344:    : v* ( f_addr1 nstride1 f_addr2 nstride2 ucount -- r )
 8345:      >r swap 2swap swap 0e r> 0 ?DO
 8346:        dup f@@ over + 2swap dup f@@ f* f+ over + 2swap
 8347:      LOOP
 8348:      2drop 2drop ; 
 8349:   [THEN]
 8350: [ELSE] \ 
 8351:   : v* ( f_addr1 nstride1 f_addr2 nstride2 ucount -- r )
 8352:   ...
 8353: [THEN]
 8354: @end example
 8355: 
 8356: Here is an example of adding a definition to the environment word list:
 8357: 
 8358: @example
 8359: get-current environment-wordlist set-current
 8360: true constant block
 8361: true constant block-ext
 8362: set-current
 8363: @end example
 8364: 
 8365: You can see what definitions are in the environment word list like this:
 8366: 
 8367: @example
 8368: environment-wordlist >order words previous
 8369: @end example
 8370: 
 8371: 
 8372: @c -------------------------------------------------------------
 8373: @node Files, Blocks, Environmental Queries, Words
 8374: @section Files
 8375: @cindex files
 8376: @cindex I/O - file-handling
 8377: 
 8378: Gforth provides facilities for accessing files that are stored in the
 8379: host operating system's file-system. Files that are processed by Gforth
 8380: can be divided into two categories:
 8381: 
 8382: @itemize @bullet
 8383: @item
 8384: Files that are processed by the Text Interpreter (@dfn{Forth source files}).
 8385: @item
 8386: Files that are processed by some other program (@dfn{general files}).
 8387: @end itemize
 8388: 
 8389: @menu
 8390: * Forth source files::          
 8391: * General files::               
 8392: * Redirection::                 
 8393: * Search Paths::                
 8394: @end menu
 8395: 
 8396: @c -------------------------------------------------------------
 8397: @node Forth source files, General files, Files, Files
 8398: @subsection Forth source files
 8399: @cindex including files
 8400: @cindex Forth source files
 8401: 
 8402: The simplest way to interpret the contents of a file is to use one of
 8403: these two formats:
 8404: 
 8405: @example
 8406: include mysource.fs
 8407: s" mysource.fs" included
 8408: @end example
 8409: 
 8410: You usually want to include a file only if it is not included already
 8411: (by, say, another source file). In that case, you can use one of these
 8412: three formats:
 8413: 
 8414: @example
 8415: require mysource.fs
 8416: needs mysource.fs
 8417: s" mysource.fs" required
 8418: @end example
 8419: 
 8420: @cindex stack effect of included files
 8421: @cindex including files, stack effect
 8422: It is good practice to write your source files such that interpreting them
 8423: does not change the stack. Source files designed in this way can be used with
 8424: @code{required} and friends without complications. For example:
 8425: 
 8426: @example
 8427: 1024 require foo.fs drop
 8428: @end example
 8429: 
 8430: Here you want to pass the argument 1024 (e.g., a buffer size) to
 8431: @file{foo.fs}.  Interpreting @file{foo.fs} has the stack effect ( n -- n
 8432: ), which allows its use with @code{require}.  Of course with such
 8433: parameters to required files, you have to ensure that the first
 8434: @code{require} fits for all uses (i.e., @code{require} it early in the
 8435: master load file).
 8436: 
 8437: doc-include-file
 8438: doc-included
 8439: doc-included?
 8440: doc-include
 8441: doc-required
 8442: doc-require
 8443: doc-needs
 8444: @c doc-init-included-files @c internal
 8445: doc-sourcefilename
 8446: doc-sourceline#
 8447: 
 8448: A definition in ANS Forth for @code{required} is provided in
 8449: @file{compat/required.fs}.
 8450: 
 8451: @c -------------------------------------------------------------
 8452: @node General files, Redirection, Forth source files, Files
 8453: @subsection General files
 8454: @cindex general files
 8455: @cindex file-handling
 8456: 
 8457: Files are opened/created by name and type. The following file access
 8458: methods (FAMs) are recognised:
 8459: 
 8460: @cindex fam (file access method)
 8461: doc-r/o
 8462: doc-r/w
 8463: doc-w/o
 8464: doc-bin
 8465: 
 8466: 
 8467: When a file is opened/created, it returns a file identifier,
 8468: @i{wfileid} that is used for all other file commands. All file
 8469: commands also return a status value, @i{wior}, that is 0 for a
 8470: successful operation and an implementation-defined non-zero value in the
 8471: case of an error.
 8472: 
 8473: 
 8474: doc-open-file
 8475: doc-create-file
 8476: 
 8477: doc-close-file
 8478: doc-delete-file
 8479: doc-rename-file
 8480: doc-read-file
 8481: doc-read-line
 8482: doc-key-file
 8483: doc-key?-file
 8484: doc-write-file
 8485: doc-write-line
 8486: doc-emit-file
 8487: doc-flush-file
 8488: 
 8489: doc-file-status
 8490: doc-file-position
 8491: doc-reposition-file
 8492: doc-file-size
 8493: doc-resize-file
 8494: 
 8495: doc-slurp-file
 8496: doc-slurp-fid
 8497: doc-stdin
 8498: doc-stdout
 8499: doc-stderr
 8500: 
 8501: @c ---------------------------------------------------------
 8502: @node Redirection, Search Paths, General files, Files
 8503: @subsection Redirection
 8504: @cindex Redirection
 8505: @cindex Input Redirection
 8506: @cindex Output Redirection
 8507: 
 8508: You can redirect the output of @code{type} and @code{emit} and all the
 8509: words that use them (all output words that don't have an explicit
 8510: target file) to an arbitrary file with the @code{outfile-execute},
 8511: used like this:
 8512: 
 8513: @example
 8514: : some-warning ( n -- )
 8515:     cr ." warning# " . ;
 8516: 
 8517: : print-some-warning ( n -- )
 8518:     ['] some-warning stderr outfile-execute ;
 8519: @end example
 8520: 
 8521: After @code{some-warning} is executed, the original output direction
 8522: is restored; this construct is safe against exceptions.  Similarly,
 8523: there is @code{infile-execute} for redirecting the input of @code{key}
 8524: and its users (any input word that does not take a file explicitly).
 8525: 
 8526: doc-outfile-execute
 8527: doc-infile-execute
 8528: 
 8529: If you do not want to redirect the input or output to a file, you can
 8530: also make use of the fact that @code{key}, @code{emit} and @code{type}
 8531: are deferred words (@pxref{Deferred Words}).  However, in that case
 8532: you have to worry about the restoration and the protection against
 8533: exceptions yourself; also, note that for redirecting the output in
 8534: this way, you have to redirect both @code{emit} and @code{type}.
 8535: 
 8536: @c ---------------------------------------------------------
 8537: @node Search Paths,  , Redirection, Files
 8538: @subsection Search Paths
 8539: @cindex path for @code{included}
 8540: @cindex file search path
 8541: @cindex @code{include} search path
 8542: @cindex search path for files
 8543: 
 8544: If you specify an absolute filename (i.e., a filename starting with
 8545: @file{/} or @file{~}, or with @file{:} in the second position (as in
 8546: @samp{C:...})) for @code{included} and friends, that file is included
 8547: just as you would expect.
 8548: 
 8549: If the filename starts with @file{./}, this refers to the directory that
 8550: the present file was @code{included} from.  This allows files to include
 8551: other files relative to their own position (irrespective of the current
 8552: working directory or the absolute position).  This feature is essential
 8553: for libraries consisting of several files, where a file may include
 8554: other files from the library.  It corresponds to @code{#include "..."}
 8555: in C. If the current input source is not a file, @file{.} refers to the
 8556: directory of the innermost file being included, or, if there is no file
 8557: being included, to the current working directory.
 8558: 
 8559: For relative filenames (not starting with @file{./}), Gforth uses a
 8560: search path similar to Forth's search order (@pxref{Word Lists}). It
 8561: tries to find the given filename in the directories present in the path,
 8562: and includes the first one it finds. There are separate search paths for
 8563: Forth source files and general files.  If the search path contains the
 8564: directory @file{.}, this refers to the directory of the current file, or
 8565: the working directory, as if the file had been specified with @file{./}.
 8566: 
 8567: Use @file{~+} to refer to the current working directory (as in the
 8568: @code{bash}).
 8569: 
 8570: @c anton: fold the following subsubsections into this subsection?
 8571: 
 8572: @menu
 8573: * Source Search Paths::         
 8574: * General Search Paths::        
 8575: @end menu
 8576: 
 8577: @c ---------------------------------------------------------
 8578: @node Source Search Paths, General Search Paths, Search Paths, Search Paths
 8579: @subsubsection Source Search Paths
 8580: @cindex search path control, source files
 8581: 
 8582: The search path is initialized when you start Gforth (@pxref{Invoking
 8583: Gforth}). You can display it and change it using @code{fpath} in
 8584: combination with the general path handling words.
 8585: 
 8586: doc-fpath
 8587: @c the functionality of the following words is easily available through
 8588: @c   fpath and the general path words.  The may go away.
 8589: @c doc-.fpath
 8590: @c doc-fpath+
 8591: @c doc-fpath=
 8592: @c doc-open-fpath-file
 8593: 
 8594: @noindent
 8595: Here is an example of using @code{fpath} and @code{require}:
 8596: 
 8597: @example
 8598: fpath path= /usr/lib/forth/|./
 8599: require timer.fs
 8600: @end example
 8601: 
 8602: 
 8603: @c ---------------------------------------------------------
 8604: @node General Search Paths,  , Source Search Paths, Search Paths
 8605: @subsubsection General Search Paths
 8606: @cindex search path control, source files
 8607: 
 8608: Your application may need to search files in several directories, like
 8609: @code{included} does. To facilitate this, Gforth allows you to define
 8610: and use your own search paths, by providing generic equivalents of the
 8611: Forth search path words:
 8612: 
 8613: doc-open-path-file
 8614: doc-path-allot
 8615: doc-clear-path
 8616: doc-also-path
 8617: doc-.path
 8618: doc-path+
 8619: doc-path=
 8620: 
 8621: @c anton: better define a word for it, say "path-allot ( ucount -- path-addr )
 8622: 
 8623: Here's an example of creating an empty search path:
 8624: @c
 8625: @example
 8626: create mypath 500 path-allot \ maximum length 500 chars (is checked)
 8627: @end example
 8628: 
 8629: @c -------------------------------------------------------------
 8630: @node Blocks, Other I/O, Files, Words
 8631: @section Blocks
 8632: @cindex I/O - blocks
 8633: @cindex blocks
 8634: 
 8635: When you run Gforth on a modern desk-top computer, it runs under the
 8636: control of an operating system which provides certain services.  One of
 8637: these services is @var{file services}, which allows Forth source code
 8638: and data to be stored in files and read into Gforth (@pxref{Files}).
 8639: 
 8640: Traditionally, Forth has been an important programming language on
 8641: systems where it has interfaced directly to the underlying hardware with
 8642: no intervening operating system. Forth provides a mechanism, called
 8643: @dfn{blocks}, for accessing mass storage on such systems.
 8644: 
 8645: A block is a 1024-byte data area, which can be used to hold data or
 8646: Forth source code. No structure is imposed on the contents of the
 8647: block. A block is identified by its number; blocks are numbered
 8648: contiguously from 1 to an implementation-defined maximum.
 8649: 
 8650: A typical system that used blocks but no operating system might use a
 8651: single floppy-disk drive for mass storage, with the disks formatted to
 8652: provide 256-byte sectors. Blocks would be implemented by assigning the
 8653: first four sectors of the disk to block 1, the second four sectors to
 8654: block 2 and so on, up to the limit of the capacity of the disk. The disk
 8655: would not contain any file system information, just the set of blocks.
 8656: 
 8657: @cindex blocks file
 8658: On systems that do provide file services, blocks are typically
 8659: implemented by storing a sequence of blocks within a single @dfn{blocks
 8660: file}.  The size of the blocks file will be an exact multiple of 1024
 8661: bytes, corresponding to the number of blocks it contains. This is the
 8662: mechanism that Gforth uses.
 8663: 
 8664: @cindex @file{blocks.fb}
 8665: Only one blocks file can be open at a time. If you use block words without
 8666: having specified a blocks file, Gforth defaults to the blocks file
 8667: @file{blocks.fb}. Gforth uses the Forth search path when attempting to
 8668: locate a blocks file (@pxref{Source Search Paths}).
 8669: 
 8670: @cindex block buffers
 8671: When you read and write blocks under program control, Gforth uses a
 8672: number of @dfn{block buffers} as intermediate storage. These buffers are
 8673: not used when you use @code{load} to interpret the contents of a block.
 8674: 
 8675: The behaviour of the block buffers is analagous to that of a cache.
 8676: Each block buffer has three states:
 8677: 
 8678: @itemize @bullet
 8679: @item
 8680: Unassigned
 8681: @item
 8682: Assigned-clean
 8683: @item
 8684: Assigned-dirty
 8685: @end itemize
 8686: 
 8687: Initially, all block buffers are @i{unassigned}. In order to access a
 8688: block, the block (specified by its block number) must be assigned to a
 8689: block buffer.
 8690: 
 8691: The assignment of a block to a block buffer is performed by @code{block}
 8692: or @code{buffer}. Use @code{block} when you wish to modify the existing
 8693: contents of a block. Use @code{buffer} when you don't care about the
 8694: existing contents of the block@footnote{The ANS Forth definition of
 8695: @code{buffer} is intended not to cause disk I/O; if the data associated
 8696: with the particular block is already stored in a block buffer due to an
 8697: earlier @code{block} command, @code{buffer} will return that block
 8698: buffer and the existing contents of the block will be
 8699: available. Otherwise, @code{buffer} will simply assign a new, empty
 8700: block buffer for the block.}.
 8701: 
 8702: Once a block has been assigned to a block buffer using @code{block} or
 8703: @code{buffer}, that block buffer becomes the @i{current block
 8704: buffer}. Data may only be manipulated (read or written) within the
 8705: current block buffer.
 8706: 
 8707: When the contents of the current block buffer has been modified it is
 8708: necessary, @emph{before calling @code{block} or @code{buffer} again}, to
 8709: either abandon the changes (by doing nothing) or mark the block as
 8710: changed (assigned-dirty), using @code{update}. Using @code{update} does
 8711: not change the blocks file; it simply changes a block buffer's state to
 8712: @i{assigned-dirty}.  The block will be written implicitly when it's
 8713: buffer is needed for another block, or explicitly by @code{flush} or
 8714: @code{save-buffers}.
 8715: 
 8716: word @code{Flush} writes all @i{assigned-dirty} blocks back to the
 8717: blocks file on disk. Leaving Gforth with @code{bye} also performs a
 8718: @code{flush}.
 8719: 
 8720: In Gforth, @code{block} and @code{buffer} use a @i{direct-mapped}
 8721: algorithm to assign a block buffer to a block. That means that any
 8722: particular block can only be assigned to one specific block buffer,
 8723: called (for the particular operation) the @i{victim buffer}. If the
 8724: victim buffer is @i{unassigned} or @i{assigned-clean} it is allocated to
 8725: the new block immediately. If it is @i{assigned-dirty} its current
 8726: contents are written back to the blocks file on disk before it is
 8727: allocated to the new block.
 8728: 
 8729: Although no structure is imposed on the contents of a block, it is
 8730: traditional to display the contents as 16 lines each of 64 characters.  A
 8731: block provides a single, continuous stream of input (for example, it
 8732: acts as a single parse area) -- there are no end-of-line characters
 8733: within a block, and no end-of-file character at the end of a
 8734: block. There are two consequences of this:
 8735: 
 8736: @itemize @bullet
 8737: @item
 8738: The last character of one line wraps straight into the first character
 8739: of the following line
 8740: @item
 8741: The word @code{\} -- comment to end of line -- requires special
 8742: treatment; in the context of a block it causes all characters until the
 8743: end of the current 64-character ``line'' to be ignored.
 8744: @end itemize
 8745: 
 8746: In Gforth, when you use @code{block} with a non-existent block number,
 8747: the current blocks file will be extended to the appropriate size and the
 8748: block buffer will be initialised with spaces.
 8749: 
 8750: Gforth includes a simple block editor (type @code{use blocked.fb 0 list}
 8751: for details) but doesn't encourage the use of blocks; the mechanism is
 8752: only provided for backward compatibility -- ANS Forth requires blocks to
 8753: be available when files are.
 8754: 
 8755: Common techniques that are used when working with blocks include:
 8756: 
 8757: @itemize @bullet
 8758: @item
 8759: A screen editor that allows you to edit blocks without leaving the Forth
 8760: environment.
 8761: @item
 8762: Shadow screens; where every code block has an associated block
 8763: containing comments (for example: code in odd block numbers, comments in
 8764: even block numbers). Typically, the block editor provides a convenient
 8765: mechanism to toggle between code and comments.
 8766: @item
 8767: Load blocks; a single block (typically block 1) contains a number of
 8768: @code{thru} commands which @code{load} the whole of the application.
 8769: @end itemize
 8770: 
 8771: See Frank Sergeant's Pygmy Forth to see just how well blocks can be
 8772: integrated into a Forth programming environment.
 8773: 
 8774: @comment TODO what about errors on open-blocks?
 8775: 
 8776: doc-open-blocks
 8777: doc-use
 8778: doc-block-offset
 8779: doc-get-block-fid
 8780: doc-block-position
 8781: 
 8782: doc-list
 8783: doc-scr
 8784: 
 8785: doc-block
 8786: doc-buffer
 8787: 
 8788: doc-empty-buffers
 8789: doc-empty-buffer
 8790: doc-update
 8791: doc-updated?
 8792: doc-save-buffers
 8793: doc-save-buffer
 8794: doc-flush
 8795: 
 8796: doc-load
 8797: doc-thru
 8798: doc-+load
 8799: doc-+thru
 8800: doc---gforthman--->
 8801: doc-block-included
 8802: 
 8803: 
 8804: @c -------------------------------------------------------------
 8805: @node Other I/O, OS command line arguments, Blocks, Words
 8806: @section Other I/O
 8807: @cindex I/O - keyboard and display
 8808: 
 8809: @menu
 8810: * Simple numeric output::       Predefined formats
 8811: * Formatted numeric output::    Formatted (pictured) output
 8812: * String Formats::              How Forth stores strings in memory
 8813: * Displaying characters and strings::  Other stuff
 8814: * Terminal output::             Cursor positioning etc.
 8815: * Single-key input::            
 8816: * Line input and conversion::   
 8817: * Pipes::                       How to create your own pipes
 8818: * Xchars and Unicode::          Non-ASCII characters
 8819: @end menu
 8820: 
 8821: @node Simple numeric output, Formatted numeric output, Other I/O, Other I/O
 8822: @subsection Simple numeric output
 8823: @cindex numeric output - simple/free-format
 8824: 
 8825: The simplest output functions are those that display numbers from the
 8826: data or floating-point stacks. Floating-point output is always displayed
 8827: using base 10. Numbers displayed from the data stack use the value stored
 8828: in @code{base}.
 8829: 
 8830: 
 8831: doc-.
 8832: doc-dec.
 8833: doc-hex.
 8834: doc-u.
 8835: doc-.r
 8836: doc-u.r
 8837: doc-d.
 8838: doc-ud.
 8839: doc-d.r
 8840: doc-ud.r
 8841: doc-f.
 8842: doc-fe.
 8843: doc-fs.
 8844: doc-f.rdp
 8845: 
 8846: Examples of printing the number 1234.5678E23 in the different floating-point output
 8847: formats are shown below:
 8848: 
 8849: @example
 8850: f. 123456779999999000000000000.
 8851: fe. 123.456779999999E24
 8852: fs. 1.23456779999999E26
 8853: @end example
 8854: 
 8855: 
 8856: @node Formatted numeric output, String Formats, Simple numeric output, Other I/O
 8857: @subsection Formatted numeric output
 8858: @cindex formatted numeric output
 8859: @cindex pictured numeric output
 8860: @cindex numeric output - formatted
 8861: 
 8862: Forth traditionally uses a technique called @dfn{pictured numeric
 8863: output} for formatted printing of integers.  In this technique, digits
 8864: are extracted from the number (using the current output radix defined by
 8865: @code{base}), converted to ASCII codes and appended to a string that is
 8866: built in a scratch-pad area of memory (@pxref{core-idef,
 8867: Implementation-defined options, Implementation-defined
 8868: options}). Arbitrary characters can be appended to the string during the
 8869: extraction process. The completed string is specified by an address
 8870: and length and can be manipulated (@code{TYPE}ed, copied, modified)
 8871: under program control.
 8872: 
 8873: All of the integer output words described in the previous section
 8874: (@pxref{Simple numeric output}) are implemented in Gforth using pictured
 8875: numeric output.
 8876: 
 8877: Three important things to remember about pictured numeric output:
 8878: 
 8879: @itemize @bullet
 8880: @item
 8881: It always operates on double-precision numbers; to display a
 8882: single-precision number, convert it first (for ways of doing this
 8883: @pxref{Double precision}).
 8884: @item
 8885: It always treats the double-precision number as though it were
 8886: unsigned. The examples below show ways of printing signed numbers.
 8887: @item
 8888: The string is built up from right to left; least significant digit first.
 8889: @end itemize
 8890: 
 8891: 
 8892: doc-<#
 8893: doc-<<#
 8894: doc-#
 8895: doc-#s
 8896: doc-hold
 8897: doc-sign
 8898: doc-#>
 8899: doc-#>>
 8900: 
 8901: doc-represent
 8902: doc-f>str-rdp
 8903: doc-f>buf-rdp
 8904: 
 8905: 
 8906: @noindent
 8907: Here are some examples of using pictured numeric output:
 8908: 
 8909: @example
 8910: : my-u. ( u -- )
 8911:   \ Simplest use of pns.. behaves like Standard u. 
 8912:   0              \ convert to unsigned double
 8913:   <<#            \ start conversion
 8914:   #s             \ convert all digits
 8915:   #>             \ complete conversion
 8916:   TYPE SPACE     \ display, with trailing space
 8917:   #>> ;          \ release hold area
 8918: 
 8919: : cents-only ( u -- )
 8920:   0              \ convert to unsigned double
 8921:   <<#            \ start conversion
 8922:   # #            \ convert two least-significant digits
 8923:   #>             \ complete conversion, discard other digits
 8924:   TYPE SPACE     \ display, with trailing space
 8925:   #>> ;          \ release hold area
 8926: 
 8927: : dollars-and-cents ( u -- )
 8928:   0              \ convert to unsigned double
 8929:   <<#            \ start conversion
 8930:   # #            \ convert two least-significant digits
 8931:   [char] . hold  \ insert decimal point
 8932:   #s             \ convert remaining digits
 8933:   [char] $ hold  \ append currency symbol
 8934:   #>             \ complete conversion
 8935:   TYPE SPACE     \ display, with trailing space
 8936:   #>> ;          \ release hold area
 8937: 
 8938: : my-. ( n -- )
 8939:   \ handling negatives.. behaves like Standard .
 8940:   s>d            \ convert to signed double
 8941:   swap over dabs \ leave sign byte followed by unsigned double
 8942:   <<#            \ start conversion
 8943:   #s             \ convert all digits
 8944:   rot sign       \ get at sign byte, append "-" if needed
 8945:   #>             \ complete conversion
 8946:   TYPE SPACE     \ display, with trailing space
 8947:   #>> ;          \ release hold area
 8948: 
 8949: : account. ( n -- )
 8950:   \ accountants don't like minus signs, they use parentheses
 8951:   \ for negative numbers
 8952:   s>d            \ convert to signed double
 8953:   swap over dabs \ leave sign byte followed by unsigned double
 8954:   <<#            \ start conversion
 8955:   2 pick         \ get copy of sign byte
 8956:   0< IF [char] ) hold THEN \ right-most character of output
 8957:   #s             \ convert all digits
 8958:   rot            \ get at sign byte
 8959:   0< IF [char] ( hold THEN
 8960:   #>             \ complete conversion
 8961:   TYPE SPACE     \ display, with trailing space
 8962:   #>> ;          \ release hold area
 8963: 
 8964: @end example
 8965: 
 8966: Here are some examples of using these words:
 8967: 
 8968: @example
 8969: 1 my-u. 1
 8970: hex -1 my-u. decimal FFFFFFFF
 8971: 1 cents-only 01
 8972: 1234 cents-only 34
 8973: 2 dollars-and-cents $0.02
 8974: 1234 dollars-and-cents $12.34
 8975: 123 my-. 123
 8976: -123 my. -123
 8977: 123 account. 123
 8978: -456 account. (456)
 8979: @end example
 8980: 
 8981: 
 8982: @node String Formats, Displaying characters and strings, Formatted numeric output, Other I/O
 8983: @subsection String Formats
 8984: @cindex strings - see character strings
 8985: @cindex character strings - formats
 8986: @cindex I/O - see character strings
 8987: @cindex counted strings
 8988: 
 8989: @c anton: this does not really belong here; maybe the memory section,
 8990: @c  or the principles chapter
 8991: 
 8992: Forth commonly uses two different methods for representing character
 8993: strings:
 8994: 
 8995: @itemize @bullet
 8996: @item
 8997: @cindex address of counted string
 8998: @cindex counted string
 8999: As a @dfn{counted string}, represented by a @i{c-addr}. The char
 9000: addressed by @i{c-addr} contains a character-count, @i{n}, of the
 9001: string and the string occupies the subsequent @i{n} char addresses in
 9002: memory.
 9003: @item
 9004: As cell pair on the stack; @i{c-addr u}, where @i{u} is the length
 9005: of the string in characters, and @i{c-addr} is the address of the
 9006: first byte of the string.
 9007: @end itemize
 9008: 
 9009: ANS Forth encourages the use of the second format when representing
 9010: strings.
 9011: 
 9012: 
 9013: doc-count
 9014: 
 9015: 
 9016: For words that move, copy and search for strings see @ref{Memory
 9017: Blocks}. For words that display characters and strings see
 9018: @ref{Displaying characters and strings}.
 9019: 
 9020: @node Displaying characters and strings, Terminal output, String Formats, Other I/O
 9021: @subsection Displaying characters and strings
 9022: @cindex characters - compiling and displaying
 9023: @cindex character strings - compiling and displaying
 9024: 
 9025: This section starts with a glossary of Forth words and ends with a set
 9026: of examples.
 9027: 
 9028: doc-bl
 9029: doc-space
 9030: doc-spaces
 9031: doc-emit
 9032: doc-toupper
 9033: doc-."
 9034: doc-.(
 9035: doc-.\"
 9036: doc-type
 9037: doc-typewhite
 9038: doc-cr
 9039: @cindex cursor control
 9040: doc-s"
 9041: doc-s\"
 9042: doc-c"
 9043: doc-char
 9044: doc-[char]
 9045: 
 9046: 
 9047: @noindent
 9048: As an example, consider the following text, stored in a file @file{test.fs}:
 9049: 
 9050: @example
 9051: .( text-1)
 9052: : my-word
 9053:   ." text-2" cr
 9054:   .( text-3)
 9055: ;
 9056: 
 9057: ." text-4"
 9058: 
 9059: : my-char
 9060:   [char] ALPHABET emit
 9061:   char emit
 9062: ;
 9063: @end example
 9064: 
 9065: When you load this code into Gforth, the following output is generated:
 9066: 
 9067: @example
 9068: @kbd{include test.fs @key{RET}} text-1text-3text-4 ok
 9069: @end example
 9070: 
 9071: @itemize @bullet
 9072: @item
 9073: Messages @code{text-1} and @code{text-3} are displayed because @code{.(} 
 9074: is an immediate word; it behaves in the same way whether it is used inside
 9075: or outside a colon definition.
 9076: @item
 9077: Message @code{text-4} is displayed because of Gforth's added interpretation
 9078: semantics for @code{."}.
 9079: @item
 9080: Message @code{text-2} is @i{not} displayed, because the text interpreter
 9081: performs the compilation semantics for @code{."} within the definition of
 9082: @code{my-word}.
 9083: @end itemize
 9084: 
 9085: Here are some examples of executing @code{my-word} and @code{my-char}:
 9086: 
 9087: @example
 9088: @kbd{my-word @key{RET}} text-2
 9089:  ok
 9090: @kbd{my-char fred @key{RET}} Af ok
 9091: @kbd{my-char jim @key{RET}} Aj ok
 9092: @end example
 9093: 
 9094: @itemize @bullet
 9095: @item
 9096: Message @code{text-2} is displayed because of the run-time behaviour of
 9097: @code{."}.
 9098: @item
 9099: @code{[char]} compiles the ``A'' from ``ALPHABET'' and puts its display code
 9100: on the stack at run-time. @code{emit} always displays the character
 9101: when @code{my-char} is executed.
 9102: @item
 9103: @code{char} parses a string at run-time and the second @code{emit} displays
 9104: the first character of the string.
 9105: @item
 9106: If you type @code{see my-char} you can see that @code{[char]} discarded
 9107: the text ``LPHABET'' and only compiled the display code for ``A'' into the
 9108: definition of @code{my-char}.
 9109: @end itemize
 9110: 
 9111: 
 9112: @node Terminal output, Single-key input, Displaying characters and strings, Other I/O
 9113: @subsection Terminal output
 9114: @cindex output to terminal
 9115: @cindex terminal output
 9116: 
 9117: If you are outputting to a terminal, you may want to control the
 9118: positioning of the cursor:
 9119: @cindex cursor positioning
 9120: 
 9121: doc-at-xy
 9122: 
 9123: In order to know where to position the cursor, it is often helpful to
 9124: know the size of the screen:
 9125: @cindex terminal size 
 9126: 
 9127: doc-form
 9128: 
 9129: And sometimes you want to use:
 9130: @cindex clear screen
 9131: 
 9132: doc-page
 9133: 
 9134: Note that on non-terminals you should use @code{12 emit}, not
 9135: @code{page}, to get a form feed.
 9136: 
 9137: 
 9138: @node Single-key input, Line input and conversion, Terminal output, Other I/O
 9139: @subsection Single-key input
 9140: @cindex single-key input
 9141: @cindex input, single-key
 9142: 
 9143: If you want to get a single printable character, you can use
 9144: @code{key}; to check whether a character is available for @code{key},
 9145: you can use @code{key?}.
 9146: 
 9147: doc-key
 9148: doc-key?
 9149: 
 9150: If you want to process a mix of printable and non-printable
 9151: characters, you can do that with @code{ekey} and friends.  @code{Ekey}
 9152: produces a keyboard event that you have to convert into a character
 9153: with @code{ekey>char} or into a key identifier with @code{ekey>fkey}.
 9154: 
 9155: Typical code for using EKEY looks like this:
 9156: 
 9157: @example
 9158: ekey ekey>char if ( c )
 9159:   ... \ do something with the character
 9160: else ekey>fkey if ( key-id )
 9161:   case
 9162:     k-up                                  of ... endof
 9163:     k-f1                                  of ... endof
 9164:     k-left k-shift-mask or k-ctrl-mask or of ... endof
 9165:     ...
 9166:   endcase
 9167: else ( keyboard-event )
 9168:   drop \ just ignore an unknown keyboard event type
 9169: then then
 9170: @end example
 9171: 
 9172: doc-ekey
 9173: doc-ekey>char
 9174: doc-ekey>fkey
 9175: doc-ekey?
 9176: 
 9177: The key identifiers for cursor keys are:
 9178: 
 9179: doc-k-left
 9180: doc-k-right
 9181: doc-k-up
 9182: doc-k-down
 9183: doc-k-home
 9184: doc-k-end
 9185: doc-k-prior
 9186: doc-k-next
 9187: doc-k-insert
 9188: doc-k-delete
 9189: 
 9190: The key identifiers for function keys (aka keypad keys) are:
 9191: 
 9192: doc-k-f1
 9193: doc-k-f2
 9194: doc-k-f3
 9195: doc-k-f4
 9196: doc-k-f5
 9197: doc-k-f6
 9198: doc-k-f7
 9199: doc-k-f8
 9200: doc-k-f9
 9201: doc-k-f10
 9202: doc-k-f11
 9203: doc-k-f12
 9204: 
 9205: Note that @code{k-f11} and @code{k-f12} are not as widely available.
 9206: 
 9207: You can combine these key identifiers with masks for various shift keys:
 9208: 
 9209: doc-k-shift-mask
 9210: doc-k-ctrl-mask
 9211: doc-k-alt-mask
 9212: 
 9213: Note that, even if a Forth system has @code{ekey>fkey} and the key
 9214: identifier words, the keys are not necessarily available or it may not
 9215: necessarily be able to report all the keys and all the possible
 9216: combinations with shift masks.  Therefore, write your programs in such
 9217: a way that they are still useful even if the keys and key combinations
 9218: cannot be pressed or are not recognized.
 9219: 
 9220: Examples: Older keyboards often do not have an F11 and F12 key.  If
 9221: you run Gforth in an xterm, the xterm catches a number of combinations
 9222: (e.g., @key{Shift-Up}), and never passes it to Gforth.  Finally,
 9223: Gforth currently does not recognize and report combinations with
 9224: multiple shift keys (so the @key{shift-ctrl-left} case in the example
 9225: above would never be entered).
 9226: 
 9227: Gforth recognizes various keys available on ANSI terminals (in MS-DOS
 9228: you need the ANSI.SYS driver to get that behaviour); it works by
 9229: recognizing the escape sequences that ANSI terminals send when such a
 9230: key is pressed.  If you have a terminal that sends other escape
 9231: sequences, you will not get useful results on Gforth.  Other Forth
 9232: systems may work in a different way.
 9233: 
 9234: 
 9235: @node  Line input and conversion, Pipes, Single-key input, Other I/O
 9236: @subsection Line input and conversion
 9237: @cindex line input from terminal
 9238: @cindex input, linewise from terminal
 9239: @cindex convertin strings to numbers
 9240: @cindex I/O - see input
 9241: 
 9242: For ways of storing character strings in memory see @ref{String Formats}.
 9243: 
 9244: @comment TODO examples for >number >float accept key key? pad parse word refill
 9245: @comment then index them
 9246: 
 9247: Words for inputting one line from the keyboard:
 9248: 
 9249: doc-accept
 9250: doc-edit-line
 9251: 
 9252: Conversion words:
 9253: 
 9254: doc-s>number?
 9255: doc-s>unumber?
 9256: doc->number
 9257: doc->float
 9258: 
 9259: 
 9260: @comment obsolescent words..
 9261: Obsolescent input and conversion words:
 9262: 
 9263: doc-convert
 9264: doc-expect
 9265: doc-span
 9266: 
 9267: 
 9268: @node Pipes, Xchars and Unicode, Line input and conversion, Other I/O
 9269: @subsection Pipes
 9270: @cindex pipes, creating your own
 9271: 
 9272: In addition to using Gforth in pipes created by other processes
 9273: (@pxref{Gforth in pipes}), you can create your own pipe with
 9274: @code{open-pipe}, and read from or write to it.
 9275: 
 9276: doc-open-pipe
 9277: doc-close-pipe
 9278: 
 9279: If you write to a pipe, Gforth can throw a @code{broken-pipe-error}; if
 9280: you don't catch this exception, Gforth will catch it and exit, usually
 9281: silently (@pxref{Gforth in pipes}).  Since you probably do not want
 9282: this, you should wrap a @code{catch} or @code{try} block around the code
 9283: from @code{open-pipe} to @code{close-pipe}, so you can deal with the
 9284: problem yourself, and then return to regular processing.
 9285: 
 9286: doc-broken-pipe-error
 9287: 
 9288: @node Xchars and Unicode,  , Pipes, Other I/O
 9289: @subsection Xchars and Unicode
 9290: 
 9291: ASCII is only appropriate for the English language. Most western
 9292: languages however fit somewhat into the Forth frame, since a byte is
 9293: sufficient to encode the few special characters in each (though not
 9294: always the same encoding can be used; latin-1 is most widely used,
 9295: though). For other languages, different char-sets have to be used,
 9296: several of them variable-width. Most prominent representant is
 9297: UTF-8. Let's call these extended characters xchars. The primitive
 9298: fixed-size characters stored as bytes are called pchars in this
 9299: section.
 9300: 
 9301: The xchar words add a few data types:
 9302: 
 9303: @itemize
 9304: 
 9305: @item
 9306: @var{xc} is an extended char (xchar) on the stack. It occupies one cell,
 9307: and is a subset of unsigned cell. Note: UTF-8 can not store more that
 9308: 31 bits; on 16 bit systems, only the UCS16 subset of the UTF-8
 9309: character set can be used.
 9310: 
 9311: @item
 9312: @var{xc-addr} is the address of an xchar in memory. Alignment
 9313: requirements are the same as @var{c-addr}. The memory representation of an
 9314: xchar differs from the stack representation, and depends on the
 9315: encoding used. An xchar may use a variable number of pchars in memory.
 9316: 
 9317: @item
 9318: @var{xc-addr} @var{u} is a buffer of xchars in memory, starting at
 9319: @var{xc-addr}, @var{u} pchars long.
 9320: 
 9321: @end itemize
 9322: 
 9323: doc-xc-size
 9324: doc-x-size
 9325: doc-xc@+
 9326: doc-xc!+?
 9327: doc-xchar+
 9328: doc-xchar-
 9329: doc-+x/string
 9330: doc-x\string-
 9331: doc--trailing-garbage
 9332: doc-x-width
 9333: doc-xkey
 9334: doc-xemit
 9335: 
 9336: There's a new environment query
 9337: 
 9338: doc-xchar-encoding
 9339: 
 9340: @node OS command line arguments, Locals, Other I/O, Words
 9341: @section OS command line arguments
 9342: @cindex OS command line arguments
 9343: @cindex command line arguments, OS
 9344: @cindex arguments, OS command line
 9345: 
 9346: The usual way to pass arguments to Gforth programs on the command line
 9347: is via the @option{-e} option, e.g.
 9348: 
 9349: @example
 9350: gforth -e "123 456" foo.fs -e bye
 9351: @end example
 9352: 
 9353: However, you may want to interpret the command-line arguments directly.
 9354: In that case, you can access the (image-specific) command-line arguments
 9355: through @code{next-arg}:
 9356: 
 9357: doc-next-arg
 9358: 
 9359: Here's an example program @file{echo.fs} for @code{next-arg}:
 9360: 
 9361: @example
 9362: : echo ( -- )
 9363:     begin
 9364: 	next-arg 2dup 0 0 d<> while
 9365: 	    type space
 9366:     repeat
 9367:     2drop ;
 9368: 
 9369: echo cr bye
 9370: @end example
 9371: 
 9372: This can be invoked with
 9373: 
 9374: @example
 9375: gforth echo.fs hello world
 9376: @end example
 9377: 
 9378: and it will print
 9379: 
 9380: @example
 9381: hello world
 9382: @end example
 9383: 
 9384: The next lower level of dealing with the OS command line are the
 9385: following words:
 9386: 
 9387: doc-arg
 9388: doc-shift-args
 9389: 
 9390: Finally, at the lowest level Gforth provides the following words:
 9391: 
 9392: doc-argc
 9393: doc-argv
 9394: 
 9395: @c -------------------------------------------------------------
 9396: @node Locals, Structures, OS command line arguments, Words
 9397: @section Locals
 9398: @cindex locals
 9399: 
 9400: Local variables can make Forth programming more enjoyable and Forth
 9401: programs easier to read. Unfortunately, the locals of ANS Forth are
 9402: laden with restrictions. Therefore, we provide not only the ANS Forth
 9403: locals wordset, but also our own, more powerful locals wordset (we
 9404: implemented the ANS Forth locals wordset through our locals wordset).
 9405: 
 9406: The ideas in this section have also been published in M. Anton Ertl,
 9407: @cite{@uref{http://www.complang.tuwien.ac.at/papers/ertl94l.ps.gz,
 9408: Automatic Scoping of Local Variables}}, EuroForth '94.
 9409: 
 9410: @menu
 9411: * Gforth locals::               
 9412: * ANS Forth locals::            
 9413: @end menu
 9414: 
 9415: @node Gforth locals, ANS Forth locals, Locals, Locals
 9416: @subsection Gforth locals
 9417: @cindex Gforth locals
 9418: @cindex locals, Gforth style
 9419: 
 9420: Locals can be defined with
 9421: 
 9422: @example
 9423: @{ local1 local2 ... -- comment @}
 9424: @end example
 9425: or
 9426: @example
 9427: @{ local1 local2 ... @}
 9428: @end example
 9429: 
 9430: E.g.,
 9431: @example
 9432: : max @{ n1 n2 -- n3 @}
 9433:  n1 n2 > if
 9434:    n1
 9435:  else
 9436:    n2
 9437:  endif ;
 9438: @end example
 9439: 
 9440: The similarity of locals definitions with stack comments is intended. A
 9441: locals definition often replaces the stack comment of a word. The order
 9442: of the locals corresponds to the order in a stack comment and everything
 9443: after the @code{--} is really a comment.
 9444: 
 9445: This similarity has one disadvantage: It is too easy to confuse locals
 9446: declarations with stack comments, causing bugs and making them hard to
 9447: find. However, this problem can be avoided by appropriate coding
 9448: conventions: Do not use both notations in the same program. If you do,
 9449: they should be distinguished using additional means, e.g. by position.
 9450: 
 9451: @cindex types of locals
 9452: @cindex locals types
 9453: The name of the local may be preceded by a type specifier, e.g.,
 9454: @code{F:} for a floating point value:
 9455: 
 9456: @example
 9457: : CX* @{ F: Ar F: Ai F: Br F: Bi -- Cr Ci @}
 9458: \ complex multiplication
 9459:  Ar Br f* Ai Bi f* f-
 9460:  Ar Bi f* Ai Br f* f+ ;
 9461: @end example
 9462: 
 9463: @cindex flavours of locals
 9464: @cindex locals flavours
 9465: @cindex value-flavoured locals
 9466: @cindex variable-flavoured locals
 9467: Gforth currently supports cells (@code{W:}, @code{W^}), doubles
 9468: (@code{D:}, @code{D^}), floats (@code{F:}, @code{F^}) and characters
 9469: (@code{C:}, @code{C^}) in two flavours: a value-flavoured local (defined
 9470: with @code{W:}, @code{D:} etc.) produces its value and can be changed
 9471: with @code{TO}. A variable-flavoured local (defined with @code{W^} etc.)
 9472: produces its address (which becomes invalid when the variable's scope is
 9473: left). E.g., the standard word @code{emit} can be defined in terms of
 9474: @code{type} like this:
 9475: 
 9476: @example
 9477: : emit @{ C^ char* -- @}
 9478:     char* 1 type ;
 9479: @end example
 9480: 
 9481: @cindex default type of locals
 9482: @cindex locals, default type
 9483: A local without type specifier is a @code{W:} local. Both flavours of
 9484: locals are initialized with values from the data or FP stack.
 9485: 
 9486: Currently there is no way to define locals with user-defined data
 9487: structures, but we are working on it.
 9488: 
 9489: Gforth allows defining locals everywhere in a colon definition. This
 9490: poses the following questions:
 9491: 
 9492: @menu
 9493: * Where are locals visible by name?::  
 9494: * How long do locals live?::    
 9495: * Locals programming style::    
 9496: * Locals implementation::       
 9497: @end menu
 9498: 
 9499: @node Where are locals visible by name?, How long do locals live?, Gforth locals, Gforth locals
 9500: @subsubsection Where are locals visible by name?
 9501: @cindex locals visibility
 9502: @cindex visibility of locals
 9503: @cindex scope of locals
 9504: 
 9505: Basically, the answer is that locals are visible where you would expect
 9506: it in block-structured languages, and sometimes a little longer. If you
 9507: want to restrict the scope of a local, enclose its definition in
 9508: @code{SCOPE}...@code{ENDSCOPE}.
 9509: 
 9510: 
 9511: doc-scope
 9512: doc-endscope
 9513: 
 9514: 
 9515: These words behave like control structure words, so you can use them
 9516: with @code{CS-PICK} and @code{CS-ROLL} to restrict the scope in
 9517: arbitrary ways.
 9518: 
 9519: If you want a more exact answer to the visibility question, here's the
 9520: basic principle: A local is visible in all places that can only be
 9521: reached through the definition of the local@footnote{In compiler
 9522: construction terminology, all places dominated by the definition of the
 9523: local.}. In other words, it is not visible in places that can be reached
 9524: without going through the definition of the local. E.g., locals defined
 9525: in @code{IF}...@code{ENDIF} are visible until the @code{ENDIF}, locals
 9526: defined in @code{BEGIN}...@code{UNTIL} are visible after the
 9527: @code{UNTIL} (until, e.g., a subsequent @code{ENDSCOPE}).
 9528: 
 9529: The reasoning behind this solution is: We want to have the locals
 9530: visible as long as it is meaningful. The user can always make the
 9531: visibility shorter by using explicit scoping. In a place that can
 9532: only be reached through the definition of a local, the meaning of a
 9533: local name is clear. In other places it is not: How is the local
 9534: initialized at the control flow path that does not contain the
 9535: definition? Which local is meant, if the same name is defined twice in
 9536: two independent control flow paths?
 9537: 
 9538: This should be enough detail for nearly all users, so you can skip the
 9539: rest of this section. If you really must know all the gory details and
 9540: options, read on.
 9541: 
 9542: In order to implement this rule, the compiler has to know which places
 9543: are unreachable. It knows this automatically after @code{AHEAD},
 9544: @code{AGAIN}, @code{EXIT} and @code{LEAVE}; in other cases (e.g., after
 9545: most @code{THROW}s), you can use the word @code{UNREACHABLE} to tell the
 9546: compiler that the control flow never reaches that place. If
 9547: @code{UNREACHABLE} is not used where it could, the only consequence is
 9548: that the visibility of some locals is more limited than the rule above
 9549: says. If @code{UNREACHABLE} is used where it should not (i.e., if you
 9550: lie to the compiler), buggy code will be produced.
 9551: 
 9552: 
 9553: doc-unreachable
 9554: 
 9555: 
 9556: Another problem with this rule is that at @code{BEGIN}, the compiler
 9557: does not know which locals will be visible on the incoming
 9558: back-edge. All problems discussed in the following are due to this
 9559: ignorance of the compiler (we discuss the problems using @code{BEGIN}
 9560: loops as examples; the discussion also applies to @code{?DO} and other
 9561: loops). Perhaps the most insidious example is:
 9562: @example
 9563: AHEAD
 9564: BEGIN
 9565:   x
 9566: [ 1 CS-ROLL ] THEN
 9567:   @{ x @}
 9568:   ...
 9569: UNTIL
 9570: @end example
 9571: 
 9572: This should be legal according to the visibility rule. The use of
 9573: @code{x} can only be reached through the definition; but that appears
 9574: textually below the use.
 9575: 
 9576: From this example it is clear that the visibility rules cannot be fully
 9577: implemented without major headaches. Our implementation treats common
 9578: cases as advertised and the exceptions are treated in a safe way: The
 9579: compiler makes a reasonable guess about the locals visible after a
 9580: @code{BEGIN}; if it is too pessimistic, the
 9581: user will get a spurious error about the local not being defined; if the
 9582: compiler is too optimistic, it will notice this later and issue a
 9583: warning. In the case above the compiler would complain about @code{x}
 9584: being undefined at its use. You can see from the obscure examples in
 9585: this section that it takes quite unusual control structures to get the
 9586: compiler into trouble, and even then it will often do fine.
 9587: 
 9588: If the @code{BEGIN} is reachable from above, the most optimistic guess
 9589: is that all locals visible before the @code{BEGIN} will also be
 9590: visible after the @code{BEGIN}. This guess is valid for all loops that
 9591: are entered only through the @code{BEGIN}, in particular, for normal
 9592: @code{BEGIN}...@code{WHILE}...@code{REPEAT} and
 9593: @code{BEGIN}...@code{UNTIL} loops and it is implemented in our
 9594: compiler. When the branch to the @code{BEGIN} is finally generated by
 9595: @code{AGAIN} or @code{UNTIL}, the compiler checks the guess and
 9596: warns the user if it was too optimistic:
 9597: @example
 9598: IF
 9599:   @{ x @}
 9600: BEGIN
 9601:   \ x ? 
 9602: [ 1 cs-roll ] THEN
 9603:   ...
 9604: UNTIL
 9605: @end example
 9606: 
 9607: Here, @code{x} lives only until the @code{BEGIN}, but the compiler
 9608: optimistically assumes that it lives until the @code{THEN}. It notices
 9609: this difference when it compiles the @code{UNTIL} and issues a
 9610: warning. The user can avoid the warning, and make sure that @code{x}
 9611: is not used in the wrong area by using explicit scoping:
 9612: @example
 9613: IF
 9614:   SCOPE
 9615:   @{ x @}
 9616:   ENDSCOPE
 9617: BEGIN
 9618: [ 1 cs-roll ] THEN
 9619:   ...
 9620: UNTIL
 9621: @end example
 9622: 
 9623: Since the guess is optimistic, there will be no spurious error messages
 9624: about undefined locals.
 9625: 
 9626: If the @code{BEGIN} is not reachable from above (e.g., after
 9627: @code{AHEAD} or @code{EXIT}), the compiler cannot even make an
 9628: optimistic guess, as the locals visible after the @code{BEGIN} may be
 9629: defined later. Therefore, the compiler assumes that no locals are
 9630: visible after the @code{BEGIN}. However, the user can use
 9631: @code{ASSUME-LIVE} to make the compiler assume that the same locals are
 9632: visible at the BEGIN as at the point where the top control-flow stack
 9633: item was created.
 9634: 
 9635: 
 9636: doc-assume-live
 9637: 
 9638: 
 9639: @noindent
 9640: E.g.,
 9641: @example
 9642: @{ x @}
 9643: AHEAD
 9644: ASSUME-LIVE
 9645: BEGIN
 9646:   x
 9647: [ 1 CS-ROLL ] THEN
 9648:   ...
 9649: UNTIL
 9650: @end example
 9651: 
 9652: Other cases where the locals are defined before the @code{BEGIN} can be
 9653: handled by inserting an appropriate @code{CS-ROLL} before the
 9654: @code{ASSUME-LIVE} (and changing the control-flow stack manipulation
 9655: behind the @code{ASSUME-LIVE}).
 9656: 
 9657: Cases where locals are defined after the @code{BEGIN} (but should be
 9658: visible immediately after the @code{BEGIN}) can only be handled by
 9659: rearranging the loop. E.g., the ``most insidious'' example above can be
 9660: arranged into:
 9661: @example
 9662: BEGIN
 9663:   @{ x @}
 9664:   ... 0=
 9665: WHILE
 9666:   x
 9667: REPEAT
 9668: @end example
 9669: 
 9670: @node How long do locals live?, Locals programming style, Where are locals visible by name?, Gforth locals
 9671: @subsubsection How long do locals live?
 9672: @cindex locals lifetime
 9673: @cindex lifetime of locals
 9674: 
 9675: The right answer for the lifetime question would be: A local lives at
 9676: least as long as it can be accessed. For a value-flavoured local this
 9677: means: until the end of its visibility. However, a variable-flavoured
 9678: local could be accessed through its address far beyond its visibility
 9679: scope. Ultimately, this would mean that such locals would have to be
 9680: garbage collected. Since this entails un-Forth-like implementation
 9681: complexities, I adopted the same cowardly solution as some other
 9682: languages (e.g., C): The local lives only as long as it is visible;
 9683: afterwards its address is invalid (and programs that access it
 9684: afterwards are erroneous).
 9685: 
 9686: @node Locals programming style, Locals implementation, How long do locals live?, Gforth locals
 9687: @subsubsection Locals programming style
 9688: @cindex locals programming style
 9689: @cindex programming style, locals
 9690: 
 9691: The freedom to define locals anywhere has the potential to change
 9692: programming styles dramatically. In particular, the need to use the
 9693: return stack for intermediate storage vanishes. Moreover, all stack
 9694: manipulations (except @code{PICK}s and @code{ROLL}s with run-time
 9695: determined arguments) can be eliminated: If the stack items are in the
 9696: wrong order, just write a locals definition for all of them; then
 9697: write the items in the order you want.
 9698: 
 9699: This seems a little far-fetched and eliminating stack manipulations is
 9700: unlikely to become a conscious programming objective. Still, the number
 9701: of stack manipulations will be reduced dramatically if local variables
 9702: are used liberally (e.g., compare @code{max} (@pxref{Gforth locals}) with
 9703: a traditional implementation of @code{max}).
 9704: 
 9705: This shows one potential benefit of locals: making Forth programs more
 9706: readable. Of course, this benefit will only be realized if the
 9707: programmers continue to honour the principle of factoring instead of
 9708: using the added latitude to make the words longer.
 9709: 
 9710: @cindex single-assignment style for locals
 9711: Using @code{TO} can and should be avoided.  Without @code{TO},
 9712: every value-flavoured local has only a single assignment and many
 9713: advantages of functional languages apply to Forth. I.e., programs are
 9714: easier to analyse, to optimize and to read: It is clear from the
 9715: definition what the local stands for, it does not turn into something
 9716: different later.
 9717: 
 9718: E.g., a definition using @code{TO} might look like this:
 9719: @example
 9720: : strcmp @{ addr1 u1 addr2 u2 -- n @}
 9721:  u1 u2 min 0
 9722:  ?do
 9723:    addr1 c@@ addr2 c@@ -
 9724:    ?dup-if
 9725:      unloop exit
 9726:    then
 9727:    addr1 char+ TO addr1
 9728:    addr2 char+ TO addr2
 9729:  loop
 9730:  u1 u2 - ;
 9731: @end example
 9732: Here, @code{TO} is used to update @code{addr1} and @code{addr2} at
 9733: every loop iteration. @code{strcmp} is a typical example of the
 9734: readability problems of using @code{TO}. When you start reading
 9735: @code{strcmp}, you think that @code{addr1} refers to the start of the
 9736: string. Only near the end of the loop you realize that it is something
 9737: else.
 9738: 
 9739: This can be avoided by defining two locals at the start of the loop that
 9740: are initialized with the right value for the current iteration.
 9741: @example
 9742: : strcmp @{ addr1 u1 addr2 u2 -- n @}
 9743:  addr1 addr2
 9744:  u1 u2 min 0 
 9745:  ?do @{ s1 s2 @}
 9746:    s1 c@@ s2 c@@ -
 9747:    ?dup-if
 9748:      unloop exit
 9749:    then
 9750:    s1 char+ s2 char+
 9751:  loop
 9752:  2drop
 9753:  u1 u2 - ;
 9754: @end example
 9755: Here it is clear from the start that @code{s1} has a different value
 9756: in every loop iteration.
 9757: 
 9758: @node Locals implementation,  , Locals programming style, Gforth locals
 9759: @subsubsection Locals implementation
 9760: @cindex locals implementation
 9761: @cindex implementation of locals
 9762: 
 9763: @cindex locals stack
 9764: Gforth uses an extra locals stack. The most compelling reason for
 9765: this is that the return stack is not float-aligned; using an extra stack
 9766: also eliminates the problems and restrictions of using the return stack
 9767: as locals stack. Like the other stacks, the locals stack grows toward
 9768: lower addresses. A few primitives allow an efficient implementation:
 9769: 
 9770: 
 9771: doc-@local#
 9772: doc-f@local#
 9773: doc-laddr#
 9774: doc-lp+!#
 9775: doc-lp!
 9776: doc->l
 9777: doc-f>l
 9778: 
 9779: 
 9780: In addition to these primitives, some specializations of these
 9781: primitives for commonly occurring inline arguments are provided for
 9782: efficiency reasons, e.g., @code{@@local0} as specialization of
 9783: @code{@@local#} for the inline argument 0. The following compiling words
 9784: compile the right specialized version, or the general version, as
 9785: appropriate:
 9786: 
 9787: 
 9788: @c doc-compile-@local
 9789: @c doc-compile-f@local
 9790: doc-compile-lp+!
 9791: 
 9792: 
 9793: Combinations of conditional branches and @code{lp+!#} like
 9794: @code{?branch-lp+!#} (the locals pointer is only changed if the branch
 9795: is taken) are provided for efficiency and correctness in loops.
 9796: 
 9797: A special area in the dictionary space is reserved for keeping the
 9798: local variable names. @code{@{} switches the dictionary pointer to this
 9799: area and @code{@}} switches it back and generates the locals
 9800: initializing code. @code{W:} etc.@ are normal defining words. This
 9801: special area is cleared at the start of every colon definition.
 9802: 
 9803: @cindex word list for defining locals
 9804: A special feature of Gforth's dictionary is used to implement the
 9805: definition of locals without type specifiers: every word list (aka
 9806: vocabulary) has its own methods for searching
 9807: etc. (@pxref{Word Lists}). For the present purpose we defined a word list
 9808: with a special search method: When it is searched for a word, it
 9809: actually creates that word using @code{W:}. @code{@{} changes the search
 9810: order to first search the word list containing @code{@}}, @code{W:} etc.,
 9811: and then the word list for defining locals without type specifiers.
 9812: 
 9813: The lifetime rules support a stack discipline within a colon
 9814: definition: The lifetime of a local is either nested with other locals
 9815: lifetimes or it does not overlap them.
 9816: 
 9817: At @code{BEGIN}, @code{IF}, and @code{AHEAD} no code for locals stack
 9818: pointer manipulation is generated. Between control structure words
 9819: locals definitions can push locals onto the locals stack. @code{AGAIN}
 9820: is the simplest of the other three control flow words. It has to
 9821: restore the locals stack depth of the corresponding @code{BEGIN}
 9822: before branching. The code looks like this:
 9823: @format
 9824: @code{lp+!#} current-locals-size @minus{} dest-locals-size
 9825: @code{branch} <begin>
 9826: @end format
 9827: 
 9828: @code{UNTIL} is a little more complicated: If it branches back, it
 9829: must adjust the stack just like @code{AGAIN}. But if it falls through,
 9830: the locals stack must not be changed. The compiler generates the
 9831: following code:
 9832: @format
 9833: @code{?branch-lp+!#} <begin> current-locals-size @minus{} dest-locals-size
 9834: @end format
 9835: The locals stack pointer is only adjusted if the branch is taken.
 9836: 
 9837: @code{THEN} can produce somewhat inefficient code:
 9838: @format
 9839: @code{lp+!#} current-locals-size @minus{} orig-locals-size
 9840: <orig target>:
 9841: @code{lp+!#} orig-locals-size @minus{} new-locals-size
 9842: @end format
 9843: The second @code{lp+!#} adjusts the locals stack pointer from the
 9844: level at the @i{orig} point to the level after the @code{THEN}. The
 9845: first @code{lp+!#} adjusts the locals stack pointer from the current
 9846: level to the level at the orig point, so the complete effect is an
 9847: adjustment from the current level to the right level after the
 9848: @code{THEN}.
 9849: 
 9850: @cindex locals information on the control-flow stack
 9851: @cindex control-flow stack items, locals information
 9852: In a conventional Forth implementation a dest control-flow stack entry
 9853: is just the target address and an orig entry is just the address to be
 9854: patched. Our locals implementation adds a word list to every orig or dest
 9855: item. It is the list of locals visible (or assumed visible) at the point
 9856: described by the entry. Our implementation also adds a tag to identify
 9857: the kind of entry, in particular to differentiate between live and dead
 9858: (reachable and unreachable) orig entries.
 9859: 
 9860: A few unusual operations have to be performed on locals word lists:
 9861: 
 9862: 
 9863: doc-common-list
 9864: doc-sub-list?
 9865: doc-list-size
 9866: 
 9867: 
 9868: Several features of our locals word list implementation make these
 9869: operations easy to implement: The locals word lists are organised as
 9870: linked lists; the tails of these lists are shared, if the lists
 9871: contain some of the same locals; and the address of a name is greater
 9872: than the address of the names behind it in the list.
 9873: 
 9874: Another important implementation detail is the variable
 9875: @code{dead-code}. It is used by @code{BEGIN} and @code{THEN} to
 9876: determine if they can be reached directly or only through the branch
 9877: that they resolve. @code{dead-code} is set by @code{UNREACHABLE},
 9878: @code{AHEAD}, @code{EXIT} etc., and cleared at the start of a colon
 9879: definition, by @code{BEGIN} and usually by @code{THEN}.
 9880: 
 9881: Counted loops are similar to other loops in most respects, but
 9882: @code{LEAVE} requires special attention: It performs basically the same
 9883: service as @code{AHEAD}, but it does not create a control-flow stack
 9884: entry. Therefore the information has to be stored elsewhere;
 9885: traditionally, the information was stored in the target fields of the
 9886: branches created by the @code{LEAVE}s, by organizing these fields into a
 9887: linked list. Unfortunately, this clever trick does not provide enough
 9888: space for storing our extended control flow information. Therefore, we
 9889: introduce another stack, the leave stack. It contains the control-flow
 9890: stack entries for all unresolved @code{LEAVE}s.
 9891: 
 9892: Local names are kept until the end of the colon definition, even if
 9893: they are no longer visible in any control-flow path. In a few cases
 9894: this may lead to increased space needs for the locals name area, but
 9895: usually less than reclaiming this space would cost in code size.
 9896: 
 9897: 
 9898: @node ANS Forth locals,  , Gforth locals, Locals
 9899: @subsection ANS Forth locals
 9900: @cindex locals, ANS Forth style
 9901: 
 9902: The ANS Forth locals wordset does not define a syntax for locals, but
 9903: words that make it possible to define various syntaxes. One of the
 9904: possible syntaxes is a subset of the syntax we used in the Gforth locals
 9905: wordset, i.e.:
 9906: 
 9907: @example
 9908: @{ local1 local2 ... -- comment @}
 9909: @end example
 9910: @noindent
 9911: or
 9912: @example
 9913: @{ local1 local2 ... @}
 9914: @end example
 9915: 
 9916: The order of the locals corresponds to the order in a stack comment. The
 9917: restrictions are:
 9918: 
 9919: @itemize @bullet
 9920: @item
 9921: Locals can only be cell-sized values (no type specifiers are allowed).
 9922: @item
 9923: Locals can be defined only outside control structures.
 9924: @item
 9925: Locals can interfere with explicit usage of the return stack. For the
 9926: exact (and long) rules, see the standard. If you don't use return stack
 9927: accessing words in a definition using locals, you will be all right. The
 9928: purpose of this rule is to make locals implementation on the return
 9929: stack easier.
 9930: @item
 9931: The whole definition must be in one line.
 9932: @end itemize
 9933: 
 9934: Locals defined in ANS Forth behave like @code{VALUE}s
 9935: (@pxref{Values}). I.e., they are initialized from the stack. Using their
 9936: name produces their value. Their value can be changed using @code{TO}.
 9937: 
 9938: Since the syntax above is supported by Gforth directly, you need not do
 9939: anything to use it. If you want to port a program using this syntax to
 9940: another ANS Forth system, use @file{compat/anslocal.fs} to implement the
 9941: syntax on the other system.
 9942: 
 9943: Note that a syntax shown in the standard, section A.13 looks
 9944: similar, but is quite different in having the order of locals
 9945: reversed. Beware!
 9946: 
 9947: The ANS Forth locals wordset itself consists of one word:
 9948: 
 9949: doc-(local)
 9950: 
 9951: The ANS Forth locals extension wordset defines a syntax using
 9952: @code{locals|}, but it is so awful that we strongly recommend not to use
 9953: it. We have implemented this syntax to make porting to Gforth easy, but
 9954: do not document it here. The problem with this syntax is that the locals
 9955: are defined in an order reversed with respect to the standard stack
 9956: comment notation, making programs harder to read, and easier to misread
 9957: and miswrite. The only merit of this syntax is that it is easy to
 9958: implement using the ANS Forth locals wordset.
 9959: 
 9960: 
 9961: @c ----------------------------------------------------------
 9962: @node Structures, Object-oriented Forth, Locals, Words
 9963: @section  Structures
 9964: @cindex structures
 9965: @cindex records
 9966: 
 9967: This section presents the structure package that comes with Gforth. A
 9968: version of the package implemented in ANS Forth is available in
 9969: @file{compat/struct.fs}. This package was inspired by a posting on
 9970: comp.lang.forth in 1989 (unfortunately I don't remember, by whom;
 9971: possibly John Hayes). A version of this section has been published in
 9972: M. Anton Ertl,
 9973: @uref{http://www.complang.tuwien.ac.at/forth/objects/structs.html, Yet
 9974: Another Forth Structures Package}, Forth Dimensions 19(3), pages
 9975: 13--16. Marcel Hendrix provided helpful comments.
 9976: 
 9977: @menu
 9978: * Why explicit structure support?::  
 9979: * Structure Usage::             
 9980: * Structure Naming Convention::  
 9981: * Structure Implementation::    
 9982: * Structure Glossary::          
 9983: * Forth200x Structures::        
 9984: @end menu
 9985: 
 9986: @node Why explicit structure support?, Structure Usage, Structures, Structures
 9987: @subsection Why explicit structure support?
 9988: 
 9989: @cindex address arithmetic for structures
 9990: @cindex structures using address arithmetic
 9991: If we want to use a structure containing several fields, we could simply
 9992: reserve memory for it, and access the fields using address arithmetic
 9993: (@pxref{Address arithmetic}). As an example, consider a structure with
 9994: the following fields
 9995: 
 9996: @table @code
 9997: @item a
 9998: is a float
 9999: @item b
10000: is a cell
10001: @item c
10002: is a float
10003: @end table
10004: 
10005: Given the (float-aligned) base address of the structure we get the
10006: address of the field
10007: 
10008: @table @code
10009: @item a
10010: without doing anything further.
10011: @item b
10012: with @code{float+}
10013: @item c
10014: with @code{float+ cell+ faligned}
10015: @end table
10016: 
10017: It is easy to see that this can become quite tiring. 
10018: 
10019: Moreover, it is not very readable, because seeing a
10020: @code{cell+} tells us neither which kind of structure is
10021: accessed nor what field is accessed; we have to somehow infer the kind
10022: of structure, and then look up in the documentation, which field of
10023: that structure corresponds to that offset.
10024: 
10025: Finally, this kind of address arithmetic also causes maintenance
10026: troubles: If you add or delete a field somewhere in the middle of the
10027: structure, you have to find and change all computations for the fields
10028: afterwards.
10029: 
10030: So, instead of using @code{cell+} and friends directly, how
10031: about storing the offsets in constants:
10032: 
10033: @example
10034: 0 constant a-offset
10035: 0 float+ constant b-offset
10036: 0 float+ cell+ faligned c-offset
10037: @end example
10038: 
10039: Now we can get the address of field @code{x} with @code{x-offset
10040: +}. This is much better in all respects. Of course, you still
10041: have to change all later offset definitions if you add a field. You can
10042: fix this by declaring the offsets in the following way:
10043: 
10044: @example
10045: 0 constant a-offset
10046: a-offset float+ constant b-offset
10047: b-offset cell+ faligned constant c-offset
10048: @end example
10049: 
10050: Since we always use the offsets with @code{+}, we could use a defining
10051: word @code{cfield} that includes the @code{+} in the action of the
10052: defined word:
10053: 
10054: @example
10055: : cfield ( n "name" -- )
10056:     create ,
10057: does> ( name execution: addr1 -- addr2 )
10058:     @@ + ;
10059: 
10060: 0 cfield a
10061: 0 a float+ cfield b
10062: 0 b cell+ faligned cfield c
10063: @end example
10064: 
10065: Instead of @code{x-offset +}, we now simply write @code{x}.
10066: 
10067: The structure field words now can be used quite nicely. However,
10068: their definition is still a bit cumbersome: We have to repeat the
10069: name, the information about size and alignment is distributed before
10070: and after the field definitions etc.  The structure package presented
10071: here addresses these problems.
10072: 
10073: @node Structure Usage, Structure Naming Convention, Why explicit structure support?, Structures
10074: @subsection Structure Usage
10075: @cindex structure usage
10076: 
10077: @cindex @code{field} usage
10078: @cindex @code{struct} usage
10079: @cindex @code{end-struct} usage
10080: You can define a structure for a (data-less) linked list with:
10081: @example
10082: struct
10083:     cell% field list-next
10084: end-struct list%
10085: @end example
10086: 
10087: With the address of the list node on the stack, you can compute the
10088: address of the field that contains the address of the next node with
10089: @code{list-next}. E.g., you can determine the length of a list
10090: with:
10091: 
10092: @example
10093: : list-length ( list -- n )
10094: \ "list" is a pointer to the first element of a linked list
10095: \ "n" is the length of the list
10096:     0 BEGIN ( list1 n1 )
10097:         over
10098:     WHILE ( list1 n1 )
10099:         1+ swap list-next @@ swap
10100:     REPEAT
10101:     nip ;
10102: @end example
10103: 
10104: You can reserve memory for a list node in the dictionary with
10105: @code{list% %allot}, which leaves the address of the list node on the
10106: stack. For the equivalent allocation on the heap you can use @code{list%
10107: %alloc} (or, for an @code{allocate}-like stack effect (i.e., with ior),
10108: use @code{list% %allocate}). You can get the the size of a list
10109: node with @code{list% %size} and its alignment with @code{list%
10110: %alignment}.
10111: 
10112: Note that in ANS Forth the body of a @code{create}d word is
10113: @code{aligned} but not necessarily @code{faligned};
10114: therefore, if you do a:
10115: 
10116: @example
10117: create @emph{name} foo% %allot drop
10118: @end example
10119: 
10120: @noindent
10121: then the memory alloted for @code{foo%} is guaranteed to start at the
10122: body of @code{@emph{name}} only if @code{foo%} contains only character,
10123: cell and double fields.  Therefore, if your structure contains floats,
10124: better use
10125: 
10126: @example
10127: foo% %allot constant @emph{name}
10128: @end example
10129: 
10130: @cindex structures containing structures
10131: You can include a structure @code{foo%} as a field of
10132: another structure, like this:
10133: @example
10134: struct
10135: ...
10136:     foo% field ...
10137: ...
10138: end-struct ...
10139: @end example
10140: 
10141: @cindex structure extension
10142: @cindex extended records
10143: Instead of starting with an empty structure, you can extend an
10144: existing structure. E.g., a plain linked list without data, as defined
10145: above, is hardly useful; You can extend it to a linked list of integers,
10146: like this:@footnote{This feature is also known as @emph{extended
10147: records}. It is the main innovation in the Oberon language; in other
10148: words, adding this feature to Modula-2 led Wirth to create a new
10149: language, write a new compiler etc.  Adding this feature to Forth just
10150: required a few lines of code.}
10151: 
10152: @example
10153: list%
10154:     cell% field intlist-int
10155: end-struct intlist%
10156: @end example
10157: 
10158: @code{intlist%} is a structure with two fields:
10159: @code{list-next} and @code{intlist-int}.
10160: 
10161: @cindex structures containing arrays
10162: You can specify an array type containing @emph{n} elements of
10163: type @code{foo%} like this:
10164: 
10165: @example
10166: foo% @emph{n} *
10167: @end example
10168: 
10169: You can use this array type in any place where you can use a normal
10170: type, e.g., when defining a @code{field}, or with
10171: @code{%allot}.
10172: 
10173: @cindex first field optimization
10174: The first field is at the base address of a structure and the word for
10175: this field (e.g., @code{list-next}) actually does not change the address
10176: on the stack. You may be tempted to leave it away in the interest of
10177: run-time and space efficiency. This is not necessary, because the
10178: structure package optimizes this case: If you compile a first-field
10179: words, no code is generated. So, in the interest of readability and
10180: maintainability you should include the word for the field when accessing
10181: the field.
10182: 
10183: 
10184: @node Structure Naming Convention, Structure Implementation, Structure Usage, Structures
10185: @subsection Structure Naming Convention
10186: @cindex structure naming convention
10187: 
10188: The field names that come to (my) mind are often quite generic, and,
10189: if used, would cause frequent name clashes. E.g., many structures
10190: probably contain a @code{counter} field. The structure names
10191: that come to (my) mind are often also the logical choice for the names
10192: of words that create such a structure.
10193: 
10194: Therefore, I have adopted the following naming conventions: 
10195: 
10196: @itemize @bullet
10197: @cindex field naming convention
10198: @item
10199: The names of fields are of the form
10200: @code{@emph{struct}-@emph{field}}, where
10201: @code{@emph{struct}} is the basic name of the structure, and
10202: @code{@emph{field}} is the basic name of the field. You can
10203: think of field words as converting the (address of the)
10204: structure into the (address of the) field.
10205: 
10206: @cindex structure naming convention
10207: @item
10208: The names of structures are of the form
10209: @code{@emph{struct}%}, where
10210: @code{@emph{struct}} is the basic name of the structure.
10211: @end itemize
10212: 
10213: This naming convention does not work that well for fields of extended
10214: structures; e.g., the integer list structure has a field
10215: @code{intlist-int}, but has @code{list-next}, not
10216: @code{intlist-next}.
10217: 
10218: @node Structure Implementation, Structure Glossary, Structure Naming Convention, Structures
10219: @subsection Structure Implementation
10220: @cindex structure implementation
10221: @cindex implementation of structures
10222: 
10223: The central idea in the implementation is to pass the data about the
10224: structure being built on the stack, not in some global
10225: variable. Everything else falls into place naturally once this design
10226: decision is made.
10227: 
10228: The type description on the stack is of the form @emph{align
10229: size}. Keeping the size on the top-of-stack makes dealing with arrays
10230: very simple.
10231: 
10232: @code{field} is a defining word that uses @code{Create}
10233: and @code{DOES>}. The body of the field contains the offset
10234: of the field, and the normal @code{DOES>} action is simply:
10235: 
10236: @example
10237: @@ +
10238: @end example
10239: 
10240: @noindent
10241: i.e., add the offset to the address, giving the stack effect
10242: @i{addr1 -- addr2} for a field.
10243: 
10244: @cindex first field optimization, implementation
10245: This simple structure is slightly complicated by the optimization
10246: for fields with offset 0, which requires a different
10247: @code{DOES>}-part (because we cannot rely on there being
10248: something on the stack if such a field is invoked during
10249: compilation). Therefore, we put the different @code{DOES>}-parts
10250: in separate words, and decide which one to invoke based on the
10251: offset. For a zero offset, the field is basically a noop; it is
10252: immediate, and therefore no code is generated when it is compiled.
10253: 
10254: @node Structure Glossary, Forth200x Structures, Structure Implementation, Structures
10255: @subsection Structure Glossary
10256: @cindex structure glossary
10257: 
10258: 
10259: doc-%align
10260: doc-%alignment
10261: doc-%alloc
10262: doc-%allocate
10263: doc-%allot
10264: doc-cell%
10265: doc-char%
10266: doc-dfloat%
10267: doc-double%
10268: doc-end-struct
10269: doc-field
10270: doc-float%
10271: doc-naligned
10272: doc-sfloat%
10273: doc-%size
10274: doc-struct
10275: 
10276: 
10277: @node Forth200x Structures,  , Structure Glossary, Structures
10278: @subsection Forth200x Structures
10279: @cindex Structures in Forth200x
10280: 
10281: The Forth 200x standard defines a slightly less convenient form of
10282: structures.  In general (when using @code{field+}, you have to perform
10283: the alignment yourself, but there are a number of convenience words
10284: (e.g., @code{field:} that perform the alignment for you.
10285: 
10286: A typical usage example is:
10287: 
10288: @example
10289: 0
10290:   field:                   s-a
10291:   faligned 2 floats +field s-b
10292: constant s-struct
10293: @end example
10294: 
10295: An alternative way of writing this structure is:
10296: 
10297: @example
10298: begin-structure s-struct
10299:   field:                   s-a
10300:   faligned 2 floats +field s-b
10301: end-structure
10302: @end example
10303: 
10304: doc-begin-structure
10305: doc-end-structure
10306: doc-+field
10307: doc-cfield:
10308: doc-field:
10309: doc-2field:
10310: doc-ffield:
10311: doc-sffield:
10312: doc-dffield:
10313: 
10314: @c -------------------------------------------------------------
10315: @node Object-oriented Forth, Programming Tools, Structures, Words
10316: @section Object-oriented Forth
10317: 
10318: Gforth comes with three packages for object-oriented programming:
10319: @file{objects.fs}, @file{oof.fs}, and @file{mini-oof.fs}; none of them
10320: is preloaded, so you have to @code{include} them before use. The most
10321: important differences between these packages (and others) are discussed
10322: in @ref{Comparison with other object models}. All packages are written
10323: in ANS Forth and can be used with any other ANS Forth.
10324: 
10325: @menu
10326: * Why object-oriented programming?::  
10327: * Object-Oriented Terminology::  
10328: * Objects::                     
10329: * OOF::                         
10330: * Mini-OOF::                    
10331: * Comparison with other object models::  
10332: @end menu
10333: 
10334: @c ----------------------------------------------------------------
10335: @node Why object-oriented programming?, Object-Oriented Terminology, Object-oriented Forth, Object-oriented Forth
10336: @subsection Why object-oriented programming?
10337: @cindex object-oriented programming motivation
10338: @cindex motivation for object-oriented programming
10339: 
10340: Often we have to deal with several data structures (@emph{objects}),
10341: that have to be treated similarly in some respects, but differently in
10342: others. Graphical objects are the textbook example: circles, triangles,
10343: dinosaurs, icons, and others, and we may want to add more during program
10344: development. We want to apply some operations to any graphical object,
10345: e.g., @code{draw} for displaying it on the screen. However, @code{draw}
10346: has to do something different for every kind of object.
10347: @comment TODO add some other operations eg perimeter, area
10348: @comment and tie in to concrete examples later..
10349: 
10350: We could implement @code{draw} as a big @code{CASE}
10351: control structure that executes the appropriate code depending on the
10352: kind of object to be drawn. This would be not be very elegant, and,
10353: moreover, we would have to change @code{draw} every time we add
10354: a new kind of graphical object (say, a spaceship).
10355: 
10356: What we would rather do is: When defining spaceships, we would tell
10357: the system: ``Here's how you @code{draw} a spaceship; you figure
10358: out the rest''.
10359: 
10360: This is the problem that all systems solve that (rightfully) call
10361: themselves object-oriented; the object-oriented packages presented here
10362: solve this problem (and not much else).
10363: @comment TODO ?list properties of oo systems.. oo vs o-based?
10364: 
10365: @c ------------------------------------------------------------------------
10366: @node Object-Oriented Terminology, Objects, Why object-oriented programming?, Object-oriented Forth
10367: @subsection Object-Oriented Terminology
10368: @cindex object-oriented terminology
10369: @cindex terminology for object-oriented programming
10370: 
10371: This section is mainly for reference, so you don't have to understand
10372: all of it right away.  The terminology is mainly Smalltalk-inspired.  In
10373: short:
10374: 
10375: @table @emph
10376: @cindex class
10377: @item class
10378: a data structure definition with some extras.
10379: 
10380: @cindex object
10381: @item object
10382: an instance of the data structure described by the class definition.
10383: 
10384: @cindex instance variables
10385: @item instance variables
10386: fields of the data structure.
10387: 
10388: @cindex selector
10389: @cindex method selector
10390: @cindex virtual function
10391: @item selector
10392: (or @emph{method selector}) a word (e.g.,
10393: @code{draw}) that performs an operation on a variety of data
10394: structures (classes). A selector describes @emph{what} operation to
10395: perform. In C++ terminology: a (pure) virtual function.
10396: 
10397: @cindex method
10398: @item method
10399: the concrete definition that performs the operation
10400: described by the selector for a specific class. A method specifies
10401: @emph{how} the operation is performed for a specific class.
10402: 
10403: @cindex selector invocation
10404: @cindex message send
10405: @cindex invoking a selector
10406: @item selector invocation
10407: a call of a selector. One argument of the call (the TOS (top-of-stack))
10408: is used for determining which method is used. In Smalltalk terminology:
10409: a message (consisting of the selector and the other arguments) is sent
10410: to the object.
10411: 
10412: @cindex receiving object
10413: @item receiving object
10414: the object used for determining the method executed by a selector
10415: invocation. In the @file{objects.fs} model, it is the object that is on
10416: the TOS when the selector is invoked. (@emph{Receiving} comes from
10417: the Smalltalk @emph{message} terminology.)
10418: 
10419: @cindex child class
10420: @cindex parent class
10421: @cindex inheritance
10422: @item child class
10423: a class that has (@emph{inherits}) all properties (instance variables,
10424: selectors, methods) from a @emph{parent class}. In Smalltalk
10425: terminology: The subclass inherits from the superclass. In C++
10426: terminology: The derived class inherits from the base class.
10427: 
10428: @end table
10429: 
10430: @c If you wonder about the message sending terminology, it comes from
10431: @c a time when each object had it's own task and objects communicated via
10432: @c message passing; eventually the Smalltalk developers realized that
10433: @c they can do most things through simple (indirect) calls. They kept the
10434: @c terminology.
10435: 
10436: @c --------------------------------------------------------------
10437: @node Objects, OOF, Object-Oriented Terminology, Object-oriented Forth
10438: @subsection The @file{objects.fs} model
10439: @cindex objects
10440: @cindex object-oriented programming
10441: 
10442: @cindex @file{objects.fs}
10443: @cindex @file{oof.fs}
10444: 
10445: This section describes the @file{objects.fs} package. This material also
10446: has been published in M. Anton Ertl,
10447: @cite{@uref{http://www.complang.tuwien.ac.at/forth/objects/objects.html,
10448: Yet Another Forth Objects Package}}, Forth Dimensions 19(2), pages
10449: 37--43.
10450: @c McKewan's and Zsoter's packages
10451: 
10452: This section assumes that you have read @ref{Structures}.
10453: 
10454: The techniques on which this model is based have been used to implement
10455: the parser generator, Gray, and have also been used in Gforth for
10456: implementing the various flavours of word lists (hashed or not,
10457: case-sensitive or not, special-purpose word lists for locals etc.).
10458: 
10459: 
10460: @menu
10461: * Properties of the Objects model::  
10462: * Basic Objects Usage::         
10463: * The Objects base class::      
10464: * Creating objects::            
10465: * Object-Oriented Programming Style::  
10466: * Class Binding::               
10467: * Method conveniences::         
10468: * Classes and Scoping::         
10469: * Dividing classes::            
10470: * Object Interfaces::           
10471: * Objects Implementation::      
10472: * Objects Glossary::            
10473: @end menu
10474: 
10475: Marcel Hendrix provided helpful comments on this section.
10476: 
10477: @node Properties of the Objects model, Basic Objects Usage, Objects, Objects
10478: @subsubsection Properties of the @file{objects.fs} model
10479: @cindex @file{objects.fs} properties
10480: 
10481: @itemize @bullet
10482: @item
10483: It is straightforward to pass objects on the stack. Passing
10484: selectors on the stack is a little less convenient, but possible.
10485: 
10486: @item
10487: Objects are just data structures in memory, and are referenced by their
10488: address. You can create words for objects with normal defining words
10489: like @code{constant}. Likewise, there is no difference between instance
10490: variables that contain objects and those that contain other data.
10491: 
10492: @item
10493: Late binding is efficient and easy to use.
10494: 
10495: @item
10496: It avoids parsing, and thus avoids problems with state-smartness
10497: and reduced extensibility; for convenience there are a few parsing
10498: words, but they have non-parsing counterparts. There are also a few
10499: defining words that parse. This is hard to avoid, because all standard
10500: defining words parse (except @code{:noname}); however, such
10501: words are not as bad as many other parsing words, because they are not
10502: state-smart.
10503: 
10504: @item
10505: It does not try to incorporate everything. It does a few things and does
10506: them well (IMO). In particular, this model was not designed to support
10507: information hiding (although it has features that may help); you can use
10508: a separate package for achieving this.
10509: 
10510: @item
10511: It is layered; you don't have to learn and use all features to use this
10512: model. Only a few features are necessary (@pxref{Basic Objects Usage},
10513: @pxref{The Objects base class}, @pxref{Creating objects}.), the others
10514: are optional and independent of each other.
10515: 
10516: @item
10517: An implementation in ANS Forth is available.
10518: 
10519: @end itemize
10520: 
10521: 
10522: @node Basic Objects Usage, The Objects base class, Properties of the Objects model, Objects
10523: @subsubsection Basic @file{objects.fs} Usage
10524: @cindex basic objects usage
10525: @cindex objects, basic usage
10526: 
10527: You can define a class for graphical objects like this:
10528: 
10529: @cindex @code{class} usage
10530: @cindex @code{end-class} usage
10531: @cindex @code{selector} usage
10532: @example
10533: object class \ "object" is the parent class
10534:   selector draw ( x y graphical -- )
10535: end-class graphical
10536: @end example
10537: 
10538: This code defines a class @code{graphical} with an
10539: operation @code{draw}.  We can perform the operation
10540: @code{draw} on any @code{graphical} object, e.g.:
10541: 
10542: @example
10543: 100 100 t-rex draw
10544: @end example
10545: 
10546: @noindent
10547: where @code{t-rex} is a word (say, a constant) that produces a
10548: graphical object.
10549: 
10550: @comment TODO add a 2nd operation eg perimeter.. and use for
10551: @comment a concrete example
10552: 
10553: @cindex abstract class
10554: How do we create a graphical object? With the present definitions,
10555: we cannot create a useful graphical object. The class
10556: @code{graphical} describes graphical objects in general, but not
10557: any concrete graphical object type (C++ users would call it an
10558: @emph{abstract class}); e.g., there is no method for the selector
10559: @code{draw} in the class @code{graphical}.
10560: 
10561: For concrete graphical objects, we define child classes of the
10562: class @code{graphical}, e.g.:
10563: 
10564: @cindex @code{overrides} usage
10565: @cindex @code{field} usage in class definition
10566: @example
10567: graphical class \ "graphical" is the parent class
10568:   cell% field circle-radius
10569: 
10570: :noname ( x y circle -- )
10571:   circle-radius @@ draw-circle ;
10572: overrides draw
10573: 
10574: :noname ( n-radius circle -- )
10575:   circle-radius ! ;
10576: overrides construct
10577: 
10578: end-class circle
10579: @end example
10580: 
10581: Here we define a class @code{circle} as a child of @code{graphical},
10582: with field @code{circle-radius} (which behaves just like a field
10583: (@pxref{Structures}); it defines (using @code{overrides}) new methods
10584: for the selectors @code{draw} and @code{construct} (@code{construct} is
10585: defined in @code{object}, the parent class of @code{graphical}).
10586: 
10587: Now we can create a circle on the heap (i.e.,
10588: @code{allocate}d memory) with:
10589: 
10590: @cindex @code{heap-new} usage
10591: @example
10592: 50 circle heap-new constant my-circle
10593: @end example
10594: 
10595: @noindent
10596: @code{heap-new} invokes @code{construct}, thus
10597: initializing the field @code{circle-radius} with 50. We can draw
10598: this new circle at (100,100) with:
10599: 
10600: @example
10601: 100 100 my-circle draw
10602: @end example
10603: 
10604: @cindex selector invocation, restrictions
10605: @cindex class definition, restrictions
10606: Note: You can only invoke a selector if the object on the TOS
10607: (the receiving object) belongs to the class where the selector was
10608: defined or one of its descendents; e.g., you can invoke
10609: @code{draw} only for objects belonging to @code{graphical}
10610: or its descendents (e.g., @code{circle}).  Immediately before
10611: @code{end-class}, the search order has to be the same as
10612: immediately after @code{class}.
10613: 
10614: @node The Objects base class, Creating objects, Basic Objects Usage, Objects
10615: @subsubsection The @file{object.fs} base class
10616: @cindex @code{object} class
10617: 
10618: When you define a class, you have to specify a parent class.  So how do
10619: you start defining classes? There is one class available from the start:
10620: @code{object}. It is ancestor for all classes and so is the
10621: only class that has no parent. It has two selectors: @code{construct}
10622: and @code{print}.
10623: 
10624: @node Creating objects, Object-Oriented Programming Style, The Objects base class, Objects
10625: @subsubsection Creating objects
10626: @cindex creating objects
10627: @cindex object creation
10628: @cindex object allocation options
10629: 
10630: @cindex @code{heap-new} discussion
10631: @cindex @code{dict-new} discussion
10632: @cindex @code{construct} discussion
10633: You can create and initialize an object of a class on the heap with
10634: @code{heap-new} ( ... class -- object ) and in the dictionary
10635: (allocation with @code{allot}) with @code{dict-new} (
10636: ... class -- object ). Both words invoke @code{construct}, which
10637: consumes the stack items indicated by "..." above.
10638: 
10639: @cindex @code{init-object} discussion
10640: @cindex @code{class-inst-size} discussion
10641: If you want to allocate memory for an object yourself, you can get its
10642: alignment and size with @code{class-inst-size 2@@} ( class --
10643: align size ). Once you have memory for an object, you can initialize
10644: it with @code{init-object} ( ... class object -- );
10645: @code{construct} does only a part of the necessary work.
10646: 
10647: @node Object-Oriented Programming Style, Class Binding, Creating objects, Objects
10648: @subsubsection Object-Oriented Programming Style
10649: @cindex object-oriented programming style
10650: @cindex programming style, object-oriented
10651: 
10652: This section is not exhaustive.
10653: 
10654: @cindex stack effects of selectors
10655: @cindex selectors and stack effects
10656: In general, it is a good idea to ensure that all methods for the
10657: same selector have the same stack effect: when you invoke a selector,
10658: you often have no idea which method will be invoked, so, unless all
10659: methods have the same stack effect, you will not know the stack effect
10660: of the selector invocation.
10661: 
10662: One exception to this rule is methods for the selector
10663: @code{construct}. We know which method is invoked, because we
10664: specify the class to be constructed at the same place. Actually, I
10665: defined @code{construct} as a selector only to give the users a
10666: convenient way to specify initialization. The way it is used, a
10667: mechanism different from selector invocation would be more natural
10668: (but probably would take more code and more space to explain).
10669: 
10670: @node Class Binding, Method conveniences, Object-Oriented Programming Style, Objects
10671: @subsubsection Class Binding
10672: @cindex class binding
10673: @cindex early binding
10674: 
10675: @cindex late binding
10676: Normal selector invocations determine the method at run-time depending
10677: on the class of the receiving object. This run-time selection is called
10678: @i{late binding}.
10679: 
10680: Sometimes it's preferable to invoke a different method. For example,
10681: you might want to use the simple method for @code{print}ing
10682: @code{object}s instead of the possibly long-winded @code{print} method
10683: of the receiver class. You can achieve this by replacing the invocation
10684: of @code{print} with:
10685: 
10686: @cindex @code{[bind]} usage
10687: @example
10688: [bind] object print
10689: @end example
10690: 
10691: @noindent
10692: in compiled code or:
10693: 
10694: @cindex @code{bind} usage
10695: @example
10696: bind object print
10697: @end example
10698: 
10699: @cindex class binding, alternative to
10700: @noindent
10701: in interpreted code. Alternatively, you can define the method with a
10702: name (e.g., @code{print-object}), and then invoke it through the
10703: name. Class binding is just a (often more convenient) way to achieve
10704: the same effect; it avoids name clutter and allows you to invoke
10705: methods directly without naming them first.
10706: 
10707: @cindex superclass binding
10708: @cindex parent class binding
10709: A frequent use of class binding is this: When we define a method
10710: for a selector, we often want the method to do what the selector does
10711: in the parent class, and a little more. There is a special word for
10712: this purpose: @code{[parent]}; @code{[parent]
10713: @emph{selector}} is equivalent to @code{[bind] @emph{parent
10714: selector}}, where @code{@emph{parent}} is the parent
10715: class of the current class. E.g., a method definition might look like:
10716: 
10717: @cindex @code{[parent]} usage
10718: @example
10719: :noname
10720:   dup [parent] foo \ do parent's foo on the receiving object
10721:   ... \ do some more
10722: ; overrides foo
10723: @end example
10724: 
10725: @cindex class binding as optimization
10726: In @cite{Object-oriented programming in ANS Forth} (Forth Dimensions,
10727: March 1997), Andrew McKewan presents class binding as an optimization
10728: technique. I recommend not using it for this purpose unless you are in
10729: an emergency. Late binding is pretty fast with this model anyway, so the
10730: benefit of using class binding is small; the cost of using class binding
10731: where it is not appropriate is reduced maintainability.
10732: 
10733: While we are at programming style questions: You should bind
10734: selectors only to ancestor classes of the receiving object. E.g., say,
10735: you know that the receiving object is of class @code{foo} or its
10736: descendents; then you should bind only to @code{foo} and its
10737: ancestors.
10738: 
10739: @node Method conveniences, Classes and Scoping, Class Binding, Objects
10740: @subsubsection Method conveniences
10741: @cindex method conveniences
10742: 
10743: In a method you usually access the receiving object pretty often.  If
10744: you define the method as a plain colon definition (e.g., with
10745: @code{:noname}), you may have to do a lot of stack
10746: gymnastics. To avoid this, you can define the method with @code{m:
10747: ... ;m}. E.g., you could define the method for
10748: @code{draw}ing a @code{circle} with
10749: 
10750: @cindex @code{this} usage
10751: @cindex @code{m:} usage
10752: @cindex @code{;m} usage
10753: @example
10754: m: ( x y circle -- )
10755:   ( x y ) this circle-radius @@ draw-circle ;m
10756: @end example
10757: 
10758: @cindex @code{exit} in @code{m: ... ;m}
10759: @cindex @code{exitm} discussion
10760: @cindex @code{catch} in @code{m: ... ;m}
10761: When this method is executed, the receiver object is removed from the
10762: stack; you can access it with @code{this} (admittedly, in this
10763: example the use of @code{m: ... ;m} offers no advantage). Note
10764: that I specify the stack effect for the whole method (i.e. including
10765: the receiver object), not just for the code between @code{m:}
10766: and @code{;m}. You cannot use @code{exit} in
10767: @code{m:...;m}; instead, use
10768: @code{exitm}.@footnote{Moreover, for any word that calls
10769: @code{catch} and was defined before loading
10770: @code{objects.fs}, you have to redefine it like I redefined
10771: @code{catch}: @code{: catch this >r catch r> to-this ;}}
10772: 
10773: @cindex @code{inst-var} usage
10774: You will frequently use sequences of the form @code{this
10775: @emph{field}} (in the example above: @code{this
10776: circle-radius}). If you use the field only in this way, you can
10777: define it with @code{inst-var} and eliminate the
10778: @code{this} before the field name. E.g., the @code{circle}
10779: class above could also be defined with:
10780: 
10781: @example
10782: graphical class
10783:   cell% inst-var radius
10784: 
10785: m: ( x y circle -- )
10786:   radius @@ draw-circle ;m
10787: overrides draw
10788: 
10789: m: ( n-radius circle -- )
10790:   radius ! ;m
10791: overrides construct
10792: 
10793: end-class circle
10794: @end example
10795: 
10796: @code{radius} can only be used in @code{circle} and its
10797: descendent classes and inside @code{m:...;m}.
10798: 
10799: @cindex @code{inst-value} usage
10800: You can also define fields with @code{inst-value}, which is
10801: to @code{inst-var} what @code{value} is to
10802: @code{variable}.  You can change the value of such a field with
10803: @code{[to-inst]}.  E.g., we could also define the class
10804: @code{circle} like this:
10805: 
10806: @example
10807: graphical class
10808:   inst-value radius
10809: 
10810: m: ( x y circle -- )
10811:   radius draw-circle ;m
10812: overrides draw
10813: 
10814: m: ( n-radius circle -- )
10815:   [to-inst] radius ;m
10816: overrides construct
10817: 
10818: end-class circle
10819: @end example
10820: 
10821: @c !! :m is easy to confuse with m:.  Another name would be better.
10822: 
10823: @c Finally, you can define named methods with @code{:m}.  One use of this
10824: @c feature is the definition of words that occur only in one class and are
10825: @c not intended to be overridden, but which still need method context
10826: @c (e.g., for accessing @code{inst-var}s).  Another use is for methods that
10827: @c would be bound frequently, if defined anonymously.
10828: 
10829: 
10830: @node Classes and Scoping, Dividing classes, Method conveniences, Objects
10831: @subsubsection Classes and Scoping
10832: @cindex classes and scoping
10833: @cindex scoping and classes
10834: 
10835: Inheritance is frequent, unlike structure extension. This exacerbates
10836: the problem with the field name convention (@pxref{Structure Naming
10837: Convention}): One always has to remember in which class the field was
10838: originally defined; changing a part of the class structure would require
10839: changes for renaming in otherwise unaffected code.
10840: 
10841: @cindex @code{inst-var} visibility
10842: @cindex @code{inst-value} visibility
10843: To solve this problem, I added a scoping mechanism (which was not in my
10844: original charter): A field defined with @code{inst-var} (or
10845: @code{inst-value}) is visible only in the class where it is defined and in
10846: the descendent classes of this class.  Using such fields only makes
10847: sense in @code{m:}-defined methods in these classes anyway.
10848: 
10849: This scoping mechanism allows us to use the unadorned field name,
10850: because name clashes with unrelated words become much less likely.
10851: 
10852: @cindex @code{protected} discussion
10853: @cindex @code{private} discussion
10854: Once we have this mechanism, we can also use it for controlling the
10855: visibility of other words: All words defined after
10856: @code{protected} are visible only in the current class and its
10857: descendents. @code{public} restores the compilation
10858: (i.e. @code{current}) word list that was in effect before. If you
10859: have several @code{protected}s without an intervening
10860: @code{public} or @code{set-current}, @code{public}
10861: will restore the compilation word list in effect before the first of
10862: these @code{protected}s.
10863: 
10864: @node Dividing classes, Object Interfaces, Classes and Scoping, Objects
10865: @subsubsection Dividing classes
10866: @cindex Dividing classes
10867: @cindex @code{methods}...@code{end-methods}
10868: 
10869: You may want to do the definition of methods separate from the
10870: definition of the class, its selectors, fields, and instance variables,
10871: i.e., separate the implementation from the definition.  You can do this
10872: in the following way:
10873: 
10874: @example
10875: graphical class
10876:   inst-value radius
10877: end-class circle
10878: 
10879: ... \ do some other stuff
10880: 
10881: circle methods \ now we are ready
10882: 
10883: m: ( x y circle -- )
10884:   radius draw-circle ;m
10885: overrides draw
10886: 
10887: m: ( n-radius circle -- )
10888:   [to-inst] radius ;m
10889: overrides construct
10890: 
10891: end-methods
10892: @end example
10893: 
10894: You can use several @code{methods}...@code{end-methods} sections.  The
10895: only things you can do to the class in these sections are: defining
10896: methods, and overriding the class's selectors.  You must not define new
10897: selectors or fields.
10898: 
10899: Note that you often have to override a selector before using it.  In
10900: particular, you usually have to override @code{construct} with a new
10901: method before you can invoke @code{heap-new} and friends.  E.g., you
10902: must not create a circle before the @code{overrides construct} sequence
10903: in the example above.
10904: 
10905: @node Object Interfaces, Objects Implementation, Dividing classes, Objects
10906: @subsubsection Object Interfaces
10907: @cindex object interfaces
10908: @cindex interfaces for objects
10909: 
10910: In this model you can only call selectors defined in the class of the
10911: receiving objects or in one of its ancestors. If you call a selector
10912: with a receiving object that is not in one of these classes, the
10913: result is undefined; if you are lucky, the program crashes
10914: immediately.
10915: 
10916: @cindex selectors common to hardly-related classes
10917: Now consider the case when you want to have a selector (or several)
10918: available in two classes: You would have to add the selector to a
10919: common ancestor class, in the worst case to @code{object}. You
10920: may not want to do this, e.g., because someone else is responsible for
10921: this ancestor class.
10922: 
10923: The solution for this problem is interfaces. An interface is a
10924: collection of selectors. If a class implements an interface, the
10925: selectors become available to the class and its descendents. A class
10926: can implement an unlimited number of interfaces. For the problem
10927: discussed above, we would define an interface for the selector(s), and
10928: both classes would implement the interface.
10929: 
10930: As an example, consider an interface @code{storage} for
10931: writing objects to disk and getting them back, and a class
10932: @code{foo} that implements it. The code would look like this:
10933: 
10934: @cindex @code{interface} usage
10935: @cindex @code{end-interface} usage
10936: @cindex @code{implementation} usage
10937: @example
10938: interface
10939:   selector write ( file object -- )
10940:   selector read1 ( file object -- )
10941: end-interface storage
10942: 
10943: bar class
10944:   storage implementation
10945: 
10946: ... overrides write
10947: ... overrides read1
10948: ...
10949: end-class foo
10950: @end example
10951: 
10952: @noindent
10953: (I would add a word @code{read} @i{( file -- object )} that uses
10954: @code{read1} internally, but that's beyond the point illustrated
10955: here.)
10956: 
10957: Note that you cannot use @code{protected} in an interface; and
10958: of course you cannot define fields.
10959: 
10960: In the Neon model, all selectors are available for all classes;
10961: therefore it does not need interfaces. The price you pay in this model
10962: is slower late binding, and therefore, added complexity to avoid late
10963: binding.
10964: 
10965: @node Objects Implementation, Objects Glossary, Object Interfaces, Objects
10966: @subsubsection @file{objects.fs} Implementation
10967: @cindex @file{objects.fs} implementation
10968: 
10969: @cindex @code{object-map} discussion
10970: An object is a piece of memory, like one of the data structures
10971: described with @code{struct...end-struct}. It has a field
10972: @code{object-map} that points to the method map for the object's
10973: class.
10974: 
10975: @cindex method map
10976: @cindex virtual function table
10977: The @emph{method map}@footnote{This is Self terminology; in C++
10978: terminology: virtual function table.} is an array that contains the
10979: execution tokens (@i{xt}s) of the methods for the object's class. Each
10980: selector contains an offset into a method map.
10981: 
10982: @cindex @code{selector} implementation, class
10983: @code{selector} is a defining word that uses
10984: @code{CREATE} and @code{DOES>}. The body of the
10985: selector contains the offset; the @code{DOES>} action for a
10986: class selector is, basically:
10987: 
10988: @example
10989: ( object addr ) @@ over object-map @@ + @@ execute
10990: @end example
10991: 
10992: Since @code{object-map} is the first field of the object, it
10993: does not generate any code. As you can see, calling a selector has a
10994: small, constant cost.
10995: 
10996: @cindex @code{current-interface} discussion
10997: @cindex class implementation and representation
10998: A class is basically a @code{struct} combined with a method
10999: map. During the class definition the alignment and size of the class
11000: are passed on the stack, just as with @code{struct}s, so
11001: @code{field} can also be used for defining class
11002: fields. However, passing more items on the stack would be
11003: inconvenient, so @code{class} builds a data structure in memory,
11004: which is accessed through the variable
11005: @code{current-interface}. After its definition is complete, the
11006: class is represented on the stack by a pointer (e.g., as parameter for
11007: a child class definition).
11008: 
11009: A new class starts off with the alignment and size of its parent,
11010: and a copy of the parent's method map. Defining new fields extends the
11011: size and alignment; likewise, defining new selectors extends the
11012: method map. @code{overrides} just stores a new @i{xt} in the method
11013: map at the offset given by the selector.
11014: 
11015: @cindex class binding, implementation
11016: Class binding just gets the @i{xt} at the offset given by the selector
11017: from the class's method map and @code{compile,}s (in the case of
11018: @code{[bind]}) it.
11019: 
11020: @cindex @code{this} implementation
11021: @cindex @code{catch} and @code{this}
11022: @cindex @code{this} and @code{catch}
11023: I implemented @code{this} as a @code{value}. At the
11024: start of an @code{m:...;m} method the old @code{this} is
11025: stored to the return stack and restored at the end; and the object on
11026: the TOS is stored @code{TO this}. This technique has one
11027: disadvantage: If the user does not leave the method via
11028: @code{;m}, but via @code{throw} or @code{exit},
11029: @code{this} is not restored (and @code{exit} may
11030: crash). To deal with the @code{throw} problem, I have redefined
11031: @code{catch} to save and restore @code{this}; the same
11032: should be done with any word that can catch an exception. As for
11033: @code{exit}, I simply forbid it (as a replacement, there is
11034: @code{exitm}).
11035: 
11036: @cindex @code{inst-var} implementation
11037: @code{inst-var} is just the same as @code{field}, with
11038: a different @code{DOES>} action:
11039: @example
11040: @@ this +
11041: @end example
11042: Similar for @code{inst-value}.
11043: 
11044: @cindex class scoping implementation
11045: Each class also has a word list that contains the words defined with
11046: @code{inst-var} and @code{inst-value}, and its protected
11047: words. It also has a pointer to its parent. @code{class} pushes
11048: the word lists of the class and all its ancestors onto the search order stack,
11049: and @code{end-class} drops them.
11050: 
11051: @cindex interface implementation
11052: An interface is like a class without fields, parent and protected
11053: words; i.e., it just has a method map. If a class implements an
11054: interface, its method map contains a pointer to the method map of the
11055: interface. The positive offsets in the map are reserved for class
11056: methods, therefore interface map pointers have negative
11057: offsets. Interfaces have offsets that are unique throughout the
11058: system, unlike class selectors, whose offsets are only unique for the
11059: classes where the selector is available (invokable).
11060: 
11061: This structure means that interface selectors have to perform one
11062: indirection more than class selectors to find their method. Their body
11063: contains the interface map pointer offset in the class method map, and
11064: the method offset in the interface method map. The
11065: @code{does>} action for an interface selector is, basically:
11066: 
11067: @example
11068: ( object selector-body )
11069: 2dup selector-interface @@ ( object selector-body object interface-offset )
11070: swap object-map @@ + @@ ( object selector-body map )
11071: swap selector-offset @@ + @@ execute
11072: @end example
11073: 
11074: where @code{object-map} and @code{selector-offset} are
11075: first fields and generate no code.
11076: 
11077: As a concrete example, consider the following code:
11078: 
11079: @example
11080: interface
11081:   selector if1sel1
11082:   selector if1sel2
11083: end-interface if1
11084: 
11085: object class
11086:   if1 implementation
11087:   selector cl1sel1
11088:   cell% inst-var cl1iv1
11089: 
11090: ' m1 overrides construct
11091: ' m2 overrides if1sel1
11092: ' m3 overrides if1sel2
11093: ' m4 overrides cl1sel2
11094: end-class cl1
11095: 
11096: create obj1 object dict-new drop
11097: create obj2 cl1    dict-new drop
11098: @end example
11099: 
11100: The data structure created by this code (including the data structure
11101: for @code{object}) is shown in the
11102: @uref{objects-implementation.eps,figure}, assuming a cell size of 4.
11103: @comment TODO add this diagram..
11104: 
11105: @node Objects Glossary,  , Objects Implementation, Objects
11106: @subsubsection @file{objects.fs} Glossary
11107: @cindex @file{objects.fs} Glossary
11108: 
11109: 
11110: doc---objects-bind
11111: doc---objects-<bind>
11112: doc---objects-bind'
11113: doc---objects-[bind]
11114: doc---objects-class
11115: doc---objects-class->map
11116: doc---objects-class-inst-size
11117: doc---objects-class-override!
11118: doc---objects-class-previous
11119: doc---objects-class>order
11120: doc---objects-construct
11121: doc---objects-current'
11122: doc---objects-[current]
11123: doc---objects-current-interface
11124: doc---objects-dict-new
11125: doc---objects-end-class
11126: doc---objects-end-class-noname
11127: doc---objects-end-interface
11128: doc---objects-end-interface-noname
11129: doc---objects-end-methods
11130: doc---objects-exitm
11131: doc---objects-heap-new
11132: doc---objects-implementation
11133: doc---objects-init-object
11134: doc---objects-inst-value
11135: doc---objects-inst-var
11136: doc---objects-interface
11137: doc---objects-m:
11138: doc---objects-:m
11139: doc---objects-;m
11140: doc---objects-method
11141: doc---objects-methods
11142: doc---objects-object
11143: doc---objects-overrides
11144: doc---objects-[parent]
11145: doc---objects-print
11146: doc---objects-protected
11147: doc---objects-public
11148: doc---objects-selector
11149: doc---objects-this
11150: doc---objects-<to-inst>
11151: doc---objects-[to-inst]
11152: doc---objects-to-this
11153: doc---objects-xt-new
11154: 
11155: 
11156: @c -------------------------------------------------------------
11157: @node OOF, Mini-OOF, Objects, Object-oriented Forth
11158: @subsection The @file{oof.fs} model
11159: @cindex oof
11160: @cindex object-oriented programming
11161: 
11162: @cindex @file{objects.fs}
11163: @cindex @file{oof.fs}
11164: 
11165: This section describes the @file{oof.fs} package.
11166: 
11167: The package described in this section has been used in bigFORTH since 1991, and
11168: used for two large applications: a chromatographic system used to
11169: create new medicaments, and a graphic user interface library (MINOS).
11170: 
11171: You can find a description (in German) of @file{oof.fs} in @cite{Object
11172: oriented bigFORTH} by Bernd Paysan, published in @cite{Vierte Dimension}
11173: 10(2), 1994.
11174: 
11175: @menu
11176: * Properties of the OOF model::  
11177: * Basic OOF Usage::             
11178: * The OOF base class::          
11179: * Class Declaration::           
11180: * Class Implementation::        
11181: @end menu
11182: 
11183: @node Properties of the OOF model, Basic OOF Usage, OOF, OOF
11184: @subsubsection Properties of the @file{oof.fs} model
11185: @cindex @file{oof.fs} properties
11186: 
11187: @itemize @bullet
11188: @item
11189: This model combines object oriented programming with information
11190: hiding. It helps you writing large application, where scoping is
11191: necessary, because it provides class-oriented scoping.
11192: 
11193: @item
11194: Named objects, object pointers, and object arrays can be created,
11195: selector invocation uses the ``object selector'' syntax. Selector invocation
11196: to objects and/or selectors on the stack is a bit less convenient, but
11197: possible.
11198: 
11199: @item
11200: Selector invocation and instance variable usage of the active object is
11201: straightforward, since both make use of the active object.
11202: 
11203: @item
11204: Late binding is efficient and easy to use.
11205: 
11206: @item
11207: State-smart objects parse selectors. However, extensibility is provided
11208: using a (parsing) selector @code{postpone} and a selector @code{'}.
11209: 
11210: @item
11211: An implementation in ANS Forth is available.
11212: 
11213: @end itemize
11214: 
11215: 
11216: @node Basic OOF Usage, The OOF base class, Properties of the OOF model, OOF
11217: @subsubsection Basic @file{oof.fs} Usage
11218: @cindex @file{oof.fs} usage
11219: 
11220: This section uses the same example as for @code{objects} (@pxref{Basic Objects Usage}).
11221: 
11222: You can define a class for graphical objects like this:
11223: 
11224: @cindex @code{class} usage
11225: @cindex @code{class;} usage
11226: @cindex @code{method} usage
11227: @example
11228: object class graphical \ "object" is the parent class
11229:   method draw ( x y -- )
11230: class;
11231: @end example
11232: 
11233: This code defines a class @code{graphical} with an
11234: operation @code{draw}.  We can perform the operation
11235: @code{draw} on any @code{graphical} object, e.g.:
11236: 
11237: @example
11238: 100 100 t-rex draw
11239: @end example
11240: 
11241: @noindent
11242: where @code{t-rex} is an object or object pointer, created with e.g.
11243: @code{graphical : t-rex}.
11244: 
11245: @cindex abstract class
11246: How do we create a graphical object? With the present definitions,
11247: we cannot create a useful graphical object. The class
11248: @code{graphical} describes graphical objects in general, but not
11249: any concrete graphical object type (C++ users would call it an
11250: @emph{abstract class}); e.g., there is no method for the selector
11251: @code{draw} in the class @code{graphical}.
11252: 
11253: For concrete graphical objects, we define child classes of the
11254: class @code{graphical}, e.g.:
11255: 
11256: @example
11257: graphical class circle \ "graphical" is the parent class
11258:   cell var circle-radius
11259: how:
11260:   : draw ( x y -- )
11261:     circle-radius @@ draw-circle ;
11262: 
11263:   : init ( n-radius -- )
11264:     circle-radius ! ;
11265: class;
11266: @end example
11267: 
11268: Here we define a class @code{circle} as a child of @code{graphical},
11269: with a field @code{circle-radius}; it defines new methods for the
11270: selectors @code{draw} and @code{init} (@code{init} is defined in
11271: @code{object}, the parent class of @code{graphical}).
11272: 
11273: Now we can create a circle in the dictionary with:
11274: 
11275: @example
11276: 50 circle : my-circle
11277: @end example
11278: 
11279: @noindent
11280: @code{:} invokes @code{init}, thus initializing the field
11281: @code{circle-radius} with 50. We can draw this new circle at (100,100)
11282: with:
11283: 
11284: @example
11285: 100 100 my-circle draw
11286: @end example
11287: 
11288: @cindex selector invocation, restrictions
11289: @cindex class definition, restrictions
11290: Note: You can only invoke a selector if the receiving object belongs to
11291: the class where the selector was defined or one of its descendents;
11292: e.g., you can invoke @code{draw} only for objects belonging to
11293: @code{graphical} or its descendents (e.g., @code{circle}). The scoping
11294: mechanism will check if you try to invoke a selector that is not
11295: defined in this class hierarchy, so you'll get an error at compilation
11296: time.
11297: 
11298: 
11299: @node The OOF base class, Class Declaration, Basic OOF Usage, OOF
11300: @subsubsection The @file{oof.fs} base class
11301: @cindex @file{oof.fs} base class
11302: 
11303: When you define a class, you have to specify a parent class.  So how do
11304: you start defining classes? There is one class available from the start:
11305: @code{object}. You have to use it as ancestor for all classes. It is the
11306: only class that has no parent. Classes are also objects, except that
11307: they don't have instance variables; class manipulation such as
11308: inheritance or changing definitions of a class is handled through
11309: selectors of the class @code{object}.
11310: 
11311: @code{object} provides a number of selectors:
11312: 
11313: @itemize @bullet
11314: @item
11315: @code{class} for subclassing, @code{definitions} to add definitions
11316: later on, and @code{class?} to get type informations (is the class a
11317: subclass of the class passed on the stack?).
11318: 
11319: doc---object-class
11320: doc---object-definitions
11321: doc---object-class?
11322: 
11323: 
11324: @item
11325: @code{init} and @code{dispose} as constructor and destructor of the
11326: object. @code{init} is invocated after the object's memory is allocated,
11327: while @code{dispose} also handles deallocation. Thus if you redefine
11328: @code{dispose}, you have to call the parent's dispose with @code{super
11329: dispose}, too.
11330: 
11331: doc---object-init
11332: doc---object-dispose
11333: 
11334: 
11335: @item
11336: @code{new}, @code{new[]}, @code{:}, @code{ptr}, @code{asptr}, and
11337: @code{[]} to create named and unnamed objects and object arrays or
11338: object pointers.
11339: 
11340: doc---object-new
11341: doc---object-new[]
11342: doc---object-:
11343: doc---object-ptr
11344: doc---object-asptr
11345: doc---object-[]
11346: 
11347: 
11348: @item
11349: @code{::} and @code{super} for explicit scoping. You should use explicit
11350: scoping only for super classes or classes with the same set of instance
11351: variables. Explicitly-scoped selectors use early binding.
11352: 
11353: doc---object-::
11354: doc---object-super
11355: 
11356: 
11357: @item
11358: @code{self} to get the address of the object
11359: 
11360: doc---object-self
11361: 
11362: 
11363: @item
11364: @code{bind}, @code{bound}, @code{link}, and @code{is} to assign object
11365: pointers and instance defers.
11366: 
11367: doc---object-bind
11368: doc---object-bound
11369: doc---object-link
11370: doc---object-is
11371: 
11372: 
11373: @item
11374: @code{'} to obtain selector tokens, @code{send} to invocate selectors
11375: form the stack, and @code{postpone} to generate selector invocation code.
11376: 
11377: doc---object-'
11378: doc---object-postpone
11379: 
11380: 
11381: @item
11382: @code{with} and @code{endwith} to select the active object from the
11383: stack, and enable its scope. Using @code{with} and @code{endwith}
11384: also allows you to create code using selector @code{postpone} without being
11385: trapped by the state-smart objects.
11386: 
11387: doc---object-with
11388: doc---object-endwith
11389: 
11390: 
11391: @end itemize
11392: 
11393: @node Class Declaration, Class Implementation, The OOF base class, OOF
11394: @subsubsection Class Declaration
11395: @cindex class declaration
11396: 
11397: @itemize @bullet
11398: @item
11399: Instance variables
11400: 
11401: doc---oof-var
11402: 
11403: 
11404: @item
11405: Object pointers
11406: 
11407: doc---oof-ptr
11408: doc---oof-asptr
11409: 
11410: 
11411: @item
11412: Instance defers
11413: 
11414: doc---oof-defer
11415: 
11416: 
11417: @item
11418: Method selectors
11419: 
11420: doc---oof-early
11421: doc---oof-method
11422: 
11423: 
11424: @item
11425: Class-wide variables
11426: 
11427: doc---oof-static
11428: 
11429: 
11430: @item
11431: End declaration
11432: 
11433: doc---oof-how:
11434: doc---oof-class;
11435: 
11436: 
11437: @end itemize
11438: 
11439: @c -------------------------------------------------------------
11440: @node Class Implementation,  , Class Declaration, OOF
11441: @subsubsection Class Implementation
11442: @cindex class implementation
11443: 
11444: @c -------------------------------------------------------------
11445: @node Mini-OOF, Comparison with other object models, OOF, Object-oriented Forth
11446: @subsection The @file{mini-oof.fs} model
11447: @cindex mini-oof
11448: 
11449: Gforth's third object oriented Forth package is a 12-liner. It uses a
11450: mixture of the @file{objects.fs} and the @file{oof.fs} syntax,
11451: and reduces to the bare minimum of features. This is based on a posting
11452: of Bernd Paysan in comp.lang.forth.
11453: 
11454: @menu
11455: * Basic Mini-OOF Usage::        
11456: * Mini-OOF Example::            
11457: * Mini-OOF Implementation::     
11458: @end menu
11459: 
11460: @c -------------------------------------------------------------
11461: @node Basic Mini-OOF Usage, Mini-OOF Example, Mini-OOF, Mini-OOF
11462: @subsubsection Basic @file{mini-oof.fs} Usage
11463: @cindex mini-oof usage
11464: 
11465: There is a base class (@code{class}, which allocates one cell for the
11466: object pointer) plus seven other words: to define a method, a variable,
11467: a class; to end a class, to resolve binding, to allocate an object and
11468: to compile a class method.
11469: @comment TODO better description of the last one
11470: 
11471: 
11472: doc-object
11473: doc-method
11474: doc-var
11475: doc-class
11476: doc-end-class
11477: doc-defines
11478: doc-new
11479: doc-::
11480: 
11481: 
11482: 
11483: @c -------------------------------------------------------------
11484: @node Mini-OOF Example, Mini-OOF Implementation, Basic Mini-OOF Usage, Mini-OOF
11485: @subsubsection Mini-OOF Example
11486: @cindex mini-oof example
11487: 
11488: A short example shows how to use this package. This example, in slightly
11489: extended form, is supplied as @file{moof-exm.fs}
11490: @comment TODO could flesh this out with some comments from the Forthwrite article
11491: 
11492: @example
11493: object class
11494:   method init
11495:   method draw
11496: end-class graphical
11497: @end example
11498: 
11499: This code defines a class @code{graphical} with an
11500: operation @code{draw}.  We can perform the operation
11501: @code{draw} on any @code{graphical} object, e.g.:
11502: 
11503: @example
11504: 100 100 t-rex draw
11505: @end example
11506: 
11507: where @code{t-rex} is an object or object pointer, created with e.g.
11508: @code{graphical new Constant t-rex}.
11509: 
11510: For concrete graphical objects, we define child classes of the
11511: class @code{graphical}, e.g.:
11512: 
11513: @example
11514: graphical class
11515:   cell var circle-radius
11516: end-class circle \ "graphical" is the parent class
11517: 
11518: :noname ( x y -- )
11519:   circle-radius @@ draw-circle ; circle defines draw
11520: :noname ( r -- )
11521:   circle-radius ! ; circle defines init
11522: @end example
11523: 
11524: There is no implicit init method, so we have to define one. The creation
11525: code of the object now has to call init explicitely.
11526: 
11527: @example
11528: circle new Constant my-circle
11529: 50 my-circle init
11530: @end example
11531: 
11532: It is also possible to add a function to create named objects with
11533: automatic call of @code{init}, given that all objects have @code{init}
11534: on the same place:
11535: 
11536: @example
11537: : new: ( .. o "name" -- )
11538:     new dup Constant init ;
11539: 80 circle new: large-circle
11540: @end example
11541: 
11542: We can draw this new circle at (100,100) with:
11543: 
11544: @example
11545: 100 100 my-circle draw
11546: @end example
11547: 
11548: @node Mini-OOF Implementation,  , Mini-OOF Example, Mini-OOF
11549: @subsubsection @file{mini-oof.fs} Implementation
11550: 
11551: Object-oriented systems with late binding typically use a
11552: ``vtable''-approach: the first variable in each object is a pointer to a
11553: table, which contains the methods as function pointers. The vtable
11554: may also contain other information.
11555: 
11556: So first, let's declare selectors:
11557: 
11558: @example
11559: : method ( m v "name" -- m' v ) Create  over , swap cell+ swap
11560:   DOES> ( ... o -- ... ) @@ over @@ + @@ execute ;
11561: @end example
11562: 
11563: During selector declaration, the number of selectors and instance
11564: variables is on the stack (in address units). @code{method} creates one
11565: selector and increments the selector number. To execute a selector, it
11566: takes the object, fetches the vtable pointer, adds the offset, and
11567: executes the method @i{xt} stored there. Each selector takes the object
11568: it is invoked with as top of stack parameter; it passes the parameters
11569: (including the object) unchanged to the appropriate method which should
11570: consume that object.
11571: 
11572: Now, we also have to declare instance variables
11573: 
11574: @example
11575: : var ( m v size "name" -- m v' ) Create  over , +
11576:   DOES> ( o -- addr ) @@ + ;
11577: @end example
11578: 
11579: As before, a word is created with the current offset. Instance
11580: variables can have different sizes (cells, floats, doubles, chars), so
11581: all we do is take the size and add it to the offset. If your machine
11582: has alignment restrictions, put the proper @code{aligned} or
11583: @code{faligned} before the variable, to adjust the variable
11584: offset. That's why it is on the top of stack.
11585: 
11586: We need a starting point (the base object) and some syntactic sugar:
11587: 
11588: @example
11589: Create object  1 cells , 2 cells ,
11590: : class ( class -- class selectors vars ) dup 2@@ ;
11591: @end example
11592: 
11593: For inheritance, the vtable of the parent object has to be
11594: copied when a new, derived class is declared. This gives all the
11595: methods of the parent class, which can be overridden, though.
11596: 
11597: @example
11598: : end-class  ( class selectors vars "name" -- )
11599:   Create  here >r , dup , 2 cells ?DO ['] noop , 1 cells +LOOP
11600:   cell+ dup cell+ r> rot @@ 2 cells /string move ;
11601: @end example
11602: 
11603: The first line creates the vtable, initialized with
11604: @code{noop}s. The second line is the inheritance mechanism, it
11605: copies the xts from the parent vtable.
11606: 
11607: We still have no way to define new methods, let's do that now:
11608: 
11609: @example
11610: : defines ( xt class "name" -- ) ' >body @@ + ! ;
11611: @end example
11612: 
11613: To allocate a new object, we need a word, too:
11614: 
11615: @example
11616: : new ( class -- o )  here over @@ allot swap over ! ;
11617: @end example
11618: 
11619: Sometimes derived classes want to access the method of the
11620: parent object. There are two ways to achieve this with Mini-OOF:
11621: first, you could use named words, and second, you could look up the
11622: vtable of the parent object.
11623: 
11624: @example
11625: : :: ( class "name" -- ) ' >body @@ + @@ compile, ;
11626: @end example
11627: 
11628: 
11629: Nothing can be more confusing than a good example, so here is
11630: one. First let's declare a text object (called
11631: @code{button}), that stores text and position:
11632: 
11633: @example
11634: object class
11635:   cell var text
11636:   cell var len
11637:   cell var x
11638:   cell var y
11639:   method init
11640:   method draw
11641: end-class button
11642: @end example
11643: 
11644: @noindent
11645: Now, implement the two methods, @code{draw} and @code{init}:
11646: 
11647: @example
11648: :noname ( o -- )
11649:  >r r@@ x @@ r@@ y @@ at-xy  r@@ text @@ r> len @@ type ;
11650:  button defines draw
11651: :noname ( addr u o -- )
11652:  >r 0 r@@ x ! 0 r@@ y ! r@@ len ! r> text ! ;
11653:  button defines init
11654: @end example
11655: 
11656: @noindent
11657: To demonstrate inheritance, we define a class @code{bold-button}, with no
11658: new data and no new selectors:
11659: 
11660: @example
11661: button class
11662: end-class bold-button
11663: 
11664: : bold   27 emit ." [1m" ;
11665: : normal 27 emit ." [0m" ;
11666: @end example
11667: 
11668: @noindent
11669: The class @code{bold-button} has a different draw method to
11670: @code{button}, but the new method is defined in terms of the draw method
11671: for @code{button}:
11672: 
11673: @example
11674: :noname bold [ button :: draw ] normal ; bold-button defines draw
11675: @end example
11676: 
11677: @noindent
11678: Finally, create two objects and apply selectors:
11679: 
11680: @example
11681: button new Constant foo
11682: s" thin foo" foo init
11683: page
11684: foo draw
11685: bold-button new Constant bar
11686: s" fat bar" bar init
11687: 1 bar y !
11688: bar draw
11689: @end example
11690: 
11691: 
11692: @node Comparison with other object models,  , Mini-OOF, Object-oriented Forth
11693: @subsection Comparison with other object models
11694: @cindex comparison of object models
11695: @cindex object models, comparison
11696: 
11697: Many object-oriented Forth extensions have been proposed (@cite{A survey
11698: of object-oriented Forths} (SIGPLAN Notices, April 1996) by Bradford
11699: J. Rodriguez and W. F. S. Poehlman lists 17). This section discusses the
11700: relation of the object models described here to two well-known and two
11701: closely-related (by the use of method maps) models.  Andras Zsoter
11702: helped us with this section.
11703: 
11704: @cindex Neon model
11705: The most popular model currently seems to be the Neon model (see
11706: @cite{Object-oriented programming in ANS Forth} (Forth Dimensions, March
11707: 1997) by Andrew McKewan) but this model has a number of limitations
11708: @footnote{A longer version of this critique can be
11709: found in @cite{On Standardizing Object-Oriented Forth Extensions} (Forth
11710: Dimensions, May 1997) by Anton Ertl.}:
11711: 
11712: @itemize @bullet
11713: @item
11714: It uses a @code{@emph{selector object}} syntax, which makes it unnatural
11715: to pass objects on the stack.
11716: 
11717: @item
11718: It requires that the selector parses the input stream (at
11719: compile time); this leads to reduced extensibility and to bugs that are
11720: hard to find.
11721: 
11722: @item
11723: It allows using every selector on every object; this eliminates the
11724: need for interfaces, but makes it harder to create efficient
11725: implementations.
11726: @end itemize
11727: 
11728: @cindex Pountain's object-oriented model
11729: Another well-known publication is @cite{Object-Oriented Forth} (Academic
11730: Press, London, 1987) by Dick Pountain. However, it is not really about
11731: object-oriented programming, because it hardly deals with late
11732: binding. Instead, it focuses on features like information hiding and
11733: overloading that are characteristic of modular languages like Ada (83).
11734: 
11735: @cindex Zsoter's object-oriented model
11736: In @uref{http://www.forth.org/oopf.html, Does late binding have to be
11737: slow?} (Forth Dimensions 18(1) 1996, pages 31-35) Andras Zsoter
11738: describes a model that makes heavy use of an active object (like
11739: @code{this} in @file{objects.fs}): The active object is not only used
11740: for accessing all fields, but also specifies the receiving object of
11741: every selector invocation; you have to change the active object
11742: explicitly with @code{@{ ... @}}, whereas in @file{objects.fs} it
11743: changes more or less implicitly at @code{m: ... ;m}. Such a change at
11744: the method entry point is unnecessary with Zsoter's model, because the
11745: receiving object is the active object already. On the other hand, the
11746: explicit change is absolutely necessary in that model, because otherwise
11747: no one could ever change the active object. An ANS Forth implementation
11748: of this model is available through
11749: @uref{http://www.forth.org/oopf.html}.
11750: 
11751: @cindex @file{oof.fs}, differences to other models
11752: The @file{oof.fs} model combines information hiding and overloading
11753: resolution (by keeping names in various word lists) with object-oriented
11754: programming. It sets the active object implicitly on method entry, but
11755: also allows explicit changing (with @code{>o...o>} or with
11756: @code{with...endwith}). It uses parsing and state-smart objects and
11757: classes for resolving overloading and for early binding: the object or
11758: class parses the selector and determines the method from this. If the
11759: selector is not parsed by an object or class, it performs a call to the
11760: selector for the active object (late binding), like Zsoter's model.
11761: Fields are always accessed through the active object. The big
11762: disadvantage of this model is the parsing and the state-smartness, which
11763: reduces extensibility and increases the opportunities for subtle bugs;
11764: essentially, you are only safe if you never tick or @code{postpone} an
11765: object or class (Bernd disagrees, but I (Anton) am not convinced).
11766: 
11767: @cindex @file{mini-oof.fs}, differences to other models
11768: The @file{mini-oof.fs} model is quite similar to a very stripped-down
11769: version of the @file{objects.fs} model, but syntactically it is a
11770: mixture of the @file{objects.fs} and @file{oof.fs} models.
11771: 
11772: 
11773: @c -------------------------------------------------------------
11774: @node Programming Tools, C Interface, Object-oriented Forth, Words
11775: @section Programming Tools
11776: @cindex programming tools
11777: 
11778: @c !! move this and assembler down below OO stuff.
11779: 
11780: @menu
11781: * Examining::                   Data and Code.
11782: * Forgetting words::            Usually before reloading.
11783: * Debugging::                   Simple and quick.
11784: * Assertions::                  Making your programs self-checking.
11785: * Singlestep Debugger::         Executing your program word by word.
11786: @end menu
11787: 
11788: @node Examining, Forgetting words, Programming Tools, Programming Tools
11789: @subsection Examining data and code
11790: @cindex examining data and code
11791: @cindex data examination
11792: @cindex code examination
11793: 
11794: The following words inspect the stack non-destructively:
11795: 
11796: doc-.s
11797: doc-f.s
11798: doc-maxdepth-.s
11799: 
11800: There is a word @code{.r} but it does @i{not} display the return stack!
11801: It is used for formatted numeric output (@pxref{Simple numeric output}).
11802: 
11803: doc-depth
11804: doc-fdepth
11805: doc-clearstack
11806: doc-clearstacks
11807: 
11808: The following words inspect memory.
11809: 
11810: doc-?
11811: doc-dump
11812: 
11813: And finally, @code{see} allows to inspect code:
11814: 
11815: doc-see
11816: doc-xt-see
11817: doc-simple-see
11818: doc-simple-see-range
11819: doc-see-code
11820: doc-see-code-range
11821: 
11822: @node Forgetting words, Debugging, Examining, Programming Tools
11823: @subsection Forgetting words
11824: @cindex words, forgetting
11825: @cindex forgeting words
11826: 
11827: @c  anton: other, maybe better places for this subsection: Defining Words;
11828: @c  Dictionary allocation.  At least a reference should be there.
11829: 
11830: Forth allows you to forget words (and everything that was alloted in the
11831: dictonary after them) in a LIFO manner.
11832: 
11833: doc-marker
11834: 
11835: The most common use of this feature is during progam development: when
11836: you change a source file, forget all the words it defined and load it
11837: again (since you also forget everything defined after the source file
11838: was loaded, you have to reload that, too).  Note that effects like
11839: storing to variables and destroyed system words are not undone when you
11840: forget words.  With a system like Gforth, that is fast enough at
11841: starting up and compiling, I find it more convenient to exit and restart
11842: Gforth, as this gives me a clean slate.
11843: 
11844: Here's an example of using @code{marker} at the start of a source file
11845: that you are debugging; it ensures that you only ever have one copy of
11846: the file's definitions compiled at any time:
11847: 
11848: @example
11849: [IFDEF] my-code
11850:     my-code
11851: [ENDIF]
11852: 
11853: marker my-code
11854: init-included-files
11855: 
11856: \ .. definitions start here
11857: \ .
11858: \ .
11859: \ end
11860: @end example
11861: 
11862: 
11863: @node Debugging, Assertions, Forgetting words, Programming Tools
11864: @subsection Debugging
11865: @cindex debugging
11866: 
11867: Languages with a slow edit/compile/link/test development loop tend to
11868: require sophisticated tracing/stepping debuggers to facilate debugging.
11869: 
11870: A much better (faster) way in fast-compiling languages is to add
11871: printing code at well-selected places, let the program run, look at
11872: the output, see where things went wrong, add more printing code, etc.,
11873: until the bug is found.
11874: 
11875: The simple debugging aids provided in @file{debugs.fs}
11876: are meant to support this style of debugging.
11877: 
11878: The word @code{~~} prints debugging information (by default the source
11879: location and the stack contents). It is easy to insert. If you use Emacs
11880: it is also easy to remove (@kbd{C-x ~} in the Emacs Forth mode to
11881: query-replace them with nothing). The deferred words
11882: @code{printdebugdata} and @code{.debugline} control the output of
11883: @code{~~}. The default source location output format works well with
11884: Emacs' compilation mode, so you can step through the program at the
11885: source level using @kbd{C-x `} (the advantage over a stepping debugger
11886: is that you can step in any direction and you know where the crash has
11887: happened or where the strange data has occurred).
11888: 
11889: doc-~~
11890: doc-printdebugdata
11891: doc-.debugline
11892: 
11893: @cindex filenames in @code{~~} output
11894: @code{~~} (and assertions) will usually print the wrong file name if a
11895: marker is executed in the same file after their occurance.  They will
11896: print @samp{*somewhere*} as file name if a marker is executed in the
11897: same file before their occurance.
11898: 
11899: 
11900: @node Assertions, Singlestep Debugger, Debugging, Programming Tools
11901: @subsection Assertions
11902: @cindex assertions
11903: 
11904: It is a good idea to make your programs self-checking, especially if you
11905: make an assumption that may become invalid during maintenance (for
11906: example, that a certain field of a data structure is never zero). Gforth
11907: supports @dfn{assertions} for this purpose. They are used like this:
11908: 
11909: @example
11910: assert( @i{flag} )
11911: @end example
11912: 
11913: The code between @code{assert(} and @code{)} should compute a flag, that
11914: should be true if everything is alright and false otherwise. It should
11915: not change anything else on the stack. The overall stack effect of the
11916: assertion is @code{( -- )}. E.g.
11917: 
11918: @example
11919: assert( 1 1 + 2 = ) \ what we learn in school
11920: assert( dup 0<> ) \ assert that the top of stack is not zero
11921: assert( false ) \ this code should not be reached
11922: @end example
11923: 
11924: The need for assertions is different at different times. During
11925: debugging, we want more checking, in production we sometimes care more
11926: for speed. Therefore, assertions can be turned off, i.e., the assertion
11927: becomes a comment. Depending on the importance of an assertion and the
11928: time it takes to check it, you may want to turn off some assertions and
11929: keep others turned on. Gforth provides several levels of assertions for
11930: this purpose:
11931: 
11932: 
11933: doc-assert0(
11934: doc-assert1(
11935: doc-assert2(
11936: doc-assert3(
11937: doc-assert(
11938: doc-)
11939: 
11940: 
11941: The variable @code{assert-level} specifies the highest assertions that
11942: are turned on. I.e., at the default @code{assert-level} of one,
11943: @code{assert0(} and @code{assert1(} assertions perform checking, while
11944: @code{assert2(} and @code{assert3(} assertions are treated as comments.
11945: 
11946: The value of @code{assert-level} is evaluated at compile-time, not at
11947: run-time. Therefore you cannot turn assertions on or off at run-time;
11948: you have to set the @code{assert-level} appropriately before compiling a
11949: piece of code. You can compile different pieces of code at different
11950: @code{assert-level}s (e.g., a trusted library at level 1 and
11951: newly-written code at level 3).
11952: 
11953: 
11954: doc-assert-level
11955: 
11956: 
11957: If an assertion fails, a message compatible with Emacs' compilation mode
11958: is produced and the execution is aborted (currently with @code{ABORT"}.
11959: If there is interest, we will introduce a special throw code. But if you
11960: intend to @code{catch} a specific condition, using @code{throw} is
11961: probably more appropriate than an assertion).
11962: 
11963: @cindex filenames in assertion output
11964: Assertions (and @code{~~}) will usually print the wrong file name if a
11965: marker is executed in the same file after their occurance.  They will
11966: print @samp{*somewhere*} as file name if a marker is executed in the
11967: same file before their occurance.
11968: 
11969: Definitions in ANS Forth for these assertion words are provided
11970: in @file{compat/assert.fs}.
11971: 
11972: 
11973: @node Singlestep Debugger,  , Assertions, Programming Tools
11974: @subsection Singlestep Debugger
11975: @cindex singlestep Debugger
11976: @cindex debugging Singlestep
11977: 
11978: The singlestep debugger works only with the engine @code{gforth-itc}.
11979: 
11980: When you create a new word there's often the need to check whether it
11981: behaves correctly or not. You can do this by typing @code{dbg
11982: badword}. A debug session might look like this:
11983: 
11984: @example
11985: : badword 0 DO i . LOOP ;  ok
11986: 2 dbg badword 
11987: : badword  
11988: Scanning code...
11989: 
11990: Nesting debugger ready!
11991: 
11992: 400D4738  8049BC4 0              -> [ 2 ] 00002 00000 
11993: 400D4740  8049F68 DO             -> [ 0 ] 
11994: 400D4744  804A0C8 i              -> [ 1 ] 00000 
11995: 400D4748 400C5E60 .              -> 0 [ 0 ] 
11996: 400D474C  8049D0C LOOP           -> [ 0 ] 
11997: 400D4744  804A0C8 i              -> [ 1 ] 00001 
11998: 400D4748 400C5E60 .              -> 1 [ 0 ] 
11999: 400D474C  8049D0C LOOP           -> [ 0 ] 
12000: 400D4758  804B384 ;              ->  ok
12001: @end example
12002: 
12003: Each line displayed is one step. You always have to hit return to
12004: execute the next word that is displayed. If you don't want to execute
12005: the next word in a whole, you have to type @kbd{n} for @code{nest}. Here is
12006: an overview what keys are available:
12007: 
12008: @table @i
12009: 
12010: @item @key{RET}
12011: Next; Execute the next word.
12012: 
12013: @item n
12014: Nest; Single step through next word.
12015: 
12016: @item u
12017: Unnest; Stop debugging and execute rest of word. If we got to this word
12018: with nest, continue debugging with the calling word.
12019: 
12020: @item d
12021: Done; Stop debugging and execute rest.
12022: 
12023: @item s
12024: Stop; Abort immediately.
12025: 
12026: @end table
12027: 
12028: Debugging large application with this mechanism is very difficult, because
12029: you have to nest very deeply into the program before the interesting part
12030: begins. This takes a lot of time. 
12031: 
12032: To do it more directly put a @code{BREAK:} command into your source code.
12033: When program execution reaches @code{BREAK:} the single step debugger is
12034: invoked and you have all the features described above.
12035: 
12036: If you have more than one part to debug it is useful to know where the
12037: program has stopped at the moment. You can do this by the 
12038: @code{BREAK" string"} command. This behaves like @code{BREAK:} except that
12039: string is typed out when the ``breakpoint'' is reached.
12040: 
12041: 
12042: doc-dbg
12043: doc-break:
12044: doc-break"
12045: 
12046: @c ------------------------------------------------------------
12047: @node C Interface, Assembler and Code Words, Programming Tools, Words
12048: @section C Interface
12049: @cindex C interface
12050: @cindex foreign language interface
12051: @cindex interface to C functions
12052: 
12053: Note that the C interface is not yet complete; callbacks are missing,
12054: as well as a way of declaring structs, unions, and their fields.
12055: 
12056: @menu
12057: * Calling C Functions::         
12058: * Declaring C Functions::       
12059: * Calling C function pointers::  
12060: * Defining library interfaces::  
12061: * Declaring OS-level libraries::  
12062: * Callbacks::                   
12063: * C interface internals::       
12064: * Low-Level C Interface Words::  
12065: @end menu
12066: 
12067: @node Calling C Functions, Declaring C Functions, C Interface, C Interface
12068: @subsection Calling C functions
12069: @cindex C functions, calls to
12070: @cindex calling C functions
12071: 
12072: Once a C function is declared (see @pxref{Declaring C Functions}), you
12073: can call it as follows: You push the arguments on the stack(s), and
12074: then call the word for the C function.  The arguments have to be
12075: pushed in the same order as the arguments appear in the C
12076: documentation (i.e., the first argument is deepest on the stack).
12077: Integer and pointer arguments have to be pushed on the data stack,
12078: floating-point arguments on the FP stack; these arguments are consumed
12079: by the called C function.
12080: 
12081: On returning from the C function, the return value, if any, resides on
12082: the appropriate stack: an integer return value is pushed on the data
12083: stack, an FP return value on the FP stack, and a void return value
12084: results in not pushing anything.  Note that most C functions have a
12085: return value, even if that is often not used in C; in Forth, you have
12086: to @code{drop} this return value explicitly if you do not use it.
12087: 
12088: The C interface automatically converts between the C type and the
12089: Forth type as necessary, on a best-effort basis (in some cases, there
12090: may be some loss).
12091: 
12092: As an example, consider the POSIX function @code{lseek()}:
12093: 
12094: @example
12095: off_t lseek(int fd, off_t offset, int whence);
12096: @end example
12097: 
12098: This function takes three integer arguments, and returns an integer
12099: argument, so a Forth call for setting the current file offset to the
12100: start of the file could look like this:
12101: 
12102: @example
12103: fd @@ 0 SEEK_SET lseek -1 = if
12104:   ... \ error handling
12105: then
12106: @end example
12107: 
12108: You might be worried that an @code{off_t} does not fit into a cell, so
12109: you could not pass larger offsets to lseek, and might get only a part
12110: of the return values.  In that case, in your declaration of the
12111: function (@pxref{Declaring C Functions}) you should declare it to use
12112: double-cells for the off_t argument and return value, and maybe give
12113: the resulting Forth word a different name, like @code{dlseek}; the
12114: result could be called like this:
12115: 
12116: @example
12117: fd @@ 0. SEEK_SET dlseek -1. d= if
12118:   ... \ error handling
12119: then
12120: @end example
12121: 
12122: Passing and returning structs or unions is currently not supported by
12123: our interface@footnote{If you know the calling convention of your C
12124: compiler, you usually can call such functions in some way, but that
12125: way is usually not portable between platforms, and sometimes not even
12126: between C compilers.}.
12127: 
12128: Calling functions with a variable number of arguments (@emph{variadic}
12129: functions, e.g., @code{printf()}) is only supported by having you
12130: declare one function-calling word for each argument pattern, and
12131: calling the appropriate word for the desired pattern.
12132: 
12133: 
12134: 
12135: @node Declaring C Functions, Calling C function pointers, Calling C Functions, C Interface
12136: @subsection Declaring C Functions
12137: @cindex C functions, declarations
12138: @cindex declaring C functions
12139: 
12140: Before you can call @code{lseek} or @code{dlseek}, you have to declare
12141: it.  The declaration consists of two parts: 
12142: 
12143: @table @b
12144: 
12145: @item The C part
12146: is the C declaration of the function, or more typically and portably,
12147: a C-style @code{#include} of a file that contains the declaration of
12148: the C function.
12149: 
12150: @item The Forth part
12151: declares the Forth types of the parameters and the Forth word name
12152: corresponding to the C function.
12153: 
12154: @end table
12155: 
12156: For the words @code{lseek} and @code{dlseek} mentioned earlier, the
12157: declarations are:
12158: 
12159: @example
12160: \c #define _FILE_OFFSET_BITS 64
12161: \c #include <sys/types.h>
12162: \c #include <unistd.h>
12163: c-function lseek lseek n n n -- n
12164: c-function dlseek lseek n d n -- d
12165: @end example
12166: 
12167: The C part of the declarations is prefixed by @code{\c}, and the rest
12168: of the line is ordinary C code.  You can use as many lines of C
12169: declarations as you like, and they are visible for all further
12170: function declarations.
12171: 
12172: The Forth part declares each interface word with @code{c-function},
12173: followed by the Forth name of the word, the C name of the called
12174: function, and the stack effect of the word.  The stack effect contains
12175: an arbitrary number of types of parameters, then @code{--}, and then
12176: exactly one type for the return value.  The possible types are:
12177: 
12178: @table @code
12179: 
12180: @item n
12181: single-cell integer
12182: 
12183: @item a
12184: address (single-cell)
12185: 
12186: @item d
12187: double-cell integer
12188: 
12189: @item r
12190: floating-point value
12191: 
12192: @item func
12193: C function pointer
12194: 
12195: @item void
12196: no value (used as return type for void functions)
12197: 
12198: @end table
12199: 
12200: @cindex variadic C functions
12201: 
12202: To deal with variadic C functions, you can declare one Forth word for
12203: every pattern you want to use, e.g.:
12204: 
12205: @example
12206: \c #include <stdio.h>
12207: c-function printf-nr printf a n r -- n
12208: c-function printf-rn printf a r n -- n
12209: @end example
12210: 
12211: Note that with C functions declared as variadic (or if you don't
12212: provide a prototype), the C interface has no C type to convert to, so
12213: no automatic conversion happens, which may lead to portability
12214: problems in some cases.  In such cases you can perform the conversion
12215: explicitly on the C level, e.g., as follows:
12216: 
12217: @example
12218: \c #define printfll(s,ll) printf(s,(long long)ll)
12219: c-function printfll printfll a n -- n
12220: @end example
12221: 
12222: Here, instead of calling @code{printf()} directly, we define a macro
12223: that casts (converts) the Forth single-cell integer into a
12224: C @code{long long} before calling @code{printf()}.
12225: 
12226: doc-\c
12227: doc-c-function
12228: 
12229: In order to work, this C interface invokes GCC at run-time and uses
12230: dynamic linking.  If these features are not available, there are
12231: other, less convenient and less portable C interfaces in @file{lib.fs}
12232: and @file{oldlib.fs}.  These interfaces are mostly undocumented and
12233: mostly incompatible with each other and with the documented C
12234: interface; you can find some examples for the @file{lib.fs} interface
12235: in @file{lib.fs}.
12236: 
12237: 
12238: @node Calling C function pointers, Defining library interfaces, Declaring C Functions, C Interface
12239: @subsection Calling C function pointers from Forth
12240: @cindex C function pointers, calling from Forth
12241: 
12242: If you come across a C function pointer (e.g., in some C-constructed
12243: structure) and want to call it from your Forth program, you can also
12244: use the features explained until now to achieve that, as follows:
12245: 
12246: Let us assume that there is a C function pointer type @code{func1}
12247: defined in some header file @file{func1.h}, and you know that these
12248: functions take one integer argument and return an integer result; and
12249: you want to call functions through such pointers.  Just define
12250: 
12251: @example
12252: \c #include <func1.h>
12253: \c #define call_func1(par1,fptr) ((func1)fptr)(par1)
12254: c-function call-func1 call_func1 n func -- n
12255: @end example
12256: 
12257: and then you can call a function pointed to by, say @code{func1a} as
12258: follows:
12259: 
12260: @example
12261: -5 func1a call-func1 .
12262: @end example
12263: 
12264: In the C part, @code{call_func} is defined as a macro to avoid having
12265: to declare the exact parameter and return types, so the C compiler
12266: knows them from the declaration of @code{func1}.
12267: 
12268: The Forth word @code{call-func1} is similar to @code{execute}, except
12269: that it takes a C @code{func1} pointer instead of a Forth execution
12270: token, and it is specific to @code{func1} pointers.  For each type of
12271: function pointer you want to call from Forth, you have to define
12272: a separate calling word.
12273: 
12274: 
12275: @node Defining library interfaces, Declaring OS-level libraries, Calling C function pointers, C Interface
12276: @subsection Defining library interfaces
12277: @cindex giving a name to a library interface
12278: @cindex library interface names
12279: 
12280: You can give a name to a bunch of C function declarations (a library
12281: interface), as follows:
12282: 
12283: @example
12284: c-library lseek-lib
12285: \c #define _FILE_OFFSET_BITS 64
12286: ...
12287: end-c-library
12288: @end example
12289: 
12290: The effect of giving such a name to the interface is that the
12291: generated files will contain that name, and when you use the interface
12292: a second time, it will use the existing files instead of generating
12293: and compiling them again, saving you time.  Note that even if you
12294: change the declarations, the old (stale) files will be used, probably
12295: leading to errors.  So, during development of the declarations we
12296: recommend not using @code{c-library}.
12297: 
12298: Note that the library name is not allocated in the dictionary and
12299: therefore does not shadow dictionary names.  It is used in the file
12300: system, so you have to use naming conventions appropriate for file
12301: systems.  Also, you must not call a function you declare after
12302: @code{c-library} before you perform @code{end-c-library}.
12303: 
12304: A major benefit of these named library interfaces is that, once they
12305: are generated, the tools used to generated them (in particular, the C
12306: compiler and libtool) are no longer needed, so the interface can be
12307: used even on machines that do not have the tools installed.
12308: 
12309: doc-c-library-name
12310: doc-c-library
12311: doc-end-c-library
12312: 
12313: 
12314: @node Declaring OS-level libraries, Callbacks, Defining library interfaces, C Interface
12315: @subsection Declaring OS-level libraries
12316: @cindex Shared libraries in C interface
12317: @cindex Dynamically linked libraries in C interface
12318: @cindex Libraries in C interface
12319: 
12320: For calling some C functions, you need to link with a specific
12321: OS-level library that contains that function.  E.g., the @code{sin}
12322: function requires linking a special library by using the command line
12323: switch @code{-lm}.  In our C iterface you do the equivalent thing by
12324: calling @code{add-lib} as follows:
12325: 
12326: @example
12327: clear-libs
12328: s" m" add-lib
12329: \c #include <math.h>
12330: c-function sin sin r -- r
12331: @end example
12332: 
12333: First, you clear any libraries that may have been declared earlier
12334: (you don't need them for @code{sin}); then you add the @code{m}
12335: library (actually @code{libm.so} or somesuch) to the currently
12336: declared libraries; you can add as many as you need.  Finally you
12337: declare the function as shown above.  Typically you will use the same
12338: set of library declarations for many function declarations; you need
12339: to write only one set for that, right at the beginning.
12340: 
12341: Note that you must not call @code{clear-libs} inside
12342: @code{c-library...end-c-library}; however, @code{c-library} performs
12343: the function of @code{clear-libs}, so @code{clear-libs} is not
12344: necessary, and you usually want to put @code{add-lib} calls inside
12345: @code{c-library...end-c-library}.
12346: 
12347: doc-clear-libs
12348: doc-add-lib
12349: 
12350: 
12351: @node Callbacks, C interface internals, Declaring OS-level libraries, C Interface
12352: @subsection Callbacks
12353: @cindex Callback functions written in Forth
12354: @cindex C function pointers to Forth words
12355: 
12356: Callbacks are not yet supported by the documented C interface.  You
12357: can use the undocumented @file{lib.fs} interface for callbacks.
12358: 
12359: In some cases you have to pass a function pointer to a C function,
12360: i.e., the library wants to call back to your application (and the
12361: pointed-to function is called a callback function).  You can pass the
12362: address of an existing C function (that you get with @code{lib-sym},
12363: @pxref{Low-Level C Interface Words}), but if there is no appropriate C
12364: function, you probably want to define the function as a Forth word.
12365: 
12366: @c I don't understand the existing callback interface from the example - anton
12367: 
12368: 
12369: @c > > Und dann gibt's noch die fptr-Deklaration, die einem
12370: @c > > C-Funktionspointer entspricht (Deklaration gleich wie bei
12371: @c > > Library-Funktionen, nur ohne den C-Namen, Aufruf mit der
12372: @c > > C-Funktionsadresse auf dem TOS).
12373: @c >
12374: @c > Ja, da bin ich dann ausgestiegen, weil ich aus dem Beispiel nicht
12375: @c > gesehen habe, wozu das gut ist.
12376: @c 
12377: @c Irgendwie muss ich den Callback ja testen. Und es soll ja auch 
12378: @c vorkommen, dass man von irgendwelchen kranken Interfaces einen 
12379: @c Funktionspointer übergeben bekommt, den man dann bei Gelegenheit 
12380: @c aufrufen muss. Also kann man den deklarieren, und das damit deklarierte 
12381: @c Wort verhält sich dann wie ein EXECUTE für alle C-Funktionen mit 
12382: @c demselben Prototyp.
12383: 
12384: 
12385: @node C interface internals, Low-Level C Interface Words, Callbacks, C Interface
12386: @subsection How the C interface works
12387: 
12388: The documented C interface works by generating a C code out of the
12389: declarations.
12390: 
12391: In particular, for every Forth word declared with @code{c-function},
12392: it generates a wrapper function in C that takes the Forth data from
12393: the Forth stacks, and calls the target C function with these data as
12394: arguments.  The C compiler then performs an implicit conversion
12395: between the Forth type from the stack, and the C type for the
12396: parameter, which is given by the C function prototype.  After the C
12397: function returns, the return value is likewise implicitly converted to
12398: a Forth type and written back on the stack.
12399: 
12400: The @code{\c} lines are literally included in the C code (but without
12401: the @code{\c}), and provide the necessary declarations so that the C
12402: compiler knows the C types and has enough information to perform the
12403: conversion.
12404: 
12405: These wrapper functions are eventually compiled and dynamically linked
12406: into Gforth, and then they can be called.
12407: 
12408: The libraries added with @code{add-lib} are used in the compile
12409: command line to specify dependent libraries with @code{-l@var{lib}},
12410: causing these libraries to be dynamically linked when the wrapper
12411: function is linked.
12412: 
12413: 
12414: @node Low-Level C Interface Words,  , C interface internals, C Interface
12415: @subsection Low-Level C Interface Words
12416: 
12417: doc-open-lib
12418: doc-lib-sym
12419: doc-lib-error
12420: doc-call-c
12421: 
12422: @c -------------------------------------------------------------
12423: @node Assembler and Code Words, Threading Words, C Interface, Words
12424: @section Assembler and Code Words
12425: @cindex assembler
12426: @cindex code words
12427: 
12428: @menu
12429: * Code and ;code::              
12430: * Common Assembler::            Assembler Syntax
12431: * Common Disassembler::         
12432: * 386 Assembler::               Deviations and special cases
12433: * Alpha Assembler::             Deviations and special cases
12434: * MIPS assembler::              Deviations and special cases
12435: * PowerPC assembler::           Deviations and special cases
12436: * ARM Assembler::               Deviations and special cases
12437: * Other assemblers::            How to write them
12438: @end menu
12439: 
12440: @node Code and ;code, Common Assembler, Assembler and Code Words, Assembler and Code Words
12441: @subsection @code{Code} and @code{;code}
12442: 
12443: Gforth provides some words for defining primitives (words written in
12444: machine code), and for defining the machine-code equivalent of
12445: @code{DOES>}-based defining words. However, the machine-independent
12446: nature of Gforth poses a few problems: First of all, Gforth runs on
12447: several architectures, so it can provide no standard assembler. What's
12448: worse is that the register allocation not only depends on the processor,
12449: but also on the @code{gcc} version and options used.
12450: 
12451: The words that Gforth offers encapsulate some system dependences (e.g.,
12452: the header structure), so a system-independent assembler may be used in
12453: Gforth. If you do not have an assembler, you can compile machine code
12454: directly with @code{,} and @code{c,}@footnote{This isn't portable,
12455: because these words emit stuff in @i{data} space; it works because
12456: Gforth has unified code/data spaces. Assembler isn't likely to be
12457: portable anyway.}.
12458: 
12459: 
12460: doc-assembler
12461: doc-init-asm
12462: doc-code
12463: doc-end-code
12464: doc-;code
12465: doc-flush-icache
12466: 
12467: 
12468: If @code{flush-icache} does not work correctly, @code{code} words
12469: etc. will not work (reliably), either.
12470: 
12471: The typical usage of these @code{code} words can be shown most easily by
12472: analogy to the equivalent high-level defining words:
12473: 
12474: @example
12475: : foo                              code foo
12476:    <high-level Forth words>              <assembler>
12477: ;                                  end-code
12478:                                 
12479: : bar                              : bar
12480:    <high-level Forth words>           <high-level Forth words>
12481:    CREATE                             CREATE
12482:       <high-level Forth words>           <high-level Forth words>
12483:    DOES>                              ;code
12484:       <high-level Forth words>           <assembler>
12485: ;                                  end-code
12486: @end example
12487: 
12488: @c anton: the following stuff is also in "Common Assembler", in less detail.
12489: 
12490: @cindex registers of the inner interpreter
12491: In the assembly code you will want to refer to the inner interpreter's
12492: registers (e.g., the data stack pointer) and you may want to use other
12493: registers for temporary storage. Unfortunately, the register allocation
12494: is installation-dependent.
12495: 
12496: In particular, @code{ip} (Forth instruction pointer) and @code{rp}
12497: (return stack pointer) may be in different places in @code{gforth} and
12498: @code{gforth-fast}, or different installations.  This means that you
12499: cannot write a @code{NEXT} routine that works reliably on both versions
12500: or different installations; so for doing @code{NEXT}, I recommend
12501: jumping to @code{' noop >code-address}, which contains nothing but a
12502: @code{NEXT}.
12503: 
12504: For general accesses to the inner interpreter's registers, the easiest
12505: solution is to use explicit register declarations (@pxref{Explicit Reg
12506: Vars, , Variables in Specified Registers, gcc.info, GNU C Manual}) for
12507: all of the inner interpreter's registers: You have to compile Gforth
12508: with @code{-DFORCE_REG} (configure option @code{--enable-force-reg}) and
12509: the appropriate declarations must be present in the @code{machine.h}
12510: file (see @code{mips.h} for an example; you can find a full list of all
12511: declarable register symbols with @code{grep register engine.c}). If you
12512: give explicit registers to all variables that are declared at the
12513: beginning of @code{engine()}, you should be able to use the other
12514: caller-saved registers for temporary storage. Alternatively, you can use
12515: the @code{gcc} option @code{-ffixed-REG} (@pxref{Code Gen Options, ,
12516: Options for Code Generation Conventions, gcc.info, GNU C Manual}) to
12517: reserve a register (however, this restriction on register allocation may
12518: slow Gforth significantly).
12519: 
12520: If this solution is not viable (e.g., because @code{gcc} does not allow
12521: you to explicitly declare all the registers you need), you have to find
12522: out by looking at the code where the inner interpreter's registers
12523: reside and which registers can be used for temporary storage. You can
12524: get an assembly listing of the engine's code with @code{make engine.s}.
12525: 
12526: In any case, it is good practice to abstract your assembly code from the
12527: actual register allocation. E.g., if the data stack pointer resides in
12528: register @code{$17}, create an alias for this register called @code{sp},
12529: and use that in your assembly code.
12530: 
12531: @cindex code words, portable
12532: Another option for implementing normal and defining words efficiently
12533: is to add the desired functionality to the source of Gforth. For normal
12534: words you just have to edit @file{primitives} (@pxref{Automatic
12535: Generation}). Defining words (equivalent to @code{;CODE} words, for fast
12536: defined words) may require changes in @file{engine.c}, @file{kernel.fs},
12537: @file{prims2x.fs}, and possibly @file{cross.fs}.
12538: 
12539: @node Common Assembler, Common Disassembler, Code and ;code, Assembler and Code Words
12540: @subsection Common Assembler
12541: 
12542: The assemblers in Gforth generally use a postfix syntax, i.e., the
12543: instruction name follows the operands.
12544: 
12545: The operands are passed in the usual order (the same that is used in the
12546: manual of the architecture).  Since they all are Forth words, they have
12547: to be separated by spaces; you can also use Forth words to compute the
12548: operands.
12549: 
12550: The instruction names usually end with a @code{,}.  This makes it easier
12551: to visually separate instructions if you put several of them on one
12552: line; it also avoids shadowing other Forth words (e.g., @code{and}).
12553: 
12554: Registers are usually specified by number; e.g., (decimal) @code{11}
12555: specifies registers R11 and F11 on the Alpha architecture (which one,
12556: depends on the instruction).  The usual names are also available, e.g.,
12557: @code{s2} for R11 on Alpha.
12558: 
12559: Control flow is specified similar to normal Forth code (@pxref{Arbitrary
12560: control structures}), with @code{if,}, @code{ahead,}, @code{then,},
12561: @code{begin,}, @code{until,}, @code{again,}, @code{cs-roll},
12562: @code{cs-pick}, @code{else,}, @code{while,}, and @code{repeat,}.  The
12563: conditions are specified in a way specific to each assembler.
12564: 
12565: Note that the register assignments of the Gforth engine can change
12566: between Gforth versions, or even between different compilations of the
12567: same Gforth version (e.g., if you use a different GCC version).  So if
12568: you want to refer to Gforth's registers (e.g., the stack pointer or
12569: TOS), I recommend defining your own words for refering to these
12570: registers, and using them later on; then you can easily adapt to a
12571: changed register assignment.  The stability of the register assignment
12572: is usually better if you build Gforth with @code{--enable-force-reg}.
12573: 
12574: The most common use of these registers is to dispatch to the next word
12575: (the @code{next} routine).  A portable way to do this is to jump to
12576: @code{' noop >code-address} (of course, this is less efficient than
12577: integrating the @code{next} code and scheduling it well).
12578: 
12579: Another difference between Gforth version is that the top of stack is
12580: kept in memory in @code{gforth} and, on most platforms, in a register in
12581: @code{gforth-fast}.
12582: 
12583: @node  Common Disassembler, 386 Assembler, Common Assembler, Assembler and Code Words
12584: @subsection Common Disassembler
12585: @cindex disassembler, general
12586: @cindex gdb disassembler
12587: 
12588: You can disassemble a @code{code} word with @code{see}
12589: (@pxref{Debugging}).  You can disassemble a section of memory with
12590: 
12591: doc-discode
12592: 
12593: There are two kinds of disassembler for Gforth: The Forth disassembler
12594: (available on some CPUs) and the gdb disassembler (available on
12595: platforms with @command{gdb} and @command{mktemp}).  If both are
12596: available, the Forth disassembler is used by default.  If you prefer
12597: the gdb disassembler, say
12598: 
12599: @example
12600: ' disasm-gdb is discode
12601: @end example
12602: 
12603: If neither is available, @code{discode} performs @code{dump}.
12604: 
12605: The Forth disassembler generally produces output that can be fed into the
12606: assembler (i.e., same syntax, etc.).  It also includes additional
12607: information in comments.  In particular, the address of the instruction
12608: is given in a comment before the instruction.
12609: 
12610: The gdb disassembler produces output in the same format as the gdb
12611: @code{disassemble} command (@pxref{Machine Code,,Source and machine
12612: code,gdb,Debugging with GDB}), in the default flavour (AT&T syntax for
12613: the 386 and AMD64 architectures).
12614: 
12615: @code{See} may display more or less than the actual code of the word,
12616: because the recognition of the end of the code is unreliable.  You can
12617: use @code{discode} if it did not display enough.  It may display more, if
12618: the code word is not immediately followed by a named word.  If you have
12619: something else there, you can follow the word with @code{align latest ,}
12620: to ensure that the end is recognized.
12621: 
12622: @node 386 Assembler, Alpha Assembler, Common Disassembler, Assembler and Code Words
12623: @subsection 386 Assembler
12624: 
12625: The 386 assembler included in Gforth was written by Bernd Paysan, it's
12626: available under GPL, and originally part of bigFORTH.
12627: 
12628: The 386 disassembler included in Gforth was written by Andrew McKewan
12629: and is in the public domain.
12630: 
12631: The disassembler displays code in an Intel-like prefix syntax.
12632: 
12633: The assembler uses a postfix syntax with reversed parameters.
12634: 
12635: The assembler includes all instruction of the Athlon, i.e. 486 core
12636: instructions, Pentium and PPro extensions, floating point, MMX, 3Dnow!,
12637: but not ISSE. It's an integrated 16- and 32-bit assembler. Default is 32
12638: bit, you can switch to 16 bit with .86 and back to 32 bit with .386.
12639: 
12640: There are several prefixes to switch between different operation sizes,
12641: @code{.b} for byte accesses, @code{.w} for word accesses, @code{.d} for
12642: double-word accesses. Addressing modes can be switched with @code{.wa}
12643: for 16 bit addresses, and @code{.da} for 32 bit addresses. You don't
12644: need a prefix for byte register names (@code{AL} et al).
12645: 
12646: For floating point operations, the prefixes are @code{.fs} (IEEE
12647: single), @code{.fl} (IEEE double), @code{.fx} (extended), @code{.fw}
12648: (word), @code{.fd} (double-word), and @code{.fq} (quad-word).
12649: 
12650: The MMX opcodes don't have size prefixes, they are spelled out like in
12651: the Intel assembler. Instead of move from and to memory, there are
12652: PLDQ/PLDD and PSTQ/PSTD.
12653: 
12654: The registers lack the 'e' prefix; even in 32 bit mode, eax is called
12655: ax.  Immediate values are indicated by postfixing them with @code{#},
12656: e.g., @code{3 #}.  Here are some examples of addressing modes in various
12657: syntaxes:
12658: 
12659: @example
12660: Gforth          Intel (NASM)   AT&T (gas)      Name
12661: .w ax           ax             %ax             register (16 bit)
12662: ax              eax            %eax            register (32 bit)
12663: 3 #             offset 3       $3              immediate
12664: 1000 #)         byte ptr 1000  1000            displacement
12665: bx )            [ebx]          (%ebx)          base
12666: 100 di d)       100[edi]       100(%edi)       base+displacement
12667: 20 ax *4 i#)    20[eax*4]      20(,%eax,4)     (index*scale)+displacement
12668: di ax *4 i)     [edi][eax*4]   (%edi,%eax,4)   base+(index*scale)
12669: 4 bx cx di)     4[ebx][ecx]    4(%ebx,%ecx)    base+index+displacement
12670: 12 sp ax *2 di) 12[esp][eax*2] 12(%esp,%eax,2) base+(index*scale)+displacement
12671: @end example
12672: 
12673: You can use @code{L)} and @code{LI)} instead of @code{D)} and
12674: @code{DI)} to enforce 32-bit displacement fields (useful for
12675: later patching).
12676: 
12677: Some example of instructions are:
12678: 
12679: @example
12680: ax bx mov             \ move ebx,eax
12681: 3 # ax mov            \ mov eax,3
12682: 100 di d) ax mov      \ mov eax,100[edi]
12683: 4 bx cx di) ax mov    \ mov eax,4[ebx][ecx]
12684: .w ax bx mov          \ mov bx,ax
12685: @end example
12686: 
12687: The following forms are supported for binary instructions:
12688: 
12689: @example
12690: <reg> <reg> <inst>
12691: <n> # <reg> <inst>
12692: <mem> <reg> <inst>
12693: <reg> <mem> <inst>
12694: <n> # <mem> <inst>
12695: @end example
12696: 
12697: The shift/rotate syntax is:
12698: 
12699: @example
12700: <reg/mem> 1 # shl \ shortens to shift without immediate
12701: <reg/mem> 4 # shl
12702: <reg/mem> cl shl
12703: @end example
12704: 
12705: Precede string instructions (@code{movs} etc.) with @code{.b} to get
12706: the byte version.
12707: 
12708: The control structure words @code{IF} @code{UNTIL} etc. must be preceded
12709: by one of these conditions: @code{vs vc u< u>= 0= 0<> u<= u> 0< 0>= ps
12710: pc < >= <= >}. (Note that most of these words shadow some Forth words
12711: when @code{assembler} is in front of @code{forth} in the search path,
12712: e.g., in @code{code} words).  Currently the control structure words use
12713: one stack item, so you have to use @code{roll} instead of @code{cs-roll}
12714: to shuffle them (you can also use @code{swap} etc.).
12715: 
12716: Here is an example of a @code{code} word (assumes that the stack pointer
12717: is in esi and the TOS is in ebx):
12718: 
12719: @example
12720: code my+ ( n1 n2 -- n )
12721:     4 si D) bx add
12722:     4 # si add
12723:     Next
12724: end-code
12725: @end example
12726: 
12727: 
12728: @node Alpha Assembler, MIPS assembler, 386 Assembler, Assembler and Code Words
12729: @subsection Alpha Assembler
12730: 
12731: The Alpha assembler and disassembler were originally written by Bernd
12732: Thallner.
12733: 
12734: The register names @code{a0}--@code{a5} are not available to avoid
12735: shadowing hex numbers.
12736: 
12737: Immediate forms of arithmetic instructions are distinguished by a
12738: @code{#} just before the @code{,}, e.g., @code{and#,} (note: @code{lda,}
12739: does not count as arithmetic instruction).
12740: 
12741: You have to specify all operands to an instruction, even those that
12742: other assemblers consider optional, e.g., the destination register for
12743: @code{br,}, or the destination register and hint for @code{jmp,}.
12744: 
12745: You can specify conditions for @code{if,} by removing the first @code{b}
12746: and the trailing @code{,} from a branch with a corresponding name; e.g.,
12747: 
12748: @example
12749: 11 fgt if, \ if F11>0e
12750:   ...
12751: endif,
12752: @end example
12753: 
12754: @code{fbgt,} gives @code{fgt}.  
12755: 
12756: @node MIPS assembler, PowerPC assembler, Alpha Assembler, Assembler and Code Words
12757: @subsection MIPS assembler
12758: 
12759: The MIPS assembler was originally written by Christian Pirker.
12760: 
12761: Currently the assembler and disassembler only cover the MIPS-I
12762: architecture (R3000), and don't support FP instructions.
12763: 
12764: The register names @code{$a0}--@code{$a3} are not available to avoid
12765: shadowing hex numbers.
12766: 
12767: Because there is no way to distinguish registers from immediate values,
12768: you have to explicitly use the immediate forms of instructions, i.e.,
12769: @code{addiu,}, not just @code{addu,} (@command{as} does this
12770: implicitly).
12771: 
12772: If the architecture manual specifies several formats for the instruction
12773: (e.g., for @code{jalr,}), you usually have to use the one with more
12774: arguments (i.e., two for @code{jalr,}).  When in doubt, see
12775: @code{arch/mips/testasm.fs} for an example of correct use.
12776: 
12777: Branches and jumps in the MIPS architecture have a delay slot.  You have
12778: to fill it yourself (the simplest way is to use @code{nop,}), the
12779: assembler does not do it for you (unlike @command{as}).  Even
12780: @code{if,}, @code{ahead,}, @code{until,}, @code{again,}, @code{while,},
12781: @code{else,} and @code{repeat,} need a delay slot.  Since @code{begin,}
12782: and @code{then,} just specify branch targets, they are not affected.
12783: 
12784: Note that you must not put branches, jumps, or @code{li,} into the delay
12785: slot: @code{li,} may expand to several instructions, and control flow
12786: instructions may not be put into the branch delay slot in any case.
12787: 
12788: For branches the argument specifying the target is a relative address;
12789: You have to add the address of the delay slot to get the absolute
12790: address.
12791: 
12792: The MIPS architecture also has load delay slots and restrictions on
12793: using @code{mfhi,} and @code{mflo,}; you have to order the instructions
12794: yourself to satisfy these restrictions, the assembler does not do it for
12795: you.
12796: 
12797: You can specify the conditions for @code{if,} etc. by taking a
12798: conditional branch and leaving away the @code{b} at the start and the
12799: @code{,} at the end.  E.g.,
12800: 
12801: @example
12802: 4 5 eq if,
12803:   ... \ do something if $4 equals $5
12804: then,
12805: @end example
12806: 
12807: 
12808: @node PowerPC assembler, ARM Assembler, MIPS assembler, Assembler and Code Words
12809: @subsection PowerPC assembler
12810: 
12811: The PowerPC assembler and disassembler were contributed by Michal
12812: Revucky.
12813: 
12814: This assembler does not follow the convention of ending mnemonic names
12815: with a ``,'', so some mnemonic names shadow regular Forth words (in
12816: particular: @code{and or xor fabs}); so if you want to use the Forth
12817: words, you have to make them visible first, e.g., with @code{also
12818: forth}.
12819: 
12820: Registers are referred to by their number, e.g., @code{9} means the
12821: integer register 9 or the FP register 9 (depending on the
12822: instruction).
12823: 
12824: Because there is no way to distinguish registers from immediate values,
12825: you have to explicitly use the immediate forms of instructions, i.e.,
12826: @code{addi,}, not just @code{add,}.
12827: 
12828: The assembler and disassembler usually support the most general form
12829: of an instruction, but usually not the shorter forms (especially for
12830: branches).
12831: 
12832: 
12833: @node ARM Assembler, Other assemblers, PowerPC assembler, Assembler and Code Words
12834: @subsection ARM Assembler
12835: 
12836: The ARM assembler included in Gforth was written from scratch by David
12837: Kuehling.
12838: 
12839: The assembler includes all instruction of ARM architecture version 4,
12840: but does not (yet) have support for Thumb instructions.  It also lacks
12841: support for any co-processors.
12842: 
12843: The assembler uses a postfix syntax with the target operand specified
12844: last.  For load/store instructions the last operand will be the
12845: register(s) to be loaded from/stored to.
12846: 
12847: Registers are specified by their names @code{r0} through @code{r15},
12848: with the aliases @code{pc}, @code{lr}, @code{sp}, @code{ip} and
12849: @code{fp} provided for convenience.  Note that @code{ip} means intra
12850: procedure call scratch register (@code{r12}) and does not refer to the
12851: instruction pointer.
12852: 
12853: Condition codes can be specified anywhere in the instruction, but will
12854: be most readable if specified just in front of the mnemonic.  The 'S'
12855: flag is not a separate word, but encoded into instruction mnemonics,
12856: ie. just use @code{adds,} instead of @code{add,} if you want the
12857: status register to be updated.
12858: 
12859: The following table lists the syntax of operands for general
12860: instructions:
12861: 
12862: @example
12863: Gforth          normal assembler      description
12864: 123 #           #123                  immediate
12865: r12             r12                   register
12866: r12 4 #LSL      r12, LSL #4           shift left by immediate
12867: r12 r1 #LSL     r12, LSL r1           shift left by register
12868: r12 4 #LSR      r12, LSR #4           shift right by immediate
12869: r12 r1 #LSR     r12, LSR r1           shift right by register
12870: r12 4 #ASR      r12, ASR #4           arithmetic shift right
12871: r12 r1 #ASR     r12, ASR r1           ... by register
12872: r12 4 #ROR      r12, ROR #4           rotate right by immediate
12873: r12 r1 #ROR     r12, ROR r1           ... by register
12874: r12 RRX         r12, RRX              rotate right with extend by 1
12875: @end example
12876: 
12877: Memory operand syntax is listed in this table:
12878: 
12879: @example
12880: Gforth            normal assembler      description
12881: r4 ]              [r4]                  register
12882: r4 4 #]           [r4, #+4]             register with immediate offset
12883: r4 -4 #]          [r4, #-4]             with negative offset
12884: r4 r1 +]          [r4, +r1]             register with register offset
12885: r4 r1 -]          [r4, -r1]             with negated register offset
12886: r4 r1 2 #LSL -]   [r4, -r1, LSL #2]     with negated and shifted offset
12887: r4 4 #]!          [r4, #+4]!            immediate preincrement
12888: r4 r1 +]!         [r4, +r1]!            register preincrement
12889: r4 r1 -]!         [r4, +r1]!            register predecrement
12890: r4 r1 2 #LSL +]!  [r4, +r1, LSL #2]!    shifted preincrement
12891: r4 -4 ]#          [r4], #-4             immediate postdecrement
12892: r4 r1 ]+          [r4], r1              register postincrement
12893: r4 r1 ]-          [r4], -r1             register postdecrement
12894: r4 r1 2 #LSL ]-   [r4], -r1, LSL #2     shifted postdecrement
12895: ' xyz >body [#]   xyz                   PC-relative addressing
12896: @end example
12897: 
12898: Register lists for load/store multiple instructions are started and
12899: terminated by using the words @code{@{} and @code{@}}
12900: respectivly.  Between braces, register names can be listed one by one,
12901: or register ranges can be formed by using the postfix operator
12902: @code{r-r}.  The @code{^} flag is not encoded in the register list
12903: operand, but instead directly encoded into the instruction mnemonic,
12904: ie. use @code{^ldm,} and @code{^stm,}.
12905: 
12906: Addressing modes for load/store multiple are not encoded as
12907: instruction suffixes, but instead specified after the register that
12908: supplies the address.  Use one of @code{DA}, @code{IA}, @code{DB},
12909: @code{IB}, @code{DA!}, @code{IA!}, @code{DB!} or @code{IB!}.
12910: 
12911: The following table gives some examples:
12912: 
12913: @example
12914: Gforth                           normal assembler
12915: @{ r0 r7 r8 @}  r4 ia  stm,        stmia    @{r0,r7,r8@}, r4
12916: @{ r0 r7 r8 @}  r4 db!  ldm,       ldmdb    @{r0,r7,r8@}, r4!
12917: @{ r0 r15 r-r @}  sp ia!  ^ldm,    ldmfd    @{r0-r15@}^, sp!
12918: @end example
12919: 
12920: Conditions for control structure words are specified in front of a
12921: word:
12922: 
12923: @example
12924: r1 r2 cmp,    \ compare r1 and r2
12925: eq if,        \ equal?
12926:    ...          \ code executed if r1 == r2
12927: then,
12928: @end example
12929: 
12930: Here is an example of a @code{code} word (assumes that the stack
12931: pointer is in @code{r9}, and that @code{r2} and @code{r3} can be
12932: clobbered):
12933: 
12934: @example
12935: code my+ ( n1 n2 --  n3 )
12936:    r9 IA!       @{ r2 r3 @} ldm,  \ pop r2 = n2, r3 = n1
12937:    r2   r3      r3        add,  \ r3 = n2+n1
12938:    r9 -4 #]!    r3        str,  \ push r3
12939:    next,
12940: end-code
12941: @end example
12942: 
12943: Look at @file{arch/arm/asm-example.fs} for more examples.
12944: 
12945: @node Other assemblers,  , ARM Assembler, Assembler and Code Words
12946: @subsection Other assemblers
12947: 
12948: If you want to contribute another assembler/disassembler, please contact
12949: us (@email{anton@@mips.complang.tuwien.ac.at}) to check if we have such
12950: an assembler already.  If you are writing them from scratch, please use
12951: a similar syntax style as the one we use (i.e., postfix, commas at the
12952: end of the instruction names, @pxref{Common Assembler}); make the output
12953: of the disassembler be valid input for the assembler, and keep the style
12954: similar to the style we used.
12955: 
12956: Hints on implementation: The most important part is to have a good test
12957: suite that contains all instructions.  Once you have that, the rest is
12958: easy.  For actual coding you can take a look at
12959: @file{arch/mips/disasm.fs} to get some ideas on how to use data for both
12960: the assembler and disassembler, avoiding redundancy and some potential
12961: bugs.  You can also look at that file (and @pxref{Advanced does> usage
12962: example}) to get ideas how to factor a disassembler.
12963: 
12964: Start with the disassembler, because it's easier to reuse data from the
12965: disassembler for the assembler than the other way round.
12966: 
12967: For the assembler, take a look at @file{arch/alpha/asm.fs}, which shows
12968: how simple it can be.
12969: 
12970: 
12971: 
12972: 
12973: @c -------------------------------------------------------------
12974: @node Threading Words, Passing Commands to the OS, Assembler and Code Words, Words
12975: @section Threading Words
12976: @cindex threading words
12977: 
12978: @cindex code address
12979: These words provide access to code addresses and other threading stuff
12980: in Gforth (and, possibly, other interpretive Forths). It more or less
12981: abstracts away the differences between direct and indirect threading
12982: (and, for direct threading, the machine dependences). However, at
12983: present this wordset is still incomplete. It is also pretty low-level;
12984: some day it will hopefully be made unnecessary by an internals wordset
12985: that abstracts implementation details away completely.
12986: 
12987: The terminology used here stems from indirect threaded Forth systems; in
12988: such a system, the XT of a word is represented by the CFA (code field
12989: address) of a word; the CFA points to a cell that contains the code
12990: address.  The code address is the address of some machine code that
12991: performs the run-time action of invoking the word (e.g., the
12992: @code{dovar:} routine pushes the address of the body of the word (a
12993: variable) on the stack
12994: ).
12995: 
12996: @cindex code address
12997: @cindex code field address
12998: In an indirect threaded Forth, you can get the code address of @i{name}
12999: with @code{' @i{name} @@}; in Gforth you can get it with @code{' @i{name}
13000: >code-address}, independent of the threading method.
13001: 
13002: doc-threading-method
13003: doc->code-address
13004: doc-code-address!
13005: 
13006: @cindex @code{does>}-handler
13007: @cindex @code{does>}-code
13008: For a word defined with @code{DOES>}, the code address usually points to
13009: a jump instruction (the @dfn{does-handler}) that jumps to the dodoes
13010: routine (in Gforth on some platforms, it can also point to the dodoes
13011: routine itself).  What you are typically interested in, though, is
13012: whether a word is a @code{DOES>}-defined word, and what Forth code it
13013: executes; @code{>does-code} tells you that.
13014: 
13015: doc->does-code
13016: 
13017: To create a @code{DOES>}-defined word with the following basic words,
13018: you have to set up a @code{DOES>}-handler with @code{does-handler!};
13019: @code{/does-handler} aus behind you have to place your executable Forth
13020: code.  Finally you have to create a word and modify its behaviour with
13021: @code{does-handler!}.
13022: 
13023: doc-does-code!
13024: doc-does-handler!
13025: doc-/does-handler
13026: 
13027: The code addresses produced by various defining words are produced by
13028: the following words:
13029: 
13030: doc-docol:
13031: doc-docon:
13032: doc-dovar:
13033: doc-douser:
13034: doc-dodefer:
13035: doc-dofield:
13036: 
13037: @cindex definer
13038: The following two words generalize @code{>code-address},
13039: @code{>does-code}, @code{code-address!}, and @code{does-code!}:
13040: 
13041: doc->definer
13042: doc-definer!
13043: 
13044: @c -------------------------------------------------------------
13045: @node Passing Commands to the OS, Keeping track of Time, Threading Words, Words
13046: @section Passing Commands to the Operating System
13047: @cindex operating system - passing commands
13048: @cindex shell commands
13049: 
13050: Gforth allows you to pass an arbitrary string to the host operating
13051: system shell (if such a thing exists) for execution.
13052: 
13053: doc-sh
13054: doc-system
13055: doc-$?
13056: doc-getenv
13057: 
13058: @c -------------------------------------------------------------
13059: @node Keeping track of Time, Miscellaneous Words, Passing Commands to the OS, Words
13060: @section Keeping track of Time
13061: @cindex time-related words
13062: 
13063: doc-ms
13064: doc-time&date
13065: doc-utime
13066: doc-cputime
13067: 
13068: 
13069: @c -------------------------------------------------------------
13070: @node Miscellaneous Words,  , Keeping track of Time, Words
13071: @section Miscellaneous Words
13072: @cindex miscellaneous words
13073: 
13074: @comment TODO find homes for these
13075: 
13076: These section lists the ANS Forth words that are not documented
13077: elsewhere in this manual. Ultimately, they all need proper homes.
13078: 
13079: doc-quit
13080: 
13081: The following ANS Forth words are not currently supported by Gforth 
13082: (@pxref{ANS conformance}):
13083: 
13084: @code{EDITOR} 
13085: @code{EMIT?} 
13086: @code{FORGET} 
13087: 
13088: @c ******************************************************************
13089: @node Error messages, Tools, Words, Top
13090: @chapter Error messages
13091: @cindex error messages
13092: @cindex backtrace
13093: 
13094: A typical Gforth error message looks like this:
13095: 
13096: @example
13097: in file included from \evaluated string/:-1
13098: in file included from ./yyy.fs:1
13099: ./xxx.fs:4: Invalid memory address
13100: >>>bar<<<
13101: Backtrace:
13102: $400E664C @@
13103: $400E6664 foo
13104: @end example
13105: 
13106: The message identifying the error is @code{Invalid memory address}.  The
13107: error happened when text-interpreting line 4 of the file
13108: @file{./xxx.fs}. This line is given (it contains @code{bar}), and the
13109: word on the line where the error happened, is pointed out (with
13110: @code{>>>} and @code{<<<}).
13111: 
13112: The file containing the error was included in line 1 of @file{./yyy.fs},
13113: and @file{yyy.fs} was included from a non-file (in this case, by giving
13114: @file{yyy.fs} as command-line parameter to Gforth).
13115: 
13116: At the end of the error message you find a return stack dump that can be
13117: interpreted as a backtrace (possibly empty). On top you find the top of
13118: the return stack when the @code{throw} happened, and at the bottom you
13119: find the return stack entry just above the return stack of the topmost
13120: text interpreter.
13121: 
13122: To the right of most return stack entries you see a guess for the word
13123: that pushed that return stack entry as its return address. This gives a
13124: backtrace. In our case we see that @code{bar} called @code{foo}, and
13125: @code{foo} called @code{@@} (and @code{@@} had an @emph{Invalid memory
13126: address} exception).
13127: 
13128: Note that the backtrace is not perfect: We don't know which return stack
13129: entries are return addresses (so we may get false positives); and in
13130: some cases (e.g., for @code{abort"}) we cannot determine from the return
13131: address the word that pushed the return address, so for some return
13132: addresses you see no names in the return stack dump.
13133: 
13134: @cindex @code{catch} and backtraces
13135: The return stack dump represents the return stack at the time when a
13136: specific @code{throw} was executed.  In programs that make use of
13137: @code{catch}, it is not necessarily clear which @code{throw} should be
13138: used for the return stack dump (e.g., consider one @code{throw} that
13139: indicates an error, which is caught, and during recovery another error
13140: happens; which @code{throw} should be used for the stack dump?).
13141: Gforth presents the return stack dump for the first @code{throw} after
13142: the last executed (not returned-to) @code{catch} or @code{nothrow};
13143: this works well in the usual case. To get the right backtrace, you
13144: usually want to insert @code{nothrow} or @code{['] false catch drop}
13145: after a @code{catch} if the error is not rethrown.
13146: 
13147: @cindex @code{gforth-fast} and backtraces
13148: @cindex @code{gforth-fast}, difference from @code{gforth}
13149: @cindex backtraces with @code{gforth-fast}
13150: @cindex return stack dump with @code{gforth-fast}
13151: @code{Gforth} is able to do a return stack dump for throws generated
13152: from primitives (e.g., invalid memory address, stack empty etc.);
13153: @code{gforth-fast} is only able to do a return stack dump from a
13154: directly called @code{throw} (including @code{abort} etc.).  Given an
13155: exception caused by a primitive in @code{gforth-fast}, you will
13156: typically see no return stack dump at all; however, if the exception is
13157: caught by @code{catch} (e.g., for restoring some state), and then
13158: @code{throw}n again, the return stack dump will be for the first such
13159: @code{throw}.
13160: 
13161: @c ******************************************************************
13162: @node Tools, ANS conformance, Error messages, Top
13163: @chapter Tools
13164: 
13165: @menu
13166: * ANS Report::                  Report the words used, sorted by wordset.
13167: * Stack depth changes::         Where does this stack item come from?
13168: @end menu
13169: 
13170: See also @ref{Emacs and Gforth}.
13171: 
13172: @node ANS Report, Stack depth changes, Tools, Tools
13173: @section @file{ans-report.fs}: Report the words used, sorted by wordset
13174: @cindex @file{ans-report.fs}
13175: @cindex report the words used in your program
13176: @cindex words used in your program
13177: 
13178: If you want to label a Forth program as ANS Forth Program, you must
13179: document which wordsets the program uses; for extension wordsets, it is
13180: helpful to list the words the program requires from these wordsets
13181: (because Forth systems are allowed to provide only some words of them).
13182: 
13183: The @file{ans-report.fs} tool makes it easy for you to determine which
13184: words from which wordset and which non-ANS words your application
13185: uses. You simply have to include @file{ans-report.fs} before loading the
13186: program you want to check. After loading your program, you can get the
13187: report with @code{print-ans-report}. A typical use is to run this as
13188: batch job like this:
13189: @example
13190: gforth ans-report.fs myprog.fs -e "print-ans-report bye"
13191: @end example
13192: 
13193: The output looks like this (for @file{compat/control.fs}):
13194: @example
13195: The program uses the following words
13196: from CORE :
13197: : POSTPONE THEN ; immediate ?dup IF 0= 
13198: from BLOCK-EXT :
13199: \ 
13200: from FILE :
13201: ( 
13202: @end example
13203: 
13204: @subsection Caveats
13205: 
13206: Note that @file{ans-report.fs} just checks which words are used, not whether
13207: they are used in an ANS Forth conforming way!
13208: 
13209: Some words are defined in several wordsets in the
13210: standard. @file{ans-report.fs} reports them for only one of the
13211: wordsets, and not necessarily the one you expect. It depends on usage
13212: which wordset is the right one to specify. E.g., if you only use the
13213: compilation semantics of @code{S"}, it is a Core word; if you also use
13214: its interpretation semantics, it is a File word.
13215: 
13216: 
13217: @node Stack depth changes,  , ANS Report, Tools
13218: @section Stack depth changes during interpretation
13219: @cindex @file{depth-changes.fs}
13220: @cindex depth changes during interpretation
13221: @cindex stack depth changes during interpretation
13222: @cindex items on the stack after interpretation
13223: 
13224: Sometimes you notice that, after loading a file, there are items left
13225: on the stack.  The tool @file{depth-changes.fs} helps you find out
13226: quickly where in the file these stack items are coming from.
13227: 
13228: The simplest way of using @file{depth-changes.fs} is to include it
13229: before the file(s) you want to check, e.g.:
13230: 
13231: @example
13232: gforth depth-changes.fs my-file.fs
13233: @end example
13234: 
13235: This will compare the stack depths of the data and FP stack at every
13236: empty line (in interpretation state) against these depths at the last
13237: empty line (in interpretation state).  If the depths are not equal,
13238: the position in the file and the stack contents are printed with
13239: @code{~~} (@pxref{Debugging}).  This indicates that a stack depth
13240: change has occured in the paragraph of non-empty lines before the
13241: indicated line.  It is a good idea to leave an empty line at the end
13242: of the file, so the last paragraph is checked, too.
13243: 
13244: Checking only at empty lines usually works well, but sometimes you
13245: have big blocks of non-empty lines (e.g., when building a big table),
13246: and you want to know where in this block the stack depth changed.  You
13247: can check all interpreted lines with
13248: 
13249: @example
13250: gforth depth-changes.fs -e "' all-lines is depth-changes-filter" my-file.fs
13251: @end example
13252: 
13253: This checks the stack depth at every end-of-line.  So the depth change
13254: occured in the line reported by the @code{~~} (not in the line
13255: before).
13256: 
13257: Note that, while this offers better accuracy in indicating where the
13258: stack depth changes, it will often report many intentional stack depth
13259: changes (e.g., when an interpreted computation stretches across
13260: several lines).  You can suppress the checking of some lines by
13261: putting backslashes at the end of these lines (not followed by white
13262: space), and using
13263: 
13264: @example
13265: gforth depth-changes.fs -e "' most-lines is depth-changes-filter" my-file.fs
13266: @end example
13267: 
13268: @c ******************************************************************
13269: @node ANS conformance, Standard vs Extensions, Tools, Top
13270: @chapter ANS conformance
13271: @cindex ANS conformance of Gforth
13272: 
13273: To the best of our knowledge, Gforth is an
13274: 
13275: ANS Forth System
13276: @itemize @bullet
13277: @item providing the Core Extensions word set
13278: @item providing the Block word set
13279: @item providing the Block Extensions word set
13280: @item providing the Double-Number word set
13281: @item providing the Double-Number Extensions word set
13282: @item providing the Exception word set
13283: @item providing the Exception Extensions word set
13284: @item providing the Facility word set
13285: @item providing @code{EKEY}, @code{EKEY>CHAR}, @code{EKEY?}, @code{MS} and @code{TIME&DATE} from the Facility Extensions word set
13286: @item providing the File Access word set
13287: @item providing the File Access Extensions word set
13288: @item providing the Floating-Point word set
13289: @item providing the Floating-Point Extensions word set
13290: @item providing the Locals word set
13291: @item providing the Locals Extensions word set
13292: @item providing the Memory-Allocation word set
13293: @item providing the Memory-Allocation Extensions word set (that one's easy)
13294: @item providing the Programming-Tools word set
13295: @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
13296: @item providing the Search-Order word set
13297: @item providing the Search-Order Extensions word set
13298: @item providing the String word set
13299: @item providing the String Extensions word set (another easy one)
13300: @end itemize
13301: 
13302: Gforth has the following environmental restrictions:
13303: 
13304: @cindex environmental restrictions
13305: @itemize @bullet
13306: @item
13307: While processing the OS command line, if an exception is not caught,
13308: Gforth exits with a non-zero exit code instyead of performing QUIT.
13309: 
13310: @item
13311: When an @code{throw} is performed after a @code{query}, Gforth does not
13312: allways restore the input source specification in effect at the
13313: corresponding catch.
13314: 
13315: @end itemize
13316: 
13317: 
13318: @cindex system documentation
13319: In addition, ANS Forth systems are required to document certain
13320: implementation choices. This chapter tries to meet these
13321: requirements. In many cases it gives a way to ask the system for the
13322: information instead of providing the information directly, in
13323: particular, if the information depends on the processor, the operating
13324: system or the installation options chosen, or if they are likely to
13325: change during the maintenance of Gforth.
13326: 
13327: @comment The framework for the rest has been taken from pfe.
13328: 
13329: @menu
13330: * The Core Words::              
13331: * The optional Block word set::  
13332: * The optional Double Number word set::  
13333: * The optional Exception word set::  
13334: * The optional Facility word set::  
13335: * The optional File-Access word set::  
13336: * The optional Floating-Point word set::  
13337: * The optional Locals word set::  
13338: * The optional Memory-Allocation word set::  
13339: * The optional Programming-Tools word set::  
13340: * The optional Search-Order word set::  
13341: @end menu
13342: 
13343: 
13344: @c =====================================================================
13345: @node The Core Words, The optional Block word set, ANS conformance, ANS conformance
13346: @comment  node-name,  next,  previous,  up
13347: @section The Core Words
13348: @c =====================================================================
13349: @cindex core words, system documentation
13350: @cindex system documentation, core words
13351: 
13352: @menu
13353: * core-idef::                   Implementation Defined Options                   
13354: * core-ambcond::                Ambiguous Conditions                
13355: * core-other::                  Other System Documentation                  
13356: @end menu
13357: 
13358: @c ---------------------------------------------------------------------
13359: @node core-idef, core-ambcond, The Core Words, The Core Words
13360: @subsection Implementation Defined Options
13361: @c ---------------------------------------------------------------------
13362: @cindex core words, implementation-defined options
13363: @cindex implementation-defined options, core words
13364: 
13365: 
13366: @table @i
13367: @item (Cell) aligned addresses:
13368: @cindex cell-aligned addresses
13369: @cindex aligned addresses
13370: processor-dependent. Gforth's alignment words perform natural alignment
13371: (e.g., an address aligned for a datum of size 8 is divisible by
13372: 8). Unaligned accesses usually result in a @code{-23 THROW}.
13373: 
13374: @item @code{EMIT} and non-graphic characters:
13375: @cindex @code{EMIT} and non-graphic characters
13376: @cindex non-graphic characters and @code{EMIT}
13377: The character is output using the C library function (actually, macro)
13378: @code{putc}.
13379: 
13380: @item character editing of @code{ACCEPT} and @code{EXPECT}:
13381: @cindex character editing of @code{ACCEPT} and @code{EXPECT}
13382: @cindex editing in @code{ACCEPT} and @code{EXPECT}
13383: @cindex @code{ACCEPT}, editing
13384: @cindex @code{EXPECT}, editing
13385: This is modeled on the GNU readline library (@pxref{Readline
13386: Interaction, , Command Line Editing, readline, The GNU Readline
13387: Library}) with Emacs-like key bindings. @kbd{Tab} deviates a little by
13388: producing a full word completion every time you type it (instead of
13389: producing the common prefix of all completions). @xref{Command-line editing}.
13390: 
13391: @item character set:
13392: @cindex character set
13393: The character set of your computer and display device. Gforth is
13394: 8-bit-clean (but some other component in your system may make trouble).
13395: 
13396: @item Character-aligned address requirements:
13397: @cindex character-aligned address requirements
13398: installation-dependent. Currently a character is represented by a C
13399: @code{unsigned char}; in the future we might switch to @code{wchar_t}
13400: (Comments on that requested).
13401: 
13402: @item character-set extensions and matching of names:
13403: @cindex character-set extensions and matching of names
13404: @cindex case-sensitivity for name lookup
13405: @cindex name lookup, case-sensitivity
13406: @cindex locale and case-sensitivity
13407: Any character except the ASCII NUL character can be used in a
13408: name. Matching is case-insensitive (except in @code{TABLE}s). The
13409: matching is performed using the C library function @code{strncasecmp}, whose
13410: function is probably influenced by the locale. E.g., the @code{C} locale
13411: does not know about accents and umlauts, so they are matched
13412: case-sensitively in that locale. For portability reasons it is best to
13413: write programs such that they work in the @code{C} locale. Then one can
13414: use libraries written by a Polish programmer (who might use words
13415: containing ISO Latin-2 encoded characters) and by a French programmer
13416: (ISO Latin-1) in the same program (of course, @code{WORDS} will produce
13417: funny results for some of the words (which ones, depends on the font you
13418: are using)). Also, the locale you prefer may not be available in other
13419: operating systems. Hopefully, Unicode will solve these problems one day.
13420: 
13421: @item conditions under which control characters match a space delimiter:
13422: @cindex space delimiters
13423: @cindex control characters as delimiters
13424: If @code{word} is called with the space character as a delimiter, all
13425: white-space characters (as identified by the C macro @code{isspace()})
13426: are delimiters. @code{Parse}, on the other hand, treats space like other
13427: delimiters.  @code{Parse-name}, which is used by the outer
13428: interpreter (aka text interpreter) by default, treats all white-space
13429: characters as delimiters.
13430: 
13431: @item format of the control-flow stack:
13432: @cindex control-flow stack, format
13433: The data stack is used as control-flow stack. The size of a control-flow
13434: stack item in cells is given by the constant @code{cs-item-size}. At the
13435: time of this writing, an item consists of a (pointer to a) locals list
13436: (third), an address in the code (second), and a tag for identifying the
13437: item (TOS). The following tags are used: @code{defstart},
13438: @code{live-orig}, @code{dead-orig}, @code{dest}, @code{do-dest},
13439: @code{scopestart}.
13440: 
13441: @item conversion of digits > 35
13442: @cindex digits > 35
13443: The characters @code{[\]^_'} are the digits with the decimal value
13444: 36@minus{}41. There is no way to input many of the larger digits.
13445: 
13446: @item display after input terminates in @code{ACCEPT} and @code{EXPECT}:
13447: @cindex @code{EXPECT}, display after end of input
13448: @cindex @code{ACCEPT}, display after end of input
13449: The cursor is moved to the end of the entered string. If the input is
13450: terminated using the @kbd{Return} key, a space is typed.
13451: 
13452: @item exception abort sequence of @code{ABORT"}:
13453: @cindex exception abort sequence of @code{ABORT"}
13454: @cindex @code{ABORT"}, exception abort sequence
13455: The error string is stored into the variable @code{"error} and a
13456: @code{-2 throw} is performed.
13457: 
13458: @item input line terminator:
13459: @cindex input line terminator
13460: @cindex line terminator on input
13461: @cindex newline character on input
13462: For interactive input, @kbd{C-m} (CR) and @kbd{C-j} (LF) terminate
13463: lines. One of these characters is typically produced when you type the
13464: @kbd{Enter} or @kbd{Return} key.
13465: 
13466: @item maximum size of a counted string:
13467: @cindex maximum size of a counted string
13468: @cindex counted string, maximum size
13469: @code{s" /counted-string" environment? drop .}. Currently 255 characters
13470: on all platforms, but this may change.
13471: 
13472: @item maximum size of a parsed string:
13473: @cindex maximum size of a parsed string
13474: @cindex parsed string, maximum size
13475: Given by the constant @code{/line}. Currently 255 characters.
13476: 
13477: @item maximum size of a definition name, in characters:
13478: @cindex maximum size of a definition name, in characters
13479: @cindex name, maximum length
13480: MAXU/8
13481: 
13482: @item maximum string length for @code{ENVIRONMENT?}, in characters:
13483: @cindex maximum string length for @code{ENVIRONMENT?}, in characters
13484: @cindex @code{ENVIRONMENT?} string length, maximum
13485: MAXU/8
13486: 
13487: @item method of selecting the user input device:
13488: @cindex user input device, method of selecting
13489: The user input device is the standard input. There is currently no way to
13490: change it from within Gforth. However, the input can typically be
13491: redirected in the command line that starts Gforth.
13492: 
13493: @item method of selecting the user output device:
13494: @cindex user output device, method of selecting
13495: @code{EMIT} and @code{TYPE} output to the file-id stored in the value
13496: @code{outfile-id} (@code{stdout} by default). Gforth uses unbuffered
13497: output when the user output device is a terminal, otherwise the output
13498: is buffered.
13499: 
13500: @item methods of dictionary compilation:
13501: What are we expected to document here?
13502: 
13503: @item number of bits in one address unit:
13504: @cindex number of bits in one address unit
13505: @cindex address unit, size in bits
13506: @code{s" address-units-bits" environment? drop .}. 8 in all current
13507: platforms.
13508: 
13509: @item number representation and arithmetic:
13510: @cindex number representation and arithmetic
13511: Processor-dependent. Binary two's complement on all current platforms.
13512: 
13513: @item ranges for integer types:
13514: @cindex ranges for integer types
13515: @cindex integer types, ranges
13516: Installation-dependent. Make environmental queries for @code{MAX-N},
13517: @code{MAX-U}, @code{MAX-D} and @code{MAX-UD}. The lower bounds for
13518: unsigned (and positive) types is 0. The lower bound for signed types on
13519: two's complement and one's complement machines machines can be computed
13520: by adding 1 to the upper bound.
13521: 
13522: @item read-only data space regions:
13523: @cindex read-only data space regions
13524: @cindex data-space, read-only regions
13525: The whole Forth data space is writable.
13526: 
13527: @item size of buffer at @code{WORD}:
13528: @cindex size of buffer at @code{WORD}
13529: @cindex @code{WORD} buffer size
13530: @code{PAD HERE - .}. 104 characters on 32-bit machines. The buffer is
13531: shared with the pictured numeric output string. If overwriting
13532: @code{PAD} is acceptable, it is as large as the remaining dictionary
13533: space, although only as much can be sensibly used as fits in a counted
13534: string.
13535: 
13536: @item size of one cell in address units:
13537: @cindex cell size
13538: @code{1 cells .}.
13539: 
13540: @item size of one character in address units:
13541: @cindex char size
13542: @code{1 chars .}. 1 on all current platforms.
13543: 
13544: @item size of the keyboard terminal buffer:
13545: @cindex size of the keyboard terminal buffer
13546: @cindex terminal buffer, size
13547: Varies. You can determine the size at a specific time using @code{lp@@
13548: tib - .}. It is shared with the locals stack and TIBs of files that
13549: include the current file. You can change the amount of space for TIBs
13550: and locals stack at Gforth startup with the command line option
13551: @code{-l}.
13552: 
13553: @item size of the pictured numeric output buffer:
13554: @cindex size of the pictured numeric output buffer
13555: @cindex pictured numeric output buffer, size
13556: @code{PAD HERE - .}. 104 characters on 32-bit machines. The buffer is
13557: shared with @code{WORD}.
13558: 
13559: @item size of the scratch area returned by @code{PAD}:
13560: @cindex size of the scratch area returned by @code{PAD}
13561: @cindex @code{PAD} size
13562: The remainder of dictionary space. @code{unused pad here - - .}.
13563: 
13564: @item system case-sensitivity characteristics:
13565: @cindex case-sensitivity characteristics
13566: Dictionary searches are case-insensitive (except in
13567: @code{TABLE}s). However, as explained above under @i{character-set
13568: extensions}, the matching for non-ASCII characters is determined by the
13569: locale you are using. In the default @code{C} locale all non-ASCII
13570: characters are matched case-sensitively.
13571: 
13572: @item system prompt:
13573: @cindex system prompt
13574: @cindex prompt
13575: @code{ ok} in interpret state, @code{ compiled} in compile state.
13576: 
13577: @item division rounding:
13578: @cindex division rounding
13579: The ordinary division words @code{/ mod /mod */ */mod} perform floored
13580: division (with the default installation of Gforth).  You can check
13581: this with @code{s" floored" environment? drop .}.  If you write
13582: programs that need a specific division rounding, best use
13583: @code{fm/mod} or @code{sm/rem} for portability.
13584: 
13585: @item values of @code{STATE} when true:
13586: @cindex @code{STATE} values
13587: -1.
13588: 
13589: @item values returned after arithmetic overflow:
13590: On two's complement machines, arithmetic is performed modulo
13591: 2**bits-per-cell for single arithmetic and 4**bits-per-cell for double
13592: arithmetic (with appropriate mapping for signed types). Division by
13593: zero typically results in a @code{-55 throw} (Floating-point
13594: unidentified fault) or @code{-10 throw} (divide by zero).  Integer
13595: division overflow can result in these throws, or in @code{-11 throw};
13596: in @code{gforth-fast} division overflow and divide by zero may also
13597: result in returning bogus results without producing an exception.
13598: 
13599: @item whether the current definition can be found after @t{DOES>}:
13600: @cindex @t{DOES>}, visibility of current definition
13601: No.
13602: 
13603: @end table
13604: 
13605: @c ---------------------------------------------------------------------
13606: @node core-ambcond, core-other, core-idef, The Core Words
13607: @subsection Ambiguous conditions
13608: @c ---------------------------------------------------------------------
13609: @cindex core words, ambiguous conditions
13610: @cindex ambiguous conditions, core words
13611: 
13612: @table @i
13613: 
13614: @item a name is neither a word nor a number:
13615: @cindex name not found
13616: @cindex undefined word
13617: @code{-13 throw} (Undefined word).
13618: 
13619: @item a definition name exceeds the maximum length allowed:
13620: @cindex word name too long
13621: @code{-19 throw} (Word name too long)
13622: 
13623: @item addressing a region not inside the various data spaces of the forth system:
13624: @cindex Invalid memory address
13625: The stacks, code space and header space are accessible. Machine code space is
13626: typically readable. Accessing other addresses gives results dependent on
13627: the operating system. On decent systems: @code{-9 throw} (Invalid memory
13628: address).
13629: 
13630: @item argument type incompatible with parameter:
13631: @cindex argument type mismatch
13632: This is usually not caught. Some words perform checks, e.g., the control
13633: flow words, and issue a @code{ABORT"} or @code{-12 THROW} (Argument type
13634: mismatch).
13635: 
13636: @item attempting to obtain the execution token of a word with undefined execution semantics:
13637: @cindex Interpreting a compile-only word, for @code{'} etc.
13638: @cindex execution token of words with undefined execution semantics
13639: @code{-14 throw} (Interpreting a compile-only word). In some cases, you
13640: get an execution token for @code{compile-only-error} (which performs a
13641: @code{-14 throw} when executed).
13642: 
13643: @item dividing by zero:
13644: @cindex dividing by zero
13645: @cindex floating point unidentified fault, integer division
13646: On some platforms, this produces a @code{-10 throw} (Division by
13647: zero); on other systems, this typically results in a @code{-55 throw}
13648: (Floating-point unidentified fault).
13649: 
13650: @item insufficient data stack or return stack space:
13651: @cindex insufficient data stack or return stack space
13652: @cindex stack overflow
13653: @cindex address alignment exception, stack overflow
13654: @cindex Invalid memory address, stack overflow
13655: Depending on the operating system, the installation, and the invocation
13656: of Gforth, this is either checked by the memory management hardware, or
13657: it is not checked. If it is checked, you typically get a @code{-3 throw}
13658: (Stack overflow), @code{-5 throw} (Return stack overflow), or @code{-9
13659: throw} (Invalid memory address) (depending on the platform and how you
13660: achieved the overflow) as soon as the overflow happens. If it is not
13661: checked, overflows typically result in mysterious illegal memory
13662: accesses, producing @code{-9 throw} (Invalid memory address) or
13663: @code{-23 throw} (Address alignment exception); they might also destroy
13664: the internal data structure of @code{ALLOCATE} and friends, resulting in
13665: various errors in these words.
13666: 
13667: @item insufficient space for loop control parameters:
13668: @cindex insufficient space for loop control parameters
13669: Like other return stack overflows.
13670: 
13671: @item insufficient space in the dictionary:
13672: @cindex insufficient space in the dictionary
13673: @cindex dictionary overflow
13674: If you try to allot (either directly with @code{allot}, or indirectly
13675: with @code{,}, @code{create} etc.) more memory than available in the
13676: dictionary, you get a @code{-8 throw} (Dictionary overflow). If you try
13677: to access memory beyond the end of the dictionary, the results are
13678: similar to stack overflows.
13679: 
13680: @item interpreting a word with undefined interpretation semantics:
13681: @cindex interpreting a word with undefined interpretation semantics
13682: @cindex Interpreting a compile-only word
13683: For some words, we have defined interpretation semantics. For the
13684: others: @code{-14 throw} (Interpreting a compile-only word).
13685: 
13686: @item modifying the contents of the input buffer or a string literal:
13687: @cindex modifying the contents of the input buffer or a string literal
13688: These are located in writable memory and can be modified.
13689: 
13690: @item overflow of the pictured numeric output string:
13691: @cindex overflow of the pictured numeric output string
13692: @cindex pictured numeric output string, overflow
13693: @code{-17 throw} (Pictured numeric ouput string overflow).
13694: 
13695: @item parsed string overflow:
13696: @cindex parsed string overflow
13697: @code{PARSE} cannot overflow. @code{WORD} does not check for overflow.
13698: 
13699: @item producing a result out of range:
13700: @cindex result out of range
13701: On two's complement machines, arithmetic is performed modulo
13702: 2**bits-per-cell for single arithmetic and 4**bits-per-cell for double
13703: arithmetic (with appropriate mapping for signed types). Division by
13704: zero typically results in a @code{-10 throw} (divide by zero) or
13705: @code{-55 throw} (floating point unidentified fault). Overflow on
13706: division may result in these errors or in @code{-11 throw} (result out
13707: of range).  @code{Gforth-fast} may silently produce bogus results on
13708: division overflow or division by zero.  @code{Convert} and
13709: @code{>number} currently overflow silently.
13710: 
13711: @item reading from an empty data or return stack:
13712: @cindex stack empty
13713: @cindex stack underflow
13714: @cindex return stack underflow
13715: The data stack is checked by the outer (aka text) interpreter after
13716: every word executed. If it has underflowed, a @code{-4 throw} (Stack
13717: underflow) is performed. Apart from that, stacks may be checked or not,
13718: depending on operating system, installation, and invocation. If they are
13719: caught by a check, they typically result in @code{-4 throw} (Stack
13720: underflow), @code{-6 throw} (Return stack underflow) or @code{-9 throw}
13721: (Invalid memory address), depending on the platform and which stack
13722: underflows and by how much. Note that even if the system uses checking
13723: (through the MMU), your program may have to underflow by a significant
13724: number of stack items to trigger the reaction (the reason for this is
13725: that the MMU, and therefore the checking, works with a page-size
13726: granularity).  If there is no checking, the symptoms resulting from an
13727: underflow are similar to those from an overflow.  Unbalanced return
13728: stack errors can result in a variety of symptoms, including @code{-9 throw}
13729: (Invalid memory address) and Illegal Instruction (typically @code{-260
13730: throw}).
13731: 
13732: @item unexpected end of the input buffer, resulting in an attempt to use a zero-length string as a name:
13733: @cindex unexpected end of the input buffer
13734: @cindex zero-length string as a name
13735: @cindex Attempt to use zero-length string as a name
13736: @code{Create} and its descendants perform a @code{-16 throw} (Attempt to
13737: use zero-length string as a name). Words like @code{'} probably will not
13738: find what they search. Note that it is possible to create zero-length
13739: names with @code{nextname} (should it not?).
13740: 
13741: @item @code{>IN} greater than input buffer:
13742: @cindex @code{>IN} greater than input buffer
13743: The next invocation of a parsing word returns a string with length 0.
13744: 
13745: @item @code{RECURSE} appears after @code{DOES>}:
13746: @cindex @code{RECURSE} appears after @code{DOES>}
13747: Compiles a recursive call to the defining word, not to the defined word.
13748: 
13749: @item argument input source different than current input source for @code{RESTORE-INPUT}:
13750: @cindex argument input source different than current input source for @code{RESTORE-INPUT}
13751: @cindex argument type mismatch, @code{RESTORE-INPUT}
13752: @cindex @code{RESTORE-INPUT}, Argument type mismatch
13753: @code{-12 THROW}. Note that, once an input file is closed (e.g., because
13754: the end of the file was reached), its source-id may be
13755: reused. Therefore, restoring an input source specification referencing a
13756: closed file may lead to unpredictable results instead of a @code{-12
13757: THROW}.
13758: 
13759: In the future, Gforth may be able to restore input source specifications
13760: from other than the current input source.
13761: 
13762: @item data space containing definitions gets de-allocated:
13763: @cindex data space containing definitions gets de-allocated
13764: Deallocation with @code{allot} is not checked. This typically results in
13765: memory access faults or execution of illegal instructions.
13766: 
13767: @item data space read/write with incorrect alignment:
13768: @cindex data space read/write with incorrect alignment
13769: @cindex alignment faults
13770: @cindex address alignment exception
13771: Processor-dependent. Typically results in a @code{-23 throw} (Address
13772: alignment exception). Under Linux-Intel on a 486 or later processor with
13773: alignment turned on, incorrect alignment results in a @code{-9 throw}
13774: (Invalid memory address). There are reportedly some processors with
13775: alignment restrictions that do not report violations.
13776: 
13777: @item data space pointer not properly aligned, @code{,}, @code{C,}:
13778: @cindex data space pointer not properly aligned, @code{,}, @code{C,}
13779: Like other alignment errors.
13780: 
13781: @item less than u+2 stack items (@code{PICK} and @code{ROLL}):
13782: Like other stack underflows.
13783: 
13784: @item loop control parameters not available:
13785: @cindex loop control parameters not available
13786: Not checked. The counted loop words simply assume that the top of return
13787: stack items are loop control parameters and behave accordingly.
13788: 
13789: @item most recent definition does not have a name (@code{IMMEDIATE}):
13790: @cindex most recent definition does not have a name (@code{IMMEDIATE})
13791: @cindex last word was headerless
13792: @code{abort" last word was headerless"}.
13793: 
13794: @item name not defined by @code{VALUE} used by @code{TO}:
13795: @cindex name not defined by @code{VALUE} used by @code{TO}
13796: @cindex @code{TO} on non-@code{VALUE}s
13797: @cindex Invalid name argument, @code{TO}
13798: @code{-32 throw} (Invalid name argument) (unless name is a local or was
13799: defined by @code{CONSTANT}; in the latter case it just changes the constant).
13800: 
13801: @item name not found (@code{'}, @code{POSTPONE}, @code{[']}, @code{[COMPILE]}):
13802: @cindex name not found (@code{'}, @code{POSTPONE}, @code{[']}, @code{[COMPILE]})
13803: @cindex undefined word, @code{'}, @code{POSTPONE}, @code{[']}, @code{[COMPILE]}
13804: @code{-13 throw} (Undefined word)
13805: 
13806: @item parameters are not of the same type (@code{DO}, @code{?DO}, @code{WITHIN}):
13807: @cindex parameters are not of the same type (@code{DO}, @code{?DO}, @code{WITHIN})
13808: Gforth behaves as if they were of the same type. I.e., you can predict
13809: the behaviour by interpreting all parameters as, e.g., signed.
13810: 
13811: @item @code{POSTPONE} or @code{[COMPILE]} applied to @code{TO}:
13812: @cindex @code{POSTPONE} or @code{[COMPILE]} applied to @code{TO}
13813: Assume @code{: X POSTPONE TO ; IMMEDIATE}. @code{X} performs the
13814: compilation semantics of @code{TO}.
13815: 
13816: @item String longer than a counted string returned by @code{WORD}:
13817: @cindex string longer than a counted string returned by @code{WORD}
13818: @cindex @code{WORD}, string overflow
13819: Not checked. The string will be ok, but the count will, of course,
13820: contain only the least significant bits of the length.
13821: 
13822: @item u greater than or equal to the number of bits in a cell (@code{LSHIFT}, @code{RSHIFT}):
13823: @cindex @code{LSHIFT}, large shift counts
13824: @cindex @code{RSHIFT}, large shift counts
13825: Processor-dependent. Typical behaviours are returning 0 and using only
13826: the low bits of the shift count.
13827: 
13828: @item word not defined via @code{CREATE}:
13829: @cindex @code{>BODY} of non-@code{CREATE}d words
13830: @code{>BODY} produces the PFA of the word no matter how it was defined.
13831: 
13832: @cindex @code{DOES>} of non-@code{CREATE}d words
13833: @code{DOES>} changes the execution semantics of the last defined word no
13834: matter how it was defined. E.g., @code{CONSTANT DOES>} is equivalent to
13835: @code{CREATE , DOES>}.
13836: 
13837: @item words improperly used outside @code{<#} and @code{#>}:
13838: Not checked. As usual, you can expect memory faults.
13839: 
13840: @end table
13841: 
13842: 
13843: @c ---------------------------------------------------------------------
13844: @node core-other,  , core-ambcond, The Core Words
13845: @subsection Other system documentation
13846: @c ---------------------------------------------------------------------
13847: @cindex other system documentation, core words
13848: @cindex core words, other system documentation
13849: 
13850: @table @i
13851: @item nonstandard words using @code{PAD}:
13852: @cindex @code{PAD} use by nonstandard words
13853: None.
13854: 
13855: @item operator's terminal facilities available:
13856: @cindex operator's terminal facilities available
13857: After processing the OS's command line, Gforth goes into interactive mode,
13858: and you can give commands to Gforth interactively. The actual facilities
13859: available depend on how you invoke Gforth.
13860: 
13861: @item program data space available:
13862: @cindex program data space available
13863: @cindex data space available
13864: @code{UNUSED .} gives the remaining dictionary space. The total
13865: dictionary space can be specified with the @code{-m} switch
13866: (@pxref{Invoking Gforth}) when Gforth starts up.
13867: 
13868: @item return stack space available:
13869: @cindex return stack space available
13870: You can compute the total return stack space in cells with
13871: @code{s" RETURN-STACK-CELLS" environment? drop .}. You can specify it at
13872: startup time with the @code{-r} switch (@pxref{Invoking Gforth}).
13873: 
13874: @item stack space available:
13875: @cindex stack space available
13876: You can compute the total data stack space in cells with
13877: @code{s" STACK-CELLS" environment? drop .}. You can specify it at
13878: startup time with the @code{-d} switch (@pxref{Invoking Gforth}).
13879: 
13880: @item system dictionary space required, in address units:
13881: @cindex system dictionary space required, in address units
13882: Type @code{here forthstart - .} after startup. At the time of this
13883: writing, this gives 80080 (bytes) on a 32-bit system.
13884: @end table
13885: 
13886: 
13887: @c =====================================================================
13888: @node The optional Block word set, The optional Double Number word set, The Core Words, ANS conformance
13889: @section The optional Block word set
13890: @c =====================================================================
13891: @cindex system documentation, block words
13892: @cindex block words, system documentation
13893: 
13894: @menu
13895: * block-idef::                  Implementation Defined Options
13896: * block-ambcond::               Ambiguous Conditions               
13897: * block-other::                 Other System Documentation                 
13898: @end menu
13899: 
13900: 
13901: @c ---------------------------------------------------------------------
13902: @node block-idef, block-ambcond, The optional Block word set, The optional Block word set
13903: @subsection Implementation Defined Options
13904: @c ---------------------------------------------------------------------
13905: @cindex implementation-defined options, block words
13906: @cindex block words, implementation-defined options
13907: 
13908: @table @i
13909: @item the format for display by @code{LIST}:
13910: @cindex @code{LIST} display format
13911: First the screen number is displayed, then 16 lines of 64 characters,
13912: each line preceded by the line number.
13913: 
13914: @item the length of a line affected by @code{\}:
13915: @cindex length of a line affected by @code{\}
13916: @cindex @code{\}, line length in blocks
13917: 64 characters.
13918: @end table
13919: 
13920: 
13921: @c ---------------------------------------------------------------------
13922: @node block-ambcond, block-other, block-idef, The optional Block word set
13923: @subsection Ambiguous conditions
13924: @c ---------------------------------------------------------------------
13925: @cindex block words, ambiguous conditions
13926: @cindex ambiguous conditions, block words
13927: 
13928: @table @i
13929: @item correct block read was not possible:
13930: @cindex block read not possible
13931: Typically results in a @code{throw} of some OS-derived value (between
13932: -512 and -2048). If the blocks file was just not long enough, blanks are
13933: supplied for the missing portion.
13934: 
13935: @item I/O exception in block transfer:
13936: @cindex I/O exception in block transfer
13937: @cindex block transfer, I/O exception
13938: Typically results in a @code{throw} of some OS-derived value (between
13939: -512 and -2048).
13940: 
13941: @item invalid block number:
13942: @cindex invalid block number
13943: @cindex block number invalid
13944: @code{-35 throw} (Invalid block number)
13945: 
13946: @item a program directly alters the contents of @code{BLK}:
13947: @cindex @code{BLK}, altering @code{BLK}
13948: The input stream is switched to that other block, at the same
13949: position. If the storing to @code{BLK} happens when interpreting
13950: non-block input, the system will get quite confused when the block ends.
13951: 
13952: @item no current block buffer for @code{UPDATE}:
13953: @cindex @code{UPDATE}, no current block buffer
13954: @code{UPDATE} has no effect.
13955: 
13956: @end table
13957: 
13958: @c ---------------------------------------------------------------------
13959: @node block-other,  , block-ambcond, The optional Block word set
13960: @subsection Other system documentation
13961: @c ---------------------------------------------------------------------
13962: @cindex other system documentation, block words
13963: @cindex block words, other system documentation
13964: 
13965: @table @i
13966: @item any restrictions a multiprogramming system places on the use of buffer addresses:
13967: No restrictions (yet).
13968: 
13969: @item the number of blocks available for source and data:
13970: depends on your disk space.
13971: 
13972: @end table
13973: 
13974: 
13975: @c =====================================================================
13976: @node The optional Double Number word set, The optional Exception word set, The optional Block word set, ANS conformance
13977: @section The optional Double Number word set
13978: @c =====================================================================
13979: @cindex system documentation, double words
13980: @cindex double words, system documentation
13981: 
13982: @menu
13983: * double-ambcond::              Ambiguous Conditions              
13984: @end menu
13985: 
13986: 
13987: @c ---------------------------------------------------------------------
13988: @node double-ambcond,  , The optional Double Number word set, The optional Double Number word set
13989: @subsection Ambiguous conditions
13990: @c ---------------------------------------------------------------------
13991: @cindex double words, ambiguous conditions
13992: @cindex ambiguous conditions, double words
13993: 
13994: @table @i
13995: @item @i{d} outside of range of @i{n} in @code{D>S}:
13996: @cindex @code{D>S}, @i{d} out of range of @i{n} 
13997: The least significant cell of @i{d} is produced.
13998: 
13999: @end table
14000: 
14001: 
14002: @c =====================================================================
14003: @node The optional Exception word set, The optional Facility word set, The optional Double Number word set, ANS conformance
14004: @section The optional Exception word set
14005: @c =====================================================================
14006: @cindex system documentation, exception words
14007: @cindex exception words, system documentation
14008: 
14009: @menu
14010: * exception-idef::              Implementation Defined Options              
14011: @end menu
14012: 
14013: 
14014: @c ---------------------------------------------------------------------
14015: @node exception-idef,  , The optional Exception word set, The optional Exception word set
14016: @subsection Implementation Defined Options
14017: @c ---------------------------------------------------------------------
14018: @cindex implementation-defined options, exception words
14019: @cindex exception words, implementation-defined options
14020: 
14021: @table @i
14022: @item @code{THROW}-codes used in the system:
14023: @cindex @code{THROW}-codes used in the system
14024: The codes -256@minus{}-511 are used for reporting signals. The mapping
14025: from OS signal numbers to throw codes is -256@minus{}@i{signal}. The
14026: codes -512@minus{}-2047 are used for OS errors (for file and memory
14027: allocation operations). The mapping from OS error numbers to throw codes
14028: is -512@minus{}@code{errno}. One side effect of this mapping is that
14029: undefined OS errors produce a message with a strange number; e.g.,
14030: @code{-1000 THROW} results in @code{Unknown error 488} on my system.
14031: @end table
14032: 
14033: @c =====================================================================
14034: @node The optional Facility word set, The optional File-Access word set, The optional Exception word set, ANS conformance
14035: @section The optional Facility word set
14036: @c =====================================================================
14037: @cindex system documentation, facility words
14038: @cindex facility words, system documentation
14039: 
14040: @menu
14041: * facility-idef::               Implementation Defined Options               
14042: * facility-ambcond::            Ambiguous Conditions            
14043: @end menu
14044: 
14045: 
14046: @c ---------------------------------------------------------------------
14047: @node facility-idef, facility-ambcond, The optional Facility word set, The optional Facility word set
14048: @subsection Implementation Defined Options
14049: @c ---------------------------------------------------------------------
14050: @cindex implementation-defined options, facility words
14051: @cindex facility words, implementation-defined options
14052: 
14053: @table @i
14054: @item encoding of keyboard events (@code{EKEY}):
14055: @cindex keyboard events, encoding in @code{EKEY}
14056: @cindex @code{EKEY}, encoding of keyboard events
14057: Keys corresponding to ASCII characters are encoded as ASCII characters.
14058: Other keys are encoded with the constants @code{k-left}, @code{k-right},
14059: @code{k-up}, @code{k-down}, @code{k-home}, @code{k-end}, @code{k1},
14060: @code{k2}, @code{k3}, @code{k4}, @code{k5}, @code{k6}, @code{k7},
14061: @code{k8}, @code{k9}, @code{k10}, @code{k11}, @code{k12}.
14062: 
14063: 
14064: @item duration of a system clock tick:
14065: @cindex duration of a system clock tick
14066: @cindex clock tick duration
14067: System dependent. With respect to @code{MS}, the time is specified in
14068: microseconds. How well the OS and the hardware implement this, is
14069: another question.
14070: 
14071: @item repeatability to be expected from the execution of @code{MS}:
14072: @cindex repeatability to be expected from the execution of @code{MS}
14073: @cindex @code{MS}, repeatability to be expected
14074: System dependent. On Unix, a lot depends on load. If the system is
14075: lightly loaded, and the delay is short enough that Gforth does not get
14076: swapped out, the performance should be acceptable. Under MS-DOS and
14077: other single-tasking systems, it should be good.
14078: 
14079: @end table
14080: 
14081: 
14082: @c ---------------------------------------------------------------------
14083: @node facility-ambcond,  , facility-idef, The optional Facility word set
14084: @subsection Ambiguous conditions
14085: @c ---------------------------------------------------------------------
14086: @cindex facility words, ambiguous conditions
14087: @cindex ambiguous conditions, facility words
14088: 
14089: @table @i
14090: @item @code{AT-XY} can't be performed on user output device:
14091: @cindex @code{AT-XY} can't be performed on user output device
14092: Largely terminal dependent. No range checks are done on the arguments.
14093: No errors are reported. You may see some garbage appearing, you may see
14094: simply nothing happen.
14095: 
14096: @end table
14097: 
14098: 
14099: @c =====================================================================
14100: @node The optional File-Access word set, The optional Floating-Point word set, The optional Facility word set, ANS conformance
14101: @section The optional File-Access word set
14102: @c =====================================================================
14103: @cindex system documentation, file words
14104: @cindex file words, system documentation
14105: 
14106: @menu
14107: * file-idef::                   Implementation Defined Options
14108: * file-ambcond::                Ambiguous Conditions                
14109: @end menu
14110: 
14111: @c ---------------------------------------------------------------------
14112: @node file-idef, file-ambcond, The optional File-Access word set, The optional File-Access word set
14113: @subsection Implementation Defined Options
14114: @c ---------------------------------------------------------------------
14115: @cindex implementation-defined options, file words
14116: @cindex file words, implementation-defined options
14117: 
14118: @table @i
14119: @item file access methods used:
14120: @cindex file access methods used
14121: @code{R/O}, @code{R/W} and @code{BIN} work as you would
14122: expect. @code{W/O} translates into the C file opening mode @code{w} (or
14123: @code{wb}): The file is cleared, if it exists, and created, if it does
14124: not (with both @code{open-file} and @code{create-file}).  Under Unix
14125: @code{create-file} creates a file with 666 permissions modified by your
14126: umask.
14127: 
14128: @item file exceptions:
14129: @cindex file exceptions
14130: The file words do not raise exceptions (except, perhaps, memory access
14131: faults when you pass illegal addresses or file-ids).
14132: 
14133: @item file line terminator:
14134: @cindex file line terminator
14135: System-dependent. Gforth uses C's newline character as line
14136: terminator. What the actual character code(s) of this are is
14137: system-dependent.
14138: 
14139: @item file name format:
14140: @cindex file name format
14141: System dependent. Gforth just uses the file name format of your OS.
14142: 
14143: @item information returned by @code{FILE-STATUS}:
14144: @cindex @code{FILE-STATUS}, returned information
14145: @code{FILE-STATUS} returns the most powerful file access mode allowed
14146: for the file: Either @code{R/O}, @code{W/O} or @code{R/W}. If the file
14147: cannot be accessed, @code{R/O BIN} is returned. @code{BIN} is applicable
14148: along with the returned mode.
14149: 
14150: @item input file state after an exception when including source:
14151: @cindex exception when including source
14152: All files that are left via the exception are closed.
14153: 
14154: @item @i{ior} values and meaning:
14155: @cindex @i{ior} values and meaning
14156: @cindex @i{wior} values and meaning
14157: The @i{ior}s returned by the file and memory allocation words are
14158: intended as throw codes. They typically are in the range
14159: -512@minus{}-2047 of OS errors.  The mapping from OS error numbers to
14160: @i{ior}s is -512@minus{}@i{errno}.
14161: 
14162: @item maximum depth of file input nesting:
14163: @cindex maximum depth of file input nesting
14164: @cindex file input nesting, maximum depth
14165: limited by the amount of return stack, locals/TIB stack, and the number
14166: of open files available. This should not give you troubles.
14167: 
14168: @item maximum size of input line:
14169: @cindex maximum size of input line
14170: @cindex input line size, maximum
14171: @code{/line}. Currently 255.
14172: 
14173: @item methods of mapping block ranges to files:
14174: @cindex mapping block ranges to files
14175: @cindex files containing blocks
14176: @cindex blocks in files
14177: By default, blocks are accessed in the file @file{blocks.fb} in the
14178: current working directory. The file can be switched with @code{USE}.
14179: 
14180: @item number of string buffers provided by @code{S"}:
14181: @cindex @code{S"}, number of string buffers
14182: 1
14183: 
14184: @item size of string buffer used by @code{S"}:
14185: @cindex @code{S"}, size of string buffer
14186: @code{/line}. currently 255.
14187: 
14188: @end table
14189: 
14190: @c ---------------------------------------------------------------------
14191: @node file-ambcond,  , file-idef, The optional File-Access word set
14192: @subsection Ambiguous conditions
14193: @c ---------------------------------------------------------------------
14194: @cindex file words, ambiguous conditions
14195: @cindex ambiguous conditions, file words
14196: 
14197: @table @i
14198: @item attempting to position a file outside its boundaries:
14199: @cindex @code{REPOSITION-FILE}, outside the file's boundaries
14200: @code{REPOSITION-FILE} is performed as usual: Afterwards,
14201: @code{FILE-POSITION} returns the value given to @code{REPOSITION-FILE}.
14202: 
14203: @item attempting to read from file positions not yet written:
14204: @cindex reading from file positions not yet written
14205: End-of-file, i.e., zero characters are read and no error is reported.
14206: 
14207: @item @i{file-id} is invalid (@code{INCLUDE-FILE}):
14208: @cindex @code{INCLUDE-FILE}, @i{file-id} is invalid 
14209: An appropriate exception may be thrown, but a memory fault or other
14210: problem is more probable.
14211: 
14212: @item I/O exception reading or closing @i{file-id} (@code{INCLUDE-FILE}, @code{INCLUDED}):
14213: @cindex @code{INCLUDE-FILE}, I/O exception reading or closing @i{file-id}
14214: @cindex @code{INCLUDED}, I/O exception reading or closing @i{file-id}
14215: The @i{ior} produced by the operation, that discovered the problem, is
14216: thrown.
14217: 
14218: @item named file cannot be opened (@code{INCLUDED}):
14219: @cindex @code{INCLUDED}, named file cannot be opened
14220: The @i{ior} produced by @code{open-file} is thrown.
14221: 
14222: @item requesting an unmapped block number:
14223: @cindex unmapped block numbers
14224: There are no unmapped legal block numbers. On some operating systems,
14225: writing a block with a large number may overflow the file system and
14226: have an error message as consequence.
14227: 
14228: @item using @code{source-id} when @code{blk} is non-zero:
14229: @cindex @code{SOURCE-ID}, behaviour when @code{BLK} is non-zero
14230: @code{source-id} performs its function. Typically it will give the id of
14231: the source which loaded the block. (Better ideas?)
14232: 
14233: @end table
14234: 
14235: 
14236: @c =====================================================================
14237: @node  The optional Floating-Point word set, The optional Locals word set, The optional File-Access word set, ANS conformance
14238: @section The optional Floating-Point word set
14239: @c =====================================================================
14240: @cindex system documentation, floating-point words
14241: @cindex floating-point words, system documentation
14242: 
14243: @menu
14244: * floating-idef::               Implementation Defined Options
14245: * floating-ambcond::            Ambiguous Conditions            
14246: @end menu
14247: 
14248: 
14249: @c ---------------------------------------------------------------------
14250: @node floating-idef, floating-ambcond, The optional Floating-Point word set, The optional Floating-Point word set
14251: @subsection Implementation Defined Options
14252: @c ---------------------------------------------------------------------
14253: @cindex implementation-defined options, floating-point words
14254: @cindex floating-point words, implementation-defined options
14255: 
14256: @table @i
14257: @item format and range of floating point numbers:
14258: @cindex format and range of floating point numbers
14259: @cindex floating point numbers, format and range
14260: System-dependent; the @code{double} type of C.
14261: 
14262: @item results of @code{REPRESENT} when @i{float} is out of range:
14263: @cindex  @code{REPRESENT}, results when @i{float} is out of range
14264: System dependent; @code{REPRESENT} is implemented using the C library
14265: function @code{ecvt()} and inherits its behaviour in this respect.
14266: 
14267: @item rounding or truncation of floating-point numbers:
14268: @cindex rounding of floating-point numbers
14269: @cindex truncation of floating-point numbers
14270: @cindex floating-point numbers, rounding or truncation
14271: System dependent; the rounding behaviour is inherited from the hosting C
14272: compiler. IEEE-FP-based (i.e., most) systems by default round to
14273: nearest, and break ties by rounding to even (i.e., such that the last
14274: bit of the mantissa is 0).
14275: 
14276: @item size of floating-point stack:
14277: @cindex floating-point stack size
14278: @code{s" FLOATING-STACK" environment? drop .} gives the total size of
14279: the floating-point stack (in floats). You can specify this on startup
14280: with the command-line option @code{-f} (@pxref{Invoking Gforth}).
14281: 
14282: @item width of floating-point stack:
14283: @cindex floating-point stack width 
14284: @code{1 floats}.
14285: 
14286: @end table
14287: 
14288: 
14289: @c ---------------------------------------------------------------------
14290: @node floating-ambcond,  , floating-idef, The optional Floating-Point word set
14291: @subsection Ambiguous conditions
14292: @c ---------------------------------------------------------------------
14293: @cindex floating-point words, ambiguous conditions
14294: @cindex ambiguous conditions, floating-point words
14295: 
14296: @table @i
14297: @item @code{df@@} or @code{df!} used with an address that is not double-float  aligned:
14298: @cindex @code{df@@} or @code{df!} used with an address that is not double-float  aligned
14299: System-dependent. Typically results in a @code{-23 THROW} like other
14300: alignment violations.
14301: 
14302: @item @code{f@@} or @code{f!} used with an address that is not float  aligned:
14303: @cindex @code{f@@} used with an address that is not float aligned
14304: @cindex @code{f!} used with an address that is not float aligned
14305: System-dependent. Typically results in a @code{-23 THROW} like other
14306: alignment violations.
14307: 
14308: @item floating-point result out of range:
14309: @cindex floating-point result out of range
14310: System-dependent. Can result in a @code{-43 throw} (floating point
14311: overflow), @code{-54 throw} (floating point underflow), @code{-41 throw}
14312: (floating point inexact result), @code{-55 THROW} (Floating-point
14313: unidentified fault), or can produce a special value representing, e.g.,
14314: Infinity.
14315: 
14316: @item @code{sf@@} or @code{sf!} used with an address that is not single-float  aligned:
14317: @cindex @code{sf@@} or @code{sf!} used with an address that is not single-float  aligned
14318: System-dependent. Typically results in an alignment fault like other
14319: alignment violations.
14320: 
14321: @item @code{base} is not decimal (@code{REPRESENT}, @code{F.}, @code{FE.}, @code{FS.}):
14322: @cindex @code{base} is not decimal (@code{REPRESENT}, @code{F.}, @code{FE.}, @code{FS.})
14323: The floating-point number is converted into decimal nonetheless.
14324: 
14325: @item Both arguments are equal to zero (@code{FATAN2}):
14326: @cindex @code{FATAN2}, both arguments are equal to zero
14327: System-dependent. @code{FATAN2} is implemented using the C library
14328: function @code{atan2()}.
14329: 
14330: @item Using @code{FTAN} on an argument @i{r1} where cos(@i{r1}) is zero:
14331: @cindex @code{FTAN} on an argument @i{r1} where cos(@i{r1}) is zero
14332: System-dependent. Anyway, typically the cos of @i{r1} will not be zero
14333: because of small errors and the tan will be a very large (or very small)
14334: but finite number.
14335: 
14336: @item @i{d} cannot be presented precisely as a float in @code{D>F}:
14337: @cindex @code{D>F}, @i{d} cannot be presented precisely as a float
14338: The result is rounded to the nearest float.
14339: 
14340: @item dividing by zero:
14341: @cindex dividing by zero, floating-point
14342: @cindex floating-point dividing by zero
14343: @cindex floating-point unidentified fault, FP divide-by-zero
14344: Platform-dependent; can produce an Infinity, NaN, @code{-42 throw}
14345: (floating point divide by zero) or @code{-55 throw} (Floating-point
14346: unidentified fault).
14347: 
14348: @item exponent too big for conversion (@code{DF!}, @code{DF@@}, @code{SF!}, @code{SF@@}):
14349: @cindex exponent too big for conversion (@code{DF!}, @code{DF@@}, @code{SF!}, @code{SF@@})
14350: System dependent. On IEEE-FP based systems the number is converted into
14351: an infinity.
14352: 
14353: @item @i{float}<1 (@code{FACOSH}):
14354: @cindex @code{FACOSH}, @i{float}<1
14355: @cindex floating-point unidentified fault, @code{FACOSH}
14356: Platform-dependent; on IEEE-FP systems typically produces a NaN.
14357: 
14358: @item @i{float}=<-1 (@code{FLNP1}):
14359: @cindex @code{FLNP1}, @i{float}=<-1
14360: @cindex floating-point unidentified fault, @code{FLNP1}
14361: Platform-dependent; on IEEE-FP systems typically produces a NaN (or a
14362: negative infinity for @i{float}=-1).
14363: 
14364: @item @i{float}=<0 (@code{FLN}, @code{FLOG}):
14365: @cindex @code{FLN}, @i{float}=<0
14366: @cindex @code{FLOG}, @i{float}=<0
14367: @cindex floating-point unidentified fault, @code{FLN} or @code{FLOG}
14368: Platform-dependent; on IEEE-FP systems typically produces a NaN (or a
14369: negative infinity for @i{float}=0).
14370: 
14371: @item @i{float}<0 (@code{FASINH}, @code{FSQRT}):
14372: @cindex @code{FASINH}, @i{float}<0
14373: @cindex @code{FSQRT}, @i{float}<0
14374: @cindex floating-point unidentified fault, @code{FASINH} or @code{FSQRT}
14375: Platform-dependent; for @code{fsqrt} this typically gives a NaN, for
14376: @code{fasinh} some platforms produce a NaN, others a number (bug in the
14377: C library?).
14378: 
14379: @item |@i{float}|>1 (@code{FACOS}, @code{FASIN}, @code{FATANH}):
14380: @cindex @code{FACOS}, |@i{float}|>1
14381: @cindex @code{FASIN}, |@i{float}|>1
14382: @cindex @code{FATANH}, |@i{float}|>1
14383: @cindex floating-point unidentified fault, @code{FACOS}, @code{FASIN} or @code{FATANH}
14384: Platform-dependent; IEEE-FP systems typically produce a NaN.
14385: 
14386: @item integer part of float cannot be represented by @i{d} in @code{F>D}:
14387: @cindex @code{F>D}, integer part of float cannot be represented by @i{d}
14388: @cindex floating-point unidentified fault, @code{F>D}
14389: Platform-dependent; typically, some double number is produced and no
14390: error is reported.
14391: 
14392: @item string larger than pictured numeric output area (@code{f.}, @code{fe.}, @code{fs.}):
14393: @cindex string larger than pictured numeric output area (@code{f.}, @code{fe.}, @code{fs.})
14394: @code{Precision} characters of the numeric output area are used.  If
14395: @code{precision} is too high, these words will smash the data or code
14396: close to @code{here}.
14397: @end table
14398: 
14399: @c =====================================================================
14400: @node  The optional Locals word set, The optional Memory-Allocation word set, The optional Floating-Point word set, ANS conformance
14401: @section The optional Locals word set
14402: @c =====================================================================
14403: @cindex system documentation, locals words
14404: @cindex locals words, system documentation
14405: 
14406: @menu
14407: * locals-idef::                 Implementation Defined Options                 
14408: * locals-ambcond::              Ambiguous Conditions              
14409: @end menu
14410: 
14411: 
14412: @c ---------------------------------------------------------------------
14413: @node locals-idef, locals-ambcond, The optional Locals word set, The optional Locals word set
14414: @subsection Implementation Defined Options
14415: @c ---------------------------------------------------------------------
14416: @cindex implementation-defined options, locals words
14417: @cindex locals words, implementation-defined options
14418: 
14419: @table @i
14420: @item maximum number of locals in a definition:
14421: @cindex maximum number of locals in a definition
14422: @cindex locals, maximum number in a definition
14423: @code{s" #locals" environment? drop .}. Currently 15. This is a lower
14424: bound, e.g., on a 32-bit machine there can be 41 locals of up to 8
14425: characters. The number of locals in a definition is bounded by the size
14426: of locals-buffer, which contains the names of the locals.
14427: 
14428: @end table
14429: 
14430: 
14431: @c ---------------------------------------------------------------------
14432: @node locals-ambcond,  , locals-idef, The optional Locals word set
14433: @subsection Ambiguous conditions
14434: @c ---------------------------------------------------------------------
14435: @cindex locals words, ambiguous conditions
14436: @cindex ambiguous conditions, locals words
14437: 
14438: @table @i
14439: @item executing a named local in interpretation state:
14440: @cindex local in interpretation state
14441: @cindex Interpreting a compile-only word, for a local
14442: Locals have no interpretation semantics. If you try to perform the
14443: interpretation semantics, you will get a @code{-14 throw} somewhere
14444: (Interpreting a compile-only word). If you perform the compilation
14445: semantics, the locals access will be compiled (irrespective of state).
14446: 
14447: @item @i{name} not defined by @code{VALUE} or @code{(LOCAL)} (@code{TO}):
14448: @cindex name not defined by @code{VALUE} or @code{(LOCAL)} used by @code{TO}
14449: @cindex @code{TO} on non-@code{VALUE}s and non-locals
14450: @cindex Invalid name argument, @code{TO}
14451: @code{-32 throw} (Invalid name argument)
14452: 
14453: @end table
14454: 
14455: 
14456: @c =====================================================================
14457: @node  The optional Memory-Allocation word set, The optional Programming-Tools word set, The optional Locals word set, ANS conformance
14458: @section The optional Memory-Allocation word set
14459: @c =====================================================================
14460: @cindex system documentation, memory-allocation words
14461: @cindex memory-allocation words, system documentation
14462: 
14463: @menu
14464: * memory-idef::                 Implementation Defined Options                 
14465: @end menu
14466: 
14467: 
14468: @c ---------------------------------------------------------------------
14469: @node memory-idef,  , The optional Memory-Allocation word set, The optional Memory-Allocation word set
14470: @subsection Implementation Defined Options
14471: @c ---------------------------------------------------------------------
14472: @cindex implementation-defined options, memory-allocation words
14473: @cindex memory-allocation words, implementation-defined options
14474: 
14475: @table @i
14476: @item values and meaning of @i{ior}:
14477: @cindex  @i{ior} values and meaning
14478: The @i{ior}s returned by the file and memory allocation words are
14479: intended as throw codes. They typically are in the range
14480: -512@minus{}-2047 of OS errors.  The mapping from OS error numbers to
14481: @i{ior}s is -512@minus{}@i{errno}.
14482: 
14483: @end table
14484: 
14485: @c =====================================================================
14486: @node  The optional Programming-Tools word set, The optional Search-Order word set, The optional Memory-Allocation word set, ANS conformance
14487: @section The optional Programming-Tools word set
14488: @c =====================================================================
14489: @cindex system documentation, programming-tools words
14490: @cindex programming-tools words, system documentation
14491: 
14492: @menu
14493: * programming-idef::            Implementation Defined Options            
14494: * programming-ambcond::         Ambiguous Conditions         
14495: @end menu
14496: 
14497: 
14498: @c ---------------------------------------------------------------------
14499: @node programming-idef, programming-ambcond, The optional Programming-Tools word set, The optional Programming-Tools word set
14500: @subsection Implementation Defined Options
14501: @c ---------------------------------------------------------------------
14502: @cindex implementation-defined options, programming-tools words
14503: @cindex programming-tools words, implementation-defined options
14504: 
14505: @table @i
14506: @item ending sequence for input following @code{;CODE} and @code{CODE}:
14507: @cindex @code{;CODE} ending sequence
14508: @cindex @code{CODE} ending sequence
14509: @code{END-CODE}
14510: 
14511: @item manner of processing input following @code{;CODE} and @code{CODE}:
14512: @cindex @code{;CODE}, processing input
14513: @cindex @code{CODE}, processing input
14514: The @code{ASSEMBLER} vocabulary is pushed on the search order stack, and
14515: the input is processed by the text interpreter, (starting) in interpret
14516: state.
14517: 
14518: @item search order capability for @code{EDITOR} and @code{ASSEMBLER}:
14519: @cindex @code{ASSEMBLER}, search order capability
14520: The ANS Forth search order word set.
14521: 
14522: @item source and format of display by @code{SEE}:
14523: @cindex @code{SEE}, source and format of output
14524: The source for @code{see} is the executable code used by the inner
14525: interpreter.  The current @code{see} tries to output Forth source code
14526: (and on some platforms, assembly code for primitives) as well as
14527: possible.
14528: 
14529: @end table
14530: 
14531: @c ---------------------------------------------------------------------
14532: @node programming-ambcond,  , programming-idef, The optional Programming-Tools word set
14533: @subsection Ambiguous conditions
14534: @c ---------------------------------------------------------------------
14535: @cindex programming-tools words, ambiguous conditions
14536: @cindex ambiguous conditions, programming-tools words
14537: 
14538: @table @i
14539: 
14540: @item deleting the compilation word list (@code{FORGET}):
14541: @cindex @code{FORGET}, deleting the compilation word list
14542: Not implemented (yet).
14543: 
14544: @item fewer than @i{u}+1 items on the control-flow stack (@code{CS-PICK}, @code{CS-ROLL}):
14545: @cindex @code{CS-PICK}, fewer than @i{u}+1 items on the control flow-stack
14546: @cindex @code{CS-ROLL}, fewer than @i{u}+1 items on the control flow-stack
14547: @cindex control-flow stack underflow
14548: This typically results in an @code{abort"} with a descriptive error
14549: message (may change into a @code{-22 throw} (Control structure mismatch)
14550: in the future). You may also get a memory access error. If you are
14551: unlucky, this ambiguous condition is not caught.