File:  [gforth] / gforth / doc / gforth.ds
Revision 1.184: download - view: text, annotated - select for diffs
Fri Jul 6 12:54:56 2007 UTC (16 years, 8 months ago) by anton
Branches: MAIN
CVS tags: HEAD
fixed most problems reported by "make checkdoc"

    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 Free Software Foundation, Inc.
   65: 
   66: @quotation
   67: Permission is granted to copy, distribute and/or modify this document
   68: under the terms of the GNU Free Documentation License, Version 1.1 or
   69: any later version published by the Free Software Foundation; with no
   70: Invariant Sections, with the Front-Cover texts being ``A GNU Manual,''
   71: and with the Back-Cover Texts as in (a) below.  A copy of the
   72: license is included in the section entitled ``GNU Free Documentation
   73: License.''
   74: 
   75: (a) The FSF's Back-Cover Text is: ``You have freedom to copy and modify
   76: this GNU Manual, like GNU software.  Copies published by the Free
   77: Software Foundation raise funds for GNU development.''
   78: @end quotation
   79: @end copying
   80: 
   81: @dircategory Software development
   82: @direntry
   83: * Gforth: (gforth).             A fast interpreter for the Forth language.
   84: @end direntry
   85: @c The Texinfo manual also recommends doing this, but for Gforth it may
   86: @c  not make much sense
   87: @c @dircategory Individual utilities
   88: @c @direntry
   89: @c * Gforth: (gforth)Invoking Gforth.      gforth, gforth-fast, gforthmi
   90: @c @end direntry
   91: 
   92: @titlepage
   93: @title Gforth
   94: @subtitle for version @value{VERSION}, @value{UPDATED}
   95: @author Neal Crook
   96: @author Anton Ertl
   97: @author David Kuehling
   98: @author Bernd Paysan
   99: @author Jens Wilke
  100: @page
  101: @vskip 0pt plus 1filll
  102: @insertcopying
  103: @end titlepage
  104: 
  105: @contents
  106: 
  107: @ifnottex
  108: @node Top, Goals, (dir), (dir)
  109: @top Gforth
  110: 
  111: @insertcopying
  112: @end ifnottex
  113: 
  114: @menu
  115: * Goals::                       About the Gforth Project
  116: * Gforth Environment::          Starting (and exiting) Gforth
  117: * Tutorial::                    Hands-on Forth Tutorial
  118: * Introduction::                An introduction to ANS Forth
  119: * Words::                       Forth words available in Gforth
  120: * Error messages::              How to interpret them
  121: * Tools::                       Programming tools
  122: * ANS conformance::             Implementation-defined options etc.
  123: * Standard vs Extensions::      Should I use extensions?
  124: * Model::                       The abstract machine of Gforth
  125: * Integrating Gforth::          Forth as scripting language for applications
  126: * Emacs and Gforth::            The Gforth Mode
  127: * Image Files::                 @code{.fi} files contain compiled code
  128: * Engine::                      The inner interpreter and the primitives
  129: * Cross Compiler::              The Cross Compiler
  130: * Bugs::                        How to report them
  131: * Origin::                      Authors and ancestors of Gforth
  132: * Forth-related information::   Books and places to look on the WWW
  133: * Licenses::                    
  134: * Word Index::                  An item for each Forth word
  135: * Concept Index::               A menu covering many topics
  136: 
  137: @detailmenu
  138:  --- The Detailed Node Listing ---
  139: 
  140: Gforth Environment
  141: 
  142: * Invoking Gforth::             Getting in
  143: * Leaving Gforth::              Getting out
  144: * Command-line editing::        
  145: * Environment variables::       that affect how Gforth starts up
  146: * Gforth Files::                What gets installed and where
  147: * Gforth in pipes::             
  148: * Startup speed::               When 35ms is not fast enough ...
  149: 
  150: Forth Tutorial
  151: 
  152: * Starting Gforth Tutorial::    
  153: * Syntax Tutorial::             
  154: * Crash Course Tutorial::       
  155: * Stack Tutorial::              
  156: * Arithmetics Tutorial::        
  157: * Stack Manipulation Tutorial::  
  158: * Using files for Forth code Tutorial::  
  159: * Comments Tutorial::           
  160: * Colon Definitions Tutorial::  
  161: * Decompilation Tutorial::      
  162: * Stack-Effect Comments Tutorial::  
  163: * Types Tutorial::              
  164: * Factoring Tutorial::          
  165: * Designing the stack effect Tutorial::  
  166: * Local Variables Tutorial::    
  167: * Conditional execution Tutorial::  
  168: * Flags and Comparisons Tutorial::  
  169: * General Loops Tutorial::      
  170: * Counted loops Tutorial::      
  171: * Recursion Tutorial::          
  172: * Leaving definitions or loops Tutorial::  
  173: * Return Stack Tutorial::       
  174: * Memory Tutorial::             
  175: * Characters and Strings Tutorial::  
  176: * Alignment Tutorial::          
  177: * Files Tutorial::              
  178: * Interpretation and Compilation Semantics and Immediacy Tutorial::  
  179: * Execution Tokens Tutorial::   
  180: * Exceptions Tutorial::         
  181: * Defining Words Tutorial::     
  182: * Arrays and Records Tutorial::  
  183: * POSTPONE Tutorial::           
  184: * Literal Tutorial::            
  185: * Advanced macros Tutorial::    
  186: * Compilation Tokens Tutorial::  
  187: * Wordlists and Search Order Tutorial::  
  188: 
  189: An Introduction to ANS Forth
  190: 
  191: * Introducing the Text Interpreter::  
  192: * Stacks and Postfix notation::  
  193: * Your first definition::       
  194: * How does that work?::         
  195: * Forth is written in Forth::   
  196: * Review - elements of a Forth system::  
  197: * Where to go next::            
  198: * Exercises::                   
  199: 
  200: Forth Words
  201: 
  202: * Notation::                    
  203: * Case insensitivity::          
  204: * Comments::                    
  205: * Boolean Flags::               
  206: * Arithmetic::                  
  207: * Stack Manipulation::          
  208: * Memory::                      
  209: * Control Structures::          
  210: * Defining Words::              
  211: * Interpretation and Compilation Semantics::  
  212: * Tokens for Words::            
  213: * Compiling words::             
  214: * The Text Interpreter::        
  215: * The Input Stream::            
  216: * Word Lists::                  
  217: * Environmental Queries::       
  218: * Files::                       
  219: * Blocks::                      
  220: * Other I/O::                   
  221: * OS command line arguments::   
  222: * Locals::                      
  223: * Structures::                  
  224: * Object-oriented Forth::       
  225: * Programming Tools::           
  226: * C Interface::                 
  227: * Assembler and Code Words::    
  228: * Threading Words::             
  229: * Passing Commands to the OS::  
  230: * Keeping track of Time::       
  231: * Miscellaneous Words::         
  232: 
  233: Arithmetic
  234: 
  235: * Single precision::            
  236: * Double precision::            Double-cell integer arithmetic
  237: * Bitwise operations::          
  238: * Numeric comparison::          
  239: * Mixed precision::             Operations with single and double-cell integers
  240: * Floating Point::              
  241: 
  242: Stack Manipulation
  243: 
  244: * Data stack::                  
  245: * Floating point stack::        
  246: * Return stack::                
  247: * Locals stack::                
  248: * Stack pointer manipulation::  
  249: 
  250: Memory
  251: 
  252: * Memory model::                
  253: * Dictionary allocation::       
  254: * Heap Allocation::             
  255: * Memory Access::               
  256: * Address arithmetic::          
  257: * Memory Blocks::               
  258: 
  259: Control Structures
  260: 
  261: * Selection::                   IF ... ELSE ... ENDIF
  262: * Simple Loops::                BEGIN ...
  263: * Counted Loops::               DO
  264: * Arbitrary control structures::  
  265: * Calls and returns::           
  266: * Exception Handling::          
  267: 
  268: Defining Words
  269: 
  270: * CREATE::                      
  271: * Variables::                   Variables and user variables
  272: * Constants::                   
  273: * Values::                      Initialised variables
  274: * Colon Definitions::           
  275: * Anonymous Definitions::       Definitions without names
  276: * Supplying names::             Passing definition names as strings
  277: * User-defined Defining Words::  
  278: * Deferred Words::              Allow forward references
  279: * Aliases::                     
  280: 
  281: User-defined Defining Words
  282: 
  283: * CREATE..DOES> applications::  
  284: * CREATE..DOES> details::       
  285: * Advanced does> usage example::  
  286: * Const-does>::                 
  287: 
  288: Interpretation and Compilation Semantics
  289: 
  290: * Combined words::              
  291: 
  292: Tokens for Words
  293: 
  294: * Execution token::             represents execution/interpretation semantics
  295: * Compilation token::           represents compilation semantics
  296: * Name token::                  represents named words
  297: 
  298: Compiling words
  299: 
  300: * Literals::                    Compiling data values
  301: * Macros::                      Compiling words
  302: 
  303: The Text Interpreter
  304: 
  305: * Input Sources::               
  306: * Number Conversion::           
  307: * Interpret/Compile states::    
  308: * Interpreter Directives::      
  309: 
  310: Word Lists
  311: 
  312: * Vocabularies::                
  313: * Why use word lists?::         
  314: * Word list example::           
  315: 
  316: Files
  317: 
  318: * Forth source files::          
  319: * General files::               
  320: * Redirection::                 
  321: * Search Paths::                
  322: 
  323: Search Paths
  324: 
  325: * Source Search Paths::         
  326: * General Search Paths::        
  327: 
  328: Other I/O
  329: 
  330: * Simple numeric output::       Predefined formats
  331: * Formatted numeric output::    Formatted (pictured) output
  332: * String Formats::              How Forth stores strings in memory
  333: * Displaying characters and strings::  Other stuff
  334: * Terminal output::             Cursor positioning etc.
  335: * Single-key input::            
  336: * Line input and conversion::   
  337: * Pipes::                       How to create your own pipes
  338: * Xchars and Unicode::          Non-ASCII characters
  339: 
  340: Locals
  341: 
  342: * Gforth locals::               
  343: * ANS Forth locals::            
  344: 
  345: Gforth locals
  346: 
  347: * Where are locals visible by name?::  
  348: * How long do locals live?::    
  349: * Locals programming style::    
  350: * Locals implementation::       
  351: 
  352: Structures
  353: 
  354: * Why explicit structure support?::  
  355: * Structure Usage::             
  356: * Structure Naming Convention::  
  357: * Structure Implementation::    
  358: * Structure Glossary::          
  359: * Forth200x Structures::        
  360: 
  361: Object-oriented Forth
  362: 
  363: * Why object-oriented programming?::  
  364: * Object-Oriented Terminology::  
  365: * Objects::                     
  366: * OOF::                         
  367: * Mini-OOF::                    
  368: * Comparison with other object models::  
  369: 
  370: The @file{objects.fs} model
  371: 
  372: * Properties of the Objects model::  
  373: * Basic Objects Usage::         
  374: * The Objects base class::      
  375: * Creating objects::            
  376: * Object-Oriented Programming Style::  
  377: * Class Binding::               
  378: * Method conveniences::         
  379: * Classes and Scoping::         
  380: * Dividing classes::            
  381: * Object Interfaces::           
  382: * Objects Implementation::      
  383: * Objects Glossary::            
  384: 
  385: The @file{oof.fs} model
  386: 
  387: * Properties of the OOF model::  
  388: * Basic OOF Usage::             
  389: * The OOF base class::          
  390: * Class Declaration::           
  391: * Class Implementation::        
  392: 
  393: The @file{mini-oof.fs} model
  394: 
  395: * Basic Mini-OOF Usage::        
  396: * Mini-OOF Example::            
  397: * Mini-OOF Implementation::     
  398: 
  399: Programming Tools
  400: 
  401: * Examining::                   Data and Code.
  402: * Forgetting words::            Usually before reloading.
  403: * Debugging::                   Simple and quick.
  404: * Assertions::                  Making your programs self-checking.
  405: * Singlestep Debugger::         Executing your program word by word.
  406: 
  407: C Interface
  408: 
  409: * Calling C Functions::         
  410: * Declaring C Functions::       
  411: * Calling C function pointers::  
  412: * Callbacks::                   
  413: * C interface internals::       
  414: * Low-Level C Interface Words::  
  415: 
  416: Assembler and Code Words
  417: 
  418: * Code and ;code::              
  419: * Common Assembler::            Assembler Syntax
  420: * Common Disassembler::         
  421: * 386 Assembler::               Deviations and special cases
  422: * Alpha Assembler::             Deviations and special cases
  423: * MIPS assembler::              Deviations and special cases
  424: * PowerPC assembler::           Deviations and special cases
  425: * Other assemblers::            How to write them
  426: 
  427: Tools
  428: 
  429: * ANS Report::                  Report the words used, sorted by wordset.
  430: * Stack depth changes::         Where does this stack item come from?
  431: 
  432: ANS conformance
  433: 
  434: * The Core Words::              
  435: * The optional Block word set::  
  436: * The optional Double Number word set::  
  437: * The optional Exception word set::  
  438: * The optional Facility word set::  
  439: * The optional File-Access word set::  
  440: * The optional Floating-Point word set::  
  441: * The optional Locals word set::  
  442: * The optional Memory-Allocation word set::  
  443: * The optional Programming-Tools word set::  
  444: * The optional Search-Order word set::  
  445: 
  446: The Core Words
  447: 
  448: * core-idef::                   Implementation Defined Options                   
  449: * core-ambcond::                Ambiguous Conditions                
  450: * core-other::                  Other System Documentation                  
  451: 
  452: The optional Block word set
  453: 
  454: * block-idef::                  Implementation Defined Options
  455: * block-ambcond::               Ambiguous Conditions               
  456: * block-other::                 Other System Documentation                 
  457: 
  458: The optional Double Number word set
  459: 
  460: * double-ambcond::              Ambiguous Conditions              
  461: 
  462: The optional Exception word set
  463: 
  464: * exception-idef::              Implementation Defined Options              
  465: 
  466: The optional Facility word set
  467: 
  468: * facility-idef::               Implementation Defined Options               
  469: * facility-ambcond::            Ambiguous Conditions            
  470: 
  471: The optional File-Access word set
  472: 
  473: * file-idef::                   Implementation Defined Options
  474: * file-ambcond::                Ambiguous Conditions                
  475: 
  476: The optional Floating-Point word set
  477: 
  478: * floating-idef::               Implementation Defined Options
  479: * floating-ambcond::            Ambiguous Conditions            
  480: 
  481: The optional Locals word set
  482: 
  483: * locals-idef::                 Implementation Defined Options                 
  484: * locals-ambcond::              Ambiguous Conditions              
  485: 
  486: The optional Memory-Allocation word set
  487: 
  488: * memory-idef::                 Implementation Defined Options                 
  489: 
  490: The optional Programming-Tools word set
  491: 
  492: * programming-idef::            Implementation Defined Options            
  493: * programming-ambcond::         Ambiguous Conditions         
  494: 
  495: The optional Search-Order word set
  496: 
  497: * search-idef::                 Implementation Defined Options                 
  498: * search-ambcond::              Ambiguous Conditions              
  499: 
  500: Emacs and Gforth
  501: 
  502: * Installing gforth.el::        Making Emacs aware of Forth.
  503: * Emacs Tags::                  Viewing the source of a word in Emacs.
  504: * Hilighting::                  Making Forth code look prettier.
  505: * Auto-Indentation::            Customizing auto-indentation.
  506: * Blocks Files::                Reading and writing blocks files.
  507: 
  508: Image Files
  509: 
  510: * Image Licensing Issues::      Distribution terms for images.
  511: * Image File Background::       Why have image files?
  512: * Non-Relocatable Image Files::  don't always work.
  513: * Data-Relocatable Image Files::  are better.
  514: * Fully Relocatable Image Files::  better yet.
  515: * Stack and Dictionary Sizes::  Setting the default sizes for an image.
  516: * Running Image Files::         @code{gforth -i @i{file}} or @i{file}.
  517: * Modifying the Startup Sequence::  and turnkey applications.
  518: 
  519: Fully Relocatable Image Files
  520: 
  521: * gforthmi::                    The normal way
  522: * cross.fs::                    The hard way
  523: 
  524: Engine
  525: 
  526: * Portability::                 
  527: * Threading::                   
  528: * Primitives::                  
  529: * Performance::                 
  530: 
  531: Threading
  532: 
  533: * Scheduling::                  
  534: * Direct or Indirect Threaded?::  
  535: * Dynamic Superinstructions::   
  536: * DOES>::                       
  537: 
  538: Primitives
  539: 
  540: * Automatic Generation::        
  541: * TOS Optimization::            
  542: * Produced code::               
  543: 
  544: Cross Compiler
  545: 
  546: * Using the Cross Compiler::    
  547: * How the Cross Compiler Works::  
  548: 
  549: Licenses
  550: 
  551: * GNU Free Documentation License::  License for copying this manual.
  552: * Copying::                         GPL (for copying this software).
  553: 
  554: @end detailmenu
  555: @end menu
  556: 
  557: @c ----------------------------------------------------------
  558: @iftex
  559: @unnumbered Preface
  560: @cindex Preface
  561: This manual documents Gforth. Some introductory material is provided for
  562: readers who are unfamiliar with Forth or who are migrating to Gforth
  563: from other Forth compilers. However, this manual is primarily a
  564: reference manual.
  565: @end iftex
  566: 
  567: @comment TODO much more blurb here.
  568: 
  569: @c ******************************************************************
  570: @node Goals, Gforth Environment, Top, Top
  571: @comment node-name,     next,           previous, up
  572: @chapter Goals of Gforth
  573: @cindex goals of the Gforth project
  574: The goal of the Gforth Project is to develop a standard model for
  575: ANS Forth. This can be split into several subgoals:
  576: 
  577: @itemize @bullet
  578: @item
  579: Gforth should conform to the ANS Forth Standard.
  580: @item
  581: It should be a model, i.e. it should define all the
  582: implementation-dependent things.
  583: @item
  584: It should become standard, i.e. widely accepted and used. This goal
  585: is the most difficult one.
  586: @end itemize
  587: 
  588: To achieve these goals Gforth should be
  589: @itemize @bullet
  590: @item
  591: Similar to previous models (fig-Forth, F83)
  592: @item
  593: Powerful. It should provide for all the things that are considered
  594: necessary today and even some that are not yet considered necessary.
  595: @item
  596: Efficient. It should not get the reputation of being exceptionally
  597: slow.
  598: @item
  599: Free.
  600: @item
  601: Available on many machines/easy to port.
  602: @end itemize
  603: 
  604: Have we achieved these goals? Gforth conforms to the ANS Forth
  605: standard. It may be considered a model, but we have not yet documented
  606: which parts of the model are stable and which parts we are likely to
  607: change. It certainly has not yet become a de facto standard, but it
  608: appears to be quite popular. It has some similarities to and some
  609: differences from previous models. It has some powerful features, but not
  610: yet everything that we envisioned. We certainly have achieved our
  611: execution speed goals (@pxref{Performance})@footnote{However, in 1998
  612: the bar was raised when the major commercial Forth vendors switched to
  613: native code compilers.}.  It is free and available on many machines.
  614: 
  615: @c ******************************************************************
  616: @node Gforth Environment, Tutorial, Goals, Top
  617: @chapter Gforth Environment
  618: @cindex Gforth environment
  619: 
  620: Note: ultimately, the Gforth man page will be auto-generated from the
  621: material in this chapter.
  622: 
  623: @menu
  624: * Invoking Gforth::             Getting in
  625: * Leaving Gforth::              Getting out
  626: * Command-line editing::        
  627: * Environment variables::       that affect how Gforth starts up
  628: * Gforth Files::                What gets installed and where
  629: * Gforth in pipes::             
  630: * Startup speed::               When 35ms is not fast enough ...
  631: @end menu
  632: 
  633: For related information about the creation of images see @ref{Image Files}.
  634: 
  635: @comment ----------------------------------------------
  636: @node Invoking Gforth, Leaving Gforth, Gforth Environment, Gforth Environment
  637: @section Invoking Gforth
  638: @cindex invoking Gforth
  639: @cindex running Gforth
  640: @cindex command-line options
  641: @cindex options on the command line
  642: @cindex flags on the command line
  643: 
  644: Gforth is made up of two parts; an executable ``engine'' (named
  645: @command{gforth} or @command{gforth-fast}) and an image file. To start it, you
  646: will usually just say @code{gforth} -- this automatically loads the
  647: default image file @file{gforth.fi}. In many other cases the default
  648: Gforth image will be invoked like this:
  649: @example
  650: gforth [file | -e forth-code] ...
  651: @end example
  652: @noindent
  653: This interprets the contents of the files and the Forth code in the order they
  654: are given.
  655: 
  656: In addition to the @command{gforth} engine, there is also an engine
  657: called @command{gforth-fast}, which is faster, but gives less
  658: informative error messages (@pxref{Error messages}) and may catch some
  659: errors (in particular, stack underflows and integer division errors)
  660: later or not at all.  You should use it for debugged,
  661: performance-critical programs.
  662: 
  663: Moreover, there is an engine called @command{gforth-itc}, which is
  664: useful in some backwards-compatibility situations (@pxref{Direct or
  665: Indirect Threaded?}).
  666: 
  667: In general, the command line looks like this:
  668: 
  669: @example
  670: gforth[-fast] [engine options] [image options]
  671: @end example
  672: 
  673: The engine options must come before the rest of the command
  674: line. They are:
  675: 
  676: @table @code
  677: @cindex -i, command-line option
  678: @cindex --image-file, command-line option
  679: @item --image-file @i{file}
  680: @itemx -i @i{file}
  681: Loads the Forth image @i{file} instead of the default
  682: @file{gforth.fi} (@pxref{Image Files}).
  683: 
  684: @cindex --appl-image, command-line option
  685: @item --appl-image @i{file}
  686: Loads the image @i{file} and leaves all further command-line arguments
  687: to the image (instead of processing them as engine options).  This is
  688: useful for building executable application images on Unix, built with
  689: @code{gforthmi --application ...}.
  690: 
  691: @cindex --path, command-line option
  692: @cindex -p, command-line option
  693: @item --path @i{path}
  694: @itemx -p @i{path}
  695: Uses @i{path} for searching the image file and Forth source code files
  696: instead of the default in the environment variable @code{GFORTHPATH} or
  697: the path specified at installation time (e.g.,
  698: @file{/usr/local/share/gforth/0.2.0:.}). A path is given as a list of
  699: directories, separated by @samp{:} (on Unix) or @samp{;} (on other OSs).
  700: 
  701: @cindex --dictionary-size, command-line option
  702: @cindex -m, command-line option
  703: @cindex @i{size} parameters for command-line options
  704: @cindex size of the dictionary and the stacks
  705: @item --dictionary-size @i{size}
  706: @itemx -m @i{size}
  707: Allocate @i{size} space for the Forth dictionary space instead of
  708: using the default specified in the image (typically 256K). The
  709: @i{size} specification for this and subsequent options consists of
  710: an integer and a unit (e.g.,
  711: @code{4M}). The unit can be one of @code{b} (bytes), @code{e} (element
  712: size, in this case Cells), @code{k} (kilobytes), @code{M} (Megabytes),
  713: @code{G} (Gigabytes), and @code{T} (Terabytes). If no unit is specified,
  714: @code{e} is used.
  715: 
  716: @cindex --data-stack-size, command-line option
  717: @cindex -d, command-line option
  718: @item --data-stack-size @i{size}
  719: @itemx -d @i{size}
  720: Allocate @i{size} space for the data stack instead of using the
  721: default specified in the image (typically 16K).
  722: 
  723: @cindex --return-stack-size, command-line option
  724: @cindex -r, command-line option
  725: @item --return-stack-size @i{size}
  726: @itemx -r @i{size}
  727: Allocate @i{size} space for the return stack instead of using the
  728: default specified in the image (typically 15K).
  729: 
  730: @cindex --fp-stack-size, command-line option
  731: @cindex -f, command-line option
  732: @item --fp-stack-size @i{size}
  733: @itemx -f @i{size}
  734: Allocate @i{size} space for the floating point stack instead of
  735: using the default specified in the image (typically 15.5K). In this case
  736: the unit specifier @code{e} refers to floating point numbers.
  737: 
  738: @cindex --locals-stack-size, command-line option
  739: @cindex -l, command-line option
  740: @item --locals-stack-size @i{size}
  741: @itemx -l @i{size}
  742: Allocate @i{size} space for the locals stack instead of using the
  743: default specified in the image (typically 14.5K).
  744: 
  745: @cindex --vm-commit, command-line option
  746: @cindex overcommit memory for dictionary and stacks
  747: @cindex memory overcommit for dictionary and stacks
  748: @item --vm-commit
  749: Normally, Gforth tries to start up even if there is not enough virtual
  750: memory for the dictionary and the stacks (using @code{MAP_NORESERVE}
  751: on OSs that support it); so you can ask for a really big dictionary
  752: and/or stacks, and as long as you don't use more virtual memory than
  753: is available, everything will be fine (but if you use more, processes
  754: get killed).  With this option you just use the default allocation
  755: policy of the OS; for OSs that don't overcommit (e.g., Solaris), this
  756: means that you cannot and should not ask for as big dictionary and
  757: stacks, but once Gforth successfully starts up, out-of-memory won't
  758: kill it.
  759: 
  760: @cindex -h, command-line option
  761: @cindex --help, command-line option
  762: @item --help
  763: @itemx -h
  764: Print a message about the command-line options
  765: 
  766: @cindex -v, command-line option
  767: @cindex --version, command-line option
  768: @item --version
  769: @itemx -v
  770: Print version and exit
  771: 
  772: @cindex --debug, command-line option
  773: @item --debug
  774: Print some information useful for debugging on startup.
  775: 
  776: @cindex --offset-image, command-line option
  777: @item --offset-image
  778: Start the dictionary at a slightly different position than would be used
  779: otherwise (useful for creating data-relocatable images,
  780: @pxref{Data-Relocatable Image Files}).
  781: 
  782: @cindex --no-offset-im, command-line option
  783: @item --no-offset-im
  784: Start the dictionary at the normal position.
  785: 
  786: @cindex --clear-dictionary, command-line option
  787: @item --clear-dictionary
  788: Initialize all bytes in the dictionary to 0 before loading the image
  789: (@pxref{Data-Relocatable Image Files}).
  790: 
  791: @cindex --die-on-signal, command-line-option
  792: @item --die-on-signal
  793: Normally Gforth handles most signals (e.g., the user interrupt SIGINT,
  794: or the segmentation violation SIGSEGV) by translating it into a Forth
  795: @code{THROW}. With this option, Gforth exits if it receives such a
  796: signal. This option is useful when the engine and/or the image might be
  797: severely broken (such that it causes another signal before recovering
  798: from the first); this option avoids endless loops in such cases.
  799: 
  800: @cindex --no-dynamic, command-line option
  801: @cindex --dynamic, command-line option
  802: @item --no-dynamic
  803: @item --dynamic
  804: Disable or enable dynamic superinstructions with replication
  805: (@pxref{Dynamic Superinstructions}).
  806: 
  807: @cindex --no-super, command-line option
  808: @item --no-super
  809: Disable dynamic superinstructions, use just dynamic replication; this is
  810: useful if you want to patch threaded code (@pxref{Dynamic
  811: Superinstructions}).
  812: 
  813: @cindex --ss-number, command-line option
  814: @item --ss-number=@var{N}
  815: Use only the first @var{N} static superinstructions compiled into the
  816: engine (default: use them all; note that only @code{gforth-fast} has
  817: any).  This option is useful for measuring the performance impact of
  818: static superinstructions.
  819: 
  820: @cindex --ss-min-..., command-line options
  821: @item --ss-min-codesize
  822: @item --ss-min-ls
  823: @item --ss-min-lsu
  824: @item --ss-min-nexts
  825: Use specified metric for determining the cost of a primitive or static
  826: superinstruction for static superinstruction selection.  @code{Codesize}
  827: is the native code size of the primive or static superinstruction,
  828: @code{ls} is the number of loads and stores, @code{lsu} is the number of
  829: loads, stores, and updates, and @code{nexts} is the number of dispatches
  830: (not taking dynamic superinstructions into account), i.e. every
  831: primitive or static superinstruction has cost 1. Default:
  832: @code{codesize} if you use dynamic code generation, otherwise
  833: @code{nexts}.
  834: 
  835: @cindex --ss-greedy, command-line option
  836: @item --ss-greedy
  837: This option is useful for measuring the performance impact of static
  838: superinstructions.  By default, an optimal shortest-path algorithm is
  839: used for selecting static superinstructions.  With @option{--ss-greedy}
  840: this algorithm is modified to assume that anything after the static
  841: superinstruction currently under consideration is not combined into
  842: static superinstructions.  With @option{--ss-min-nexts} this produces
  843: the same result as a greedy algorithm that always selects the longest
  844: superinstruction available at the moment.  E.g., if there are
  845: superinstructions AB and BCD, then for the sequence A B C D the optimal
  846: algorithm will select A BCD and the greedy algorithm will select AB C D.
  847: 
  848: @cindex --print-metrics, command-line option
  849: @item --print-metrics
  850: Prints some metrics used during static superinstruction selection:
  851: @code{code size} is the actual size of the dynamically generated code.
  852: @code{Metric codesize} is the sum of the codesize metrics as seen by
  853: static superinstruction selection; there is a difference from @code{code
  854: size}, because not all primitives and static superinstructions are
  855: compiled into dynamically generated code, and because of markers.  The
  856: other metrics correspond to the @option{ss-min-...} options.  This
  857: option is useful for evaluating the effects of the @option{--ss-...}
  858: options.
  859: 
  860: @end table
  861: 
  862: @cindex loading files at startup
  863: @cindex executing code on startup
  864: @cindex batch processing with Gforth
  865: As explained above, the image-specific command-line arguments for the
  866: default image @file{gforth.fi} consist of a sequence of filenames and
  867: @code{-e @var{forth-code}} options that are interpreted in the sequence
  868: in which they are given. The @code{-e @var{forth-code}} or
  869: @code{--evaluate @var{forth-code}} option evaluates the Forth code. This
  870: option takes only one argument; if you want to evaluate more Forth
  871: words, you have to quote them or use @code{-e} several times. To exit
  872: after processing the command line (instead of entering interactive mode)
  873: append @code{-e bye} to the command line.  You can also process the
  874: command-line arguments with a Forth program (@pxref{OS command line
  875: arguments}).
  876: 
  877: @cindex versions, invoking other versions of Gforth
  878: If you have several versions of Gforth installed, @code{gforth} will
  879: invoke the version that was installed last. @code{gforth-@i{version}}
  880: invokes a specific version. If your environment contains the variable
  881: @code{GFORTHPATH}, you may want to override it by using the
  882: @code{--path} option.
  883: 
  884: Not yet implemented:
  885: On startup the system first executes the system initialization file
  886: (unless the option @code{--no-init-file} is given; note that the system
  887: resulting from using this option may not be ANS Forth conformant). Then
  888: the user initialization file @file{.gforth.fs} is executed, unless the
  889: option @code{--no-rc} is given; this file is searched for in @file{.},
  890: then in @file{~}, then in the normal path (see above).
  891: 
  892: 
  893: 
  894: @comment ----------------------------------------------
  895: @node Leaving Gforth, Command-line editing, Invoking Gforth, Gforth Environment
  896: @section Leaving Gforth
  897: @cindex Gforth - leaving
  898: @cindex leaving Gforth
  899: 
  900: You can leave Gforth by typing @code{bye} or @kbd{Ctrl-d} (at the start
  901: of a line) or (if you invoked Gforth with the @code{--die-on-signal}
  902: option) @kbd{Ctrl-c}. When you leave Gforth, all of your definitions and
  903: data are discarded.  For ways of saving the state of the system before
  904: leaving Gforth see @ref{Image Files}.
  905: 
  906: doc-bye
  907: 
  908: 
  909: @comment ----------------------------------------------
  910: @node Command-line editing, Environment variables, Leaving Gforth, Gforth Environment
  911: @section Command-line editing
  912: @cindex command-line editing
  913: 
  914: Gforth maintains a history file that records every line that you type to
  915: the text interpreter. This file is preserved between sessions, and is
  916: used to provide a command-line recall facility; if you type @kbd{Ctrl-P}
  917: repeatedly you can recall successively older commands from this (or
  918: previous) session(s). The full list of command-line editing facilities is:
  919: 
  920: @itemize @bullet
  921: @item
  922: @kbd{Ctrl-p} (``previous'') (or up-arrow) to recall successively older
  923: commands from the history buffer.
  924: @item
  925: @kbd{Ctrl-n} (``next'') (or down-arrow) to recall successively newer commands
  926: from the history buffer.
  927: @item
  928: @kbd{Ctrl-f} (or right-arrow) to move the cursor right, non-destructively.
  929: @item
  930: @kbd{Ctrl-b} (or left-arrow) to move the cursor left, non-destructively.
  931: @item
  932: @kbd{Ctrl-h} (backspace) to delete the character to the left of the cursor,
  933: closing up the line.
  934: @item
  935: @kbd{Ctrl-k} to delete (``kill'') from the cursor to the end of the line.
  936: @item
  937: @kbd{Ctrl-a} to move the cursor to the start of the line.
  938: @item
  939: @kbd{Ctrl-e} to move the cursor to the end of the line.
  940: @item
  941: @key{RET} (@kbd{Ctrl-m}) or @key{LFD} (@kbd{Ctrl-j}) to submit the current
  942: line.
  943: @item
  944: @key{TAB} to step through all possible full-word completions of the word
  945: currently being typed.
  946: @item
  947: @kbd{Ctrl-d} on an empty line line to terminate Gforth (gracefully,
  948: using @code{bye}). 
  949: @item
  950: @kbd{Ctrl-x} (or @code{Ctrl-d} on a non-empty line) to delete the
  951: character under the cursor.
  952: @end itemize
  953: 
  954: When editing, displayable characters are inserted to the left of the
  955: cursor position; the line is always in ``insert'' (as opposed to
  956: ``overstrike'') mode.
  957: 
  958: @cindex history file
  959: @cindex @file{.gforth-history}
  960: On Unix systems, the history file is @file{~/.gforth-history} by
  961: default@footnote{i.e. it is stored in the user's home directory.}. You
  962: can find out the name and location of your history file using:
  963: 
  964: @example 
  965: history-file type \ Unix-class systems
  966: 
  967: history-file type \ Other systems
  968: history-dir  type
  969: @end example
  970: 
  971: If you enter long definitions by hand, you can use a text editor to
  972: paste them out of the history file into a Forth source file for reuse at
  973: a later time.
  974: 
  975: Gforth never trims the size of the history file, so you should do this
  976: periodically, if necessary.
  977: 
  978: @comment this is all defined in history.fs
  979: @comment NAC TODO the ctrl-D behaviour can either do a bye or a beep.. how is that option
  980: @comment chosen?
  981: 
  982: 
  983: @comment ----------------------------------------------
  984: @node Environment variables, Gforth Files, Command-line editing, Gforth Environment
  985: @section Environment variables
  986: @cindex environment variables
  987: 
  988: Gforth uses these environment variables:
  989: 
  990: @itemize @bullet
  991: @item
  992: @cindex @code{GFORTHHIST} -- environment variable
  993: @code{GFORTHHIST} -- (Unix systems only) specifies the directory in which to
  994: open/create the history file, @file{.gforth-history}. Default:
  995: @code{$HOME}.
  996: 
  997: @item
  998: @cindex @code{GFORTHPATH} -- environment variable
  999: @code{GFORTHPATH} -- specifies the path used when searching for the gforth image file and
 1000: for Forth source-code files.
 1001: 
 1002: @item
 1003: @cindex @code{LANG} -- environment variable
 1004: @code{LANG} -- see @code{LC_CTYPE}
 1005: 
 1006: @item
 1007: @cindex @code{LC_ALL} -- environment variable
 1008: @code{LC_ALL} -- see @code{LC_CTYPE}
 1009: 
 1010: @item
 1011: @cindex @code{LC_CTYPE} -- environment variable
 1012: @code{LC_CTYPE} -- If this variable contains ``UTF-8'' on Gforth
 1013: startup, Gforth uses the UTF-8 encoding for strings internally and
 1014: expects its input and produces its output in UTF-8 encoding, otherwise
 1015: the encoding is 8bit (see @pxref{Xchars and Unicode}).  If this
 1016: environment variable is unset, Gforth looks in @code{LC_ALL}, and if
 1017: that is unset, in @code{LANG}.
 1018: 
 1019: @item
 1020: @cindex @code{GFORTHSYSTEMPREFIX} -- environment variable
 1021: 
 1022: @code{GFORTHSYSTEMPREFIX} -- specifies what to prepend to the argument
 1023: of @code{system} before passing it to C's @code{system()}.  Default:
 1024: @code{"./$COMSPEC /c "} on Windows, @code{""} on other OSs.  The prefix
 1025: and the command are directly concatenated, so if a space between them is
 1026: necessary, append it to the prefix.
 1027: 
 1028: @item
 1029: @cindex @code{GFORTH} -- environment variable
 1030: @code{GFORTH} -- used by @file{gforthmi}, @xref{gforthmi}.
 1031: 
 1032: @item
 1033: @cindex @code{GFORTHD} -- environment variable
 1034: @code{GFORTHD} -- used by @file{gforthmi}, @xref{gforthmi}.
 1035: 
 1036: @item
 1037: @cindex @code{TMP}, @code{TEMP} - environment variable
 1038: @code{TMP}, @code{TEMP} - (non-Unix systems only) used as a potential
 1039: location for the history file.
 1040: @end itemize
 1041: 
 1042: @comment also POSIXELY_CORRECT LINES COLUMNS HOME but no interest in
 1043: @comment mentioning these.
 1044: 
 1045: All the Gforth environment variables default to sensible values if they
 1046: are not set.
 1047: 
 1048: 
 1049: @comment ----------------------------------------------
 1050: @node Gforth Files, Gforth in pipes, Environment variables, Gforth Environment
 1051: @section Gforth files
 1052: @cindex Gforth files
 1053: 
 1054: When you install Gforth on a Unix system, it installs files in these
 1055: locations by default:
 1056: 
 1057: @itemize @bullet
 1058: @item
 1059: @file{/usr/local/bin/gforth}
 1060: @item
 1061: @file{/usr/local/bin/gforthmi}
 1062: @item
 1063: @file{/usr/local/man/man1/gforth.1} - man page.
 1064: @item
 1065: @file{/usr/local/info} - the Info version of this manual.
 1066: @item
 1067: @file{/usr/local/lib/gforth/<version>/...} - Gforth @file{.fi} files.
 1068: @item
 1069: @file{/usr/local/share/gforth/<version>/TAGS} - Emacs TAGS file.
 1070: @item
 1071: @file{/usr/local/share/gforth/<version>/...} - Gforth source files.
 1072: @item
 1073: @file{.../emacs/site-lisp/gforth.el} - Emacs gforth mode.
 1074: @end itemize
 1075: 
 1076: You can select different places for installation by using
 1077: @code{configure} options (listed with @code{configure --help}).
 1078: 
 1079: @comment ----------------------------------------------
 1080: @node Gforth in pipes, Startup speed, Gforth Files, Gforth Environment
 1081: @section Gforth in pipes
 1082: @cindex pipes, Gforth as part of
 1083: 
 1084: Gforth can be used in pipes created elsewhere (described here).  It can
 1085: also create pipes on its own (@pxref{Pipes}).
 1086: 
 1087: @cindex input from pipes
 1088: If you pipe into Gforth, your program should read with @code{read-file}
 1089: or @code{read-line} from @code{stdin} (@pxref{General files}).
 1090: @code{Key} does not recognize the end of input.  Words like
 1091: @code{accept} echo the input and are therefore usually not useful for
 1092: reading from a pipe.  You have to invoke the Forth program with an OS
 1093: command-line option, as you have no chance to use the Forth command line
 1094: (the text interpreter would try to interpret the pipe input).
 1095: 
 1096: @cindex output in pipes
 1097: You can output to a pipe with @code{type}, @code{emit}, @code{cr} etc.
 1098: 
 1099: @cindex silent exiting from Gforth
 1100: When you write to a pipe that has been closed at the other end, Gforth
 1101: receives a SIGPIPE signal (``pipe broken'').  Gforth translates this
 1102: into the exception @code{broken-pipe-error}.  If your application does
 1103: not catch that exception, the system catches it and exits, usually
 1104: silently (unless you were working on the Forth command line; then it
 1105: prints an error message and exits).  This is usually the desired
 1106: behaviour.
 1107: 
 1108: If you do not like this behaviour, you have to catch the exception
 1109: yourself, and react to it.
 1110: 
 1111: Here's an example of an invocation of Gforth that is usable in a pipe:
 1112: 
 1113: @example
 1114: gforth -e ": foo begin pad dup 10 stdin read-file throw dup while \
 1115:  type repeat ; foo bye"
 1116: @end example
 1117: 
 1118: This example just copies the input verbatim to the output.  A very
 1119: simple pipe containing this example looks like this:
 1120: 
 1121: @example
 1122: cat startup.fs |
 1123: gforth -e ": foo begin pad dup 80 stdin read-file throw dup while \
 1124:  type repeat ; foo bye"|
 1125: head
 1126: @end example
 1127: 
 1128: @cindex stderr and pipes
 1129: Pipes involving Gforth's @code{stderr} output do not work.
 1130: 
 1131: @comment ----------------------------------------------
 1132: @node Startup speed,  , Gforth in pipes, Gforth Environment
 1133: @section Startup speed
 1134: @cindex Startup speed
 1135: @cindex speed, startup
 1136: 
 1137: If Gforth is used for CGI scripts or in shell scripts, its startup
 1138: speed may become a problem.  On a 300MHz 21064a under Linux-2.2.13 with
 1139: glibc-2.0.7, @code{gforth -e bye} takes about 24.6ms user and 11.3ms
 1140: system time.
 1141: 
 1142: If startup speed is a problem, you may consider the following ways to
 1143: improve it; or you may consider ways to reduce the number of startups
 1144: (for example, by using Fast-CGI).
 1145: 
 1146: An easy step that influences Gforth startup speed is the use of the
 1147: @option{--no-dynamic} option; this decreases image loading speed, but
 1148: increases compile-time and run-time.
 1149: 
 1150: Another step to improve startup speed is to statically link Gforth, by
 1151: building it with @code{XLDFLAGS=-static}.  This requires more memory for
 1152: the code and will therefore slow down the first invocation, but
 1153: subsequent invocations avoid the dynamic linking overhead.  Another
 1154: disadvantage is that Gforth won't profit from library upgrades.  As a
 1155: result, @code{gforth-static -e bye} takes about 17.1ms user and
 1156: 8.2ms system time.
 1157: 
 1158: The next step to improve startup speed is to use a non-relocatable image
 1159: (@pxref{Non-Relocatable Image Files}).  You can create this image with
 1160: @code{gforth -e "savesystem gforthnr.fi bye"} and later use it with
 1161: @code{gforth -i gforthnr.fi ...}.  This avoids the relocation overhead
 1162: and a part of the copy-on-write overhead.  The disadvantage is that the
 1163: non-relocatable image does not work if the OS gives Gforth a different
 1164: address for the dictionary, for whatever reason; so you better provide a
 1165: fallback on a relocatable image.  @code{gforth-static -i gforthnr.fi -e
 1166: bye} takes about 15.3ms user and 7.5ms system time.
 1167: 
 1168: The final step is to disable dictionary hashing in Gforth.  Gforth
 1169: builds the hash table on startup, which takes much of the startup
 1170: overhead. You can do this by commenting out the @code{include hash.fs}
 1171: in @file{startup.fs} and everything that requires @file{hash.fs} (at the
 1172: moment @file{table.fs} and @file{ekey.fs}) and then doing @code{make}.
 1173: The disadvantages are that functionality like @code{table} and
 1174: @code{ekey} is missing and that text interpretation (e.g., compiling)
 1175: now takes much longer. So, you should only use this method if there is
 1176: no significant text interpretation to perform (the script should be
 1177: compiled into the image, amongst other things).  @code{gforth-static -i
 1178: gforthnrnh.fi -e bye} takes about 2.1ms user and 6.1ms system time.
 1179: 
 1180: @c ******************************************************************
 1181: @node Tutorial, Introduction, Gforth Environment, Top
 1182: @chapter Forth Tutorial
 1183: @cindex Tutorial
 1184: @cindex Forth Tutorial
 1185: 
 1186: @c Topics from nac's Introduction that could be mentioned:
 1187: @c press <ret> after each line
 1188: @c Prompt
 1189: @c numbers vs. words in dictionary on text interpretation
 1190: @c what happens on redefinition
 1191: @c parsing words (in particular, defining words)
 1192: 
 1193: The difference of this chapter from the Introduction
 1194: (@pxref{Introduction}) is that this tutorial is more fast-paced, should
 1195: be used while sitting in front of a computer, and covers much more
 1196: material, but does not explain how the Forth system works.
 1197: 
 1198: This tutorial can be used with any ANS-compliant Forth; any
 1199: Gforth-specific features are marked as such and you can skip them if you
 1200: work with another Forth.  This tutorial does not explain all features of
 1201: Forth, just enough to get you started and give you some ideas about the
 1202: facilities available in Forth.  Read the rest of the manual and the
 1203: standard when you are through this.
 1204: 
 1205: The intended way to use this tutorial is that you work through it while
 1206: sitting in front of the console, take a look at the examples and predict
 1207: what they will do, then try them out; if the outcome is not as expected,
 1208: find out why (e.g., by trying out variations of the example), so you
 1209: understand what's going on.  There are also some assignments that you
 1210: should solve.
 1211: 
 1212: This tutorial assumes that you have programmed before and know what,
 1213: e.g., a loop is.
 1214: 
 1215: @c !! explain compat library
 1216: 
 1217: @menu
 1218: * Starting Gforth Tutorial::    
 1219: * Syntax Tutorial::             
 1220: * Crash Course Tutorial::       
 1221: * Stack Tutorial::              
 1222: * Arithmetics Tutorial::        
 1223: * Stack Manipulation Tutorial::  
 1224: * Using files for Forth code Tutorial::  
 1225: * Comments Tutorial::           
 1226: * Colon Definitions Tutorial::  
 1227: * Decompilation Tutorial::      
 1228: * Stack-Effect Comments Tutorial::  
 1229: * Types Tutorial::              
 1230: * Factoring Tutorial::          
 1231: * Designing the stack effect Tutorial::  
 1232: * Local Variables Tutorial::    
 1233: * Conditional execution Tutorial::  
 1234: * Flags and Comparisons Tutorial::  
 1235: * General Loops Tutorial::      
 1236: * Counted loops Tutorial::      
 1237: * Recursion Tutorial::          
 1238: * Leaving definitions or loops Tutorial::  
 1239: * Return Stack Tutorial::       
 1240: * Memory Tutorial::             
 1241: * Characters and Strings Tutorial::  
 1242: * Alignment Tutorial::          
 1243: * Files Tutorial::              
 1244: * Interpretation and Compilation Semantics and Immediacy Tutorial::  
 1245: * Execution Tokens Tutorial::   
 1246: * Exceptions Tutorial::         
 1247: * Defining Words Tutorial::     
 1248: * Arrays and Records Tutorial::  
 1249: * POSTPONE Tutorial::           
 1250: * Literal Tutorial::            
 1251: * Advanced macros Tutorial::    
 1252: * Compilation Tokens Tutorial::  
 1253: * Wordlists and Search Order Tutorial::  
 1254: @end menu
 1255: 
 1256: @node Starting Gforth Tutorial, Syntax Tutorial, Tutorial, Tutorial
 1257: @section Starting Gforth
 1258: @cindex starting Gforth tutorial
 1259: You can start Gforth by typing its name:
 1260: 
 1261: @example
 1262: gforth
 1263: @end example
 1264: 
 1265: That puts you into interactive mode; you can leave Gforth by typing
 1266: @code{bye}.  While in Gforth, you can edit the command line and access
 1267: the command line history with cursor keys, similar to bash.
 1268: 
 1269: 
 1270: @node Syntax Tutorial, Crash Course Tutorial, Starting Gforth Tutorial, Tutorial
 1271: @section Syntax
 1272: @cindex syntax tutorial
 1273: 
 1274: A @dfn{word} is a sequence of arbitrary characters (except white
 1275: space).  Words are separated by white space.  E.g., each of the
 1276: following lines contains exactly one word:
 1277: 
 1278: @example
 1279: word
 1280: !@@#$%^&*()
 1281: 1234567890
 1282: 5!a
 1283: @end example
 1284: 
 1285: A frequent beginner's error is to leave away necessary white space,
 1286: resulting in an error like @samp{Undefined word}; so if you see such an
 1287: error, check if you have put spaces wherever necessary.
 1288: 
 1289: @example
 1290: ." hello, world" \ correct
 1291: ."hello, world"  \ gives an "Undefined word" error
 1292: @end example
 1293: 
 1294: Gforth and most other Forth systems ignore differences in case (they are
 1295: case-insensitive), i.e., @samp{word} is the same as @samp{Word}.  If
 1296: your system is case-sensitive, you may have to type all the examples
 1297: given here in upper case.
 1298: 
 1299: 
 1300: @node Crash Course Tutorial, Stack Tutorial, Syntax Tutorial, Tutorial
 1301: @section Crash Course
 1302: 
 1303: Type
 1304: 
 1305: @example
 1306: 0 0 !
 1307: here execute
 1308: ' catch >body 20 erase abort
 1309: ' (quit) >body 20 erase
 1310: @end example
 1311: 
 1312: The last two examples are guaranteed to destroy parts of Gforth (and
 1313: most other systems), so you better leave Gforth afterwards (if it has
 1314: not finished by itself).  On some systems you may have to kill gforth
 1315: from outside (e.g., in Unix with @code{kill}).
 1316: 
 1317: Now that you know how to produce crashes (and that there's not much to
 1318: them), let's learn how to produce meaningful programs.
 1319: 
 1320: 
 1321: @node Stack Tutorial, Arithmetics Tutorial, Crash Course Tutorial, Tutorial
 1322: @section Stack
 1323: @cindex stack tutorial
 1324: 
 1325: The most obvious feature of Forth is the stack.  When you type in a
 1326: number, it is pushed on the stack.  You can display the content of the
 1327: stack with @code{.s}.
 1328: 
 1329: @example
 1330: 1 2 .s
 1331: 3 .s
 1332: @end example
 1333: 
 1334: @code{.s} displays the top-of-stack to the right, i.e., the numbers
 1335: appear in @code{.s} output as they appeared in the input.
 1336: 
 1337: You can print the top of stack element with @code{.}.
 1338: 
 1339: @example
 1340: 1 2 3 . . .
 1341: @end example
 1342: 
 1343: In general, words consume their stack arguments (@code{.s} is an
 1344: exception).
 1345: 
 1346: @quotation Assignment
 1347: What does the stack contain after @code{5 6 7 .}?
 1348: @end quotation
 1349: 
 1350: 
 1351: @node Arithmetics Tutorial, Stack Manipulation Tutorial, Stack Tutorial, Tutorial
 1352: @section Arithmetics
 1353: @cindex arithmetics tutorial
 1354: 
 1355: The words @code{+}, @code{-}, @code{*}, @code{/}, and @code{mod} always
 1356: operate on the top two stack items:
 1357: 
 1358: @example
 1359: 2 2 .s
 1360: + .s
 1361: .
 1362: 2 1 - .
 1363: 7 3 mod .
 1364: @end example
 1365: 
 1366: The operands of @code{-}, @code{/}, and @code{mod} are in the same order
 1367: as in the corresponding infix expression (this is generally the case in
 1368: Forth).
 1369: 
 1370: Parentheses are superfluous (and not available), because the order of
 1371: the words unambiguously determines the order of evaluation and the
 1372: operands:
 1373: 
 1374: @example
 1375: 3 4 + 5 * .
 1376: 3 4 5 * + .
 1377: @end example
 1378: 
 1379: @quotation Assignment
 1380: What are the infix expressions corresponding to the Forth code above?
 1381: Write @code{6-7*8+9} in Forth notation@footnote{This notation is also
 1382: known as Postfix or RPN (Reverse Polish Notation).}.
 1383: @end quotation
 1384: 
 1385: To change the sign, use @code{negate}:
 1386: 
 1387: @example
 1388: 2 negate .
 1389: @end example
 1390: 
 1391: @quotation Assignment
 1392: Convert -(-3)*4-5 to Forth.
 1393: @end quotation
 1394: 
 1395: @code{/mod} performs both @code{/} and @code{mod}.
 1396: 
 1397: @example
 1398: 7 3 /mod . .
 1399: @end example
 1400: 
 1401: Reference: @ref{Arithmetic}.
 1402: 
 1403: 
 1404: @node Stack Manipulation Tutorial, Using files for Forth code Tutorial, Arithmetics Tutorial, Tutorial
 1405: @section Stack Manipulation
 1406: @cindex stack manipulation tutorial
 1407: 
 1408: Stack manipulation words rearrange the data on the stack.
 1409: 
 1410: @example
 1411: 1 .s drop .s
 1412: 1 .s dup .s drop drop .s
 1413: 1 2 .s over .s drop drop drop
 1414: 1 2 .s swap .s drop drop
 1415: 1 2 3 .s rot .s drop drop drop
 1416: @end example
 1417: 
 1418: These are the most important stack manipulation words.  There are also
 1419: variants that manipulate twice as many stack items:
 1420: 
 1421: @example
 1422: 1 2 3 4 .s 2swap .s 2drop 2drop
 1423: @end example
 1424: 
 1425: Two more stack manipulation words are:
 1426: 
 1427: @example
 1428: 1 2 .s nip .s drop
 1429: 1 2 .s tuck .s 2drop drop
 1430: @end example
 1431: 
 1432: @quotation Assignment
 1433: Replace @code{nip} and @code{tuck} with combinations of other stack
 1434: manipulation words.
 1435: 
 1436: @example
 1437: Given:          How do you get:
 1438: 1 2 3           3 2 1           
 1439: 1 2 3           1 2 3 2                 
 1440: 1 2 3           1 2 3 3                 
 1441: 1 2 3           1 3 3           
 1442: 1 2 3           2 1 3           
 1443: 1 2 3 4         4 3 2 1         
 1444: 1 2 3           1 2 3 1 2 3             
 1445: 1 2 3 4         1 2 3 4 1 2             
 1446: 1 2 3
 1447: 1 2 3           1 2 3 4                 
 1448: 1 2 3           1 3             
 1449: @end example
 1450: @end quotation
 1451: 
 1452: @example
 1453: 5 dup * .
 1454: @end example
 1455: 
 1456: @quotation Assignment
 1457: Write 17^3 and 17^4 in Forth, without writing @code{17} more than once.
 1458: Write a piece of Forth code that expects two numbers on the stack
 1459: (@var{a} and @var{b}, with @var{b} on top) and computes
 1460: @code{(a-b)(a+1)}.
 1461: @end quotation
 1462: 
 1463: Reference: @ref{Stack Manipulation}.
 1464: 
 1465: 
 1466: @node Using files for Forth code Tutorial, Comments Tutorial, Stack Manipulation Tutorial, Tutorial
 1467: @section Using files for Forth code
 1468: @cindex loading Forth code, tutorial
 1469: @cindex files containing Forth code, tutorial
 1470: 
 1471: While working at the Forth command line is convenient for one-line
 1472: examples and short one-off code, you probably want to store your source
 1473: code in files for convenient editing and persistence.  You can use your
 1474: favourite editor (Gforth includes Emacs support, @pxref{Emacs and
 1475: Gforth}) to create @var{file.fs} and use
 1476: 
 1477: @example
 1478: s" @var{file.fs}" included
 1479: @end example
 1480: 
 1481: to load it into your Forth system.  The file name extension I use for
 1482: Forth files is @samp{.fs}.
 1483: 
 1484: You can easily start Gforth with some files loaded like this:
 1485: 
 1486: @example
 1487: gforth @var{file1.fs} @var{file2.fs}
 1488: @end example
 1489: 
 1490: If an error occurs during loading these files, Gforth terminates,
 1491: whereas an error during @code{INCLUDED} within Gforth usually gives you
 1492: a Gforth command line.  Starting the Forth system every time gives you a
 1493: clean start every time, without interference from the results of earlier
 1494: tries.
 1495: 
 1496: I often put all the tests in a file, then load the code and run the
 1497: tests with
 1498: 
 1499: @example
 1500: gforth @var{code.fs} @var{tests.fs} -e bye
 1501: @end example
 1502: 
 1503: (often by performing this command with @kbd{C-x C-e} in Emacs).  The
 1504: @code{-e bye} ensures that Gforth terminates afterwards so that I can
 1505: restart this command without ado.
 1506: 
 1507: The advantage of this approach is that the tests can be repeated easily
 1508: every time the program ist changed, making it easy to catch bugs
 1509: introduced by the change.
 1510: 
 1511: Reference: @ref{Forth source files}.
 1512: 
 1513: 
 1514: @node Comments Tutorial, Colon Definitions Tutorial, Using files for Forth code Tutorial, Tutorial
 1515: @section Comments
 1516: @cindex comments tutorial
 1517: 
 1518: @example
 1519: \ That's a comment; it ends at the end of the line
 1520: ( Another comment; it ends here: )  .s
 1521: @end example
 1522: 
 1523: @code{\} and @code{(} are ordinary Forth words and therefore have to be
 1524: separated with white space from the following text.
 1525: 
 1526: @example
 1527: \This gives an "Undefined word" error
 1528: @end example
 1529: 
 1530: The first @code{)} ends a comment started with @code{(}, so you cannot
 1531: nest @code{(}-comments; and you cannot comment out text containing a
 1532: @code{)} with @code{( ... )}@footnote{therefore it's a good idea to
 1533: avoid @code{)} in word names.}.
 1534: 
 1535: I use @code{\}-comments for descriptive text and for commenting out code
 1536: of one or more line; I use @code{(}-comments for describing the stack
 1537: effect, the stack contents, or for commenting out sub-line pieces of
 1538: code.
 1539: 
 1540: The Emacs mode @file{gforth.el} (@pxref{Emacs and Gforth}) supports
 1541: these uses by commenting out a region with @kbd{C-x \}, uncommenting a
 1542: region with @kbd{C-u C-x \}, and filling a @code{\}-commented region
 1543: with @kbd{M-q}.
 1544: 
 1545: Reference: @ref{Comments}.
 1546: 
 1547: 
 1548: @node Colon Definitions Tutorial, Decompilation Tutorial, Comments Tutorial, Tutorial
 1549: @section Colon Definitions
 1550: @cindex colon definitions, tutorial
 1551: @cindex definitions, tutorial
 1552: @cindex procedures, tutorial
 1553: @cindex functions, tutorial
 1554: 
 1555: are similar to procedures and functions in other programming languages.
 1556: 
 1557: @example
 1558: : squared ( n -- n^2 )
 1559:    dup * ;
 1560: 5 squared .
 1561: 7 squared .
 1562: @end example
 1563: 
 1564: @code{:} starts the colon definition; its name is @code{squared}.  The
 1565: following comment describes its stack effect.  The words @code{dup *}
 1566: are not executed, but compiled into the definition.  @code{;} ends the
 1567: colon definition.
 1568: 
 1569: The newly-defined word can be used like any other word, including using
 1570: it in other definitions:
 1571: 
 1572: @example
 1573: : cubed ( n -- n^3 )
 1574:    dup squared * ;
 1575: -5 cubed .
 1576: : fourth-power ( n -- n^4 )
 1577:    squared squared ;
 1578: 3 fourth-power .
 1579: @end example
 1580: 
 1581: @quotation Assignment
 1582: Write colon definitions for @code{nip}, @code{tuck}, @code{negate}, and
 1583: @code{/mod} in terms of other Forth words, and check if they work (hint:
 1584: test your tests on the originals first).  Don't let the
 1585: @samp{redefined}-Messages spook you, they are just warnings.
 1586: @end quotation
 1587: 
 1588: Reference: @ref{Colon Definitions}.
 1589: 
 1590: 
 1591: @node Decompilation Tutorial, Stack-Effect Comments Tutorial, Colon Definitions Tutorial, Tutorial
 1592: @section Decompilation
 1593: @cindex decompilation tutorial
 1594: @cindex see tutorial
 1595: 
 1596: You can decompile colon definitions with @code{see}:
 1597: 
 1598: @example
 1599: see squared
 1600: see cubed
 1601: @end example
 1602: 
 1603: In Gforth @code{see} shows you a reconstruction of the source code from
 1604: the executable code.  Informations that were present in the source, but
 1605: not in the executable code, are lost (e.g., comments).
 1606: 
 1607: You can also decompile the predefined words:
 1608: 
 1609: @example
 1610: see .
 1611: see +
 1612: @end example
 1613: 
 1614: 
 1615: @node Stack-Effect Comments Tutorial, Types Tutorial, Decompilation Tutorial, Tutorial
 1616: @section Stack-Effect Comments
 1617: @cindex stack-effect comments, tutorial
 1618: @cindex --, tutorial
 1619: By convention the comment after the name of a definition describes the
 1620: stack effect: The part in front of the @samp{--} describes the state of
 1621: the stack before the execution of the definition, i.e., the parameters
 1622: that are passed into the colon definition; the part behind the @samp{--}
 1623: is the state of the stack after the execution of the definition, i.e.,
 1624: the results of the definition.  The stack comment only shows the top
 1625: stack items that the definition accesses and/or changes.
 1626: 
 1627: You should put a correct stack effect on every definition, even if it is
 1628: just @code{( -- )}.  You should also add some descriptive comment to
 1629: more complicated words (I usually do this in the lines following
 1630: @code{:}).  If you don't do this, your code becomes unreadable (because
 1631: you have to work through every definition before you can understand
 1632: any).
 1633: 
 1634: @quotation Assignment
 1635: The stack effect of @code{swap} can be written like this: @code{x1 x2 --
 1636: x2 x1}.  Describe the stack effect of @code{-}, @code{drop}, @code{dup},
 1637: @code{over}, @code{rot}, @code{nip}, and @code{tuck}.  Hint: When you
 1638: are done, you can compare your stack effects to those in this manual
 1639: (@pxref{Word Index}).
 1640: @end quotation
 1641: 
 1642: Sometimes programmers put comments at various places in colon
 1643: definitions that describe the contents of the stack at that place (stack
 1644: comments); i.e., they are like the first part of a stack-effect
 1645: comment. E.g.,
 1646: 
 1647: @example
 1648: : cubed ( n -- n^3 )
 1649:    dup squared  ( n n^2 ) * ;
 1650: @end example
 1651: 
 1652: In this case the stack comment is pretty superfluous, because the word
 1653: is simple enough.  If you think it would be a good idea to add such a
 1654: comment to increase readability, you should also consider factoring the
 1655: word into several simpler words (@pxref{Factoring Tutorial,,
 1656: Factoring}), which typically eliminates the need for the stack comment;
 1657: however, if you decide not to refactor it, then having such a comment is
 1658: better than not having it.
 1659: 
 1660: The names of the stack items in stack-effect and stack comments in the
 1661: standard, in this manual, and in many programs specify the type through
 1662: a type prefix, similar to Fortran and Hungarian notation.  The most
 1663: frequent prefixes are:
 1664: 
 1665: @table @code
 1666: @item n
 1667: signed integer
 1668: @item u
 1669: unsigned integer
 1670: @item c
 1671: character
 1672: @item f
 1673: Boolean flags, i.e. @code{false} or @code{true}.
 1674: @item a-addr,a-
 1675: Cell-aligned address
 1676: @item c-addr,c-
 1677: Char-aligned address (note that a Char may have two bytes in Windows NT)
 1678: @item xt
 1679: Execution token, same size as Cell
 1680: @item w,x
 1681: Cell, can contain an integer or an address.  It usually takes 32, 64 or
 1682: 16 bits (depending on your platform and Forth system). A cell is more
 1683: commonly known as machine word, but the term @emph{word} already means
 1684: something different in Forth.
 1685: @item d
 1686: signed double-cell integer
 1687: @item ud
 1688: unsigned double-cell integer
 1689: @item r
 1690: Float (on the FP stack)
 1691: @end table
 1692: 
 1693: You can find a more complete list in @ref{Notation}.
 1694: 
 1695: @quotation Assignment
 1696: Write stack-effect comments for all definitions you have written up to
 1697: now.
 1698: @end quotation
 1699: 
 1700: 
 1701: @node Types Tutorial, Factoring Tutorial, Stack-Effect Comments Tutorial, Tutorial
 1702: @section Types
 1703: @cindex types tutorial
 1704: 
 1705: In Forth the names of the operations are not overloaded; so similar
 1706: operations on different types need different names; e.g., @code{+} adds
 1707: integers, and you have to use @code{f+} to add floating-point numbers.
 1708: The following prefixes are often used for related operations on
 1709: different types:
 1710: 
 1711: @table @code
 1712: @item (none)
 1713: signed integer
 1714: @item u
 1715: unsigned integer
 1716: @item c
 1717: character
 1718: @item d
 1719: signed double-cell integer
 1720: @item ud, du
 1721: unsigned double-cell integer
 1722: @item 2
 1723: two cells (not-necessarily double-cell numbers)
 1724: @item m, um
 1725: mixed single-cell and double-cell operations
 1726: @item f
 1727: floating-point (note that in stack comments @samp{f} represents flags,
 1728: and @samp{r} represents FP numbers).
 1729: @end table
 1730: 
 1731: If there are no differences between the signed and the unsigned variant
 1732: (e.g., for @code{+}), there is only the prefix-less variant.
 1733: 
 1734: Forth does not perform type checking, neither at compile time, nor at
 1735: run time.  If you use the wrong oeration, the data are interpreted
 1736: incorrectly:
 1737: 
 1738: @example
 1739: -1 u.
 1740: @end example
 1741: 
 1742: If you have only experience with type-checked languages until now, and
 1743: have heard how important type-checking is, don't panic!  In my
 1744: experience (and that of other Forthers), type errors in Forth code are
 1745: usually easy to find (once you get used to it), the increased vigilance
 1746: of the programmer tends to catch some harder errors in addition to most
 1747: type errors, and you never have to work around the type system, so in
 1748: most situations the lack of type-checking seems to be a win (projects to
 1749: add type checking to Forth have not caught on).
 1750: 
 1751: 
 1752: @node Factoring Tutorial, Designing the stack effect Tutorial, Types Tutorial, Tutorial
 1753: @section Factoring
 1754: @cindex factoring tutorial
 1755: 
 1756: If you try to write longer definitions, you will soon find it hard to
 1757: keep track of the stack contents.  Therefore, good Forth programmers
 1758: tend to write only short definitions (e.g., three lines).  The art of
 1759: finding meaningful short definitions is known as factoring (as in
 1760: factoring polynomials).
 1761: 
 1762: Well-factored programs offer additional advantages: smaller, more
 1763: general words, are easier to test and debug and can be reused more and
 1764: better than larger, specialized words.
 1765: 
 1766: So, if you run into difficulties with stack management, when writing
 1767: code, try to define meaningful factors for the word, and define the word
 1768: in terms of those.  Even if a factor contains only two words, it is
 1769: often helpful.
 1770: 
 1771: Good factoring is not easy, and it takes some practice to get the knack
 1772: for it; but even experienced Forth programmers often don't find the
 1773: right solution right away, but only when rewriting the program.  So, if
 1774: you don't come up with a good solution immediately, keep trying, don't
 1775: despair.
 1776: 
 1777: @c example !!
 1778: 
 1779: 
 1780: @node Designing the stack effect Tutorial, Local Variables Tutorial, Factoring Tutorial, Tutorial
 1781: @section Designing the stack effect
 1782: @cindex Stack effect design, tutorial
 1783: @cindex design of stack effects, tutorial
 1784: 
 1785: In other languages you can use an arbitrary order of parameters for a
 1786: function; and since there is only one result, you don't have to deal with
 1787: the order of results, either.
 1788: 
 1789: In Forth (and other stack-based languages, e.g., PostScript) the
 1790: parameter and result order of a definition is important and should be
 1791: designed well.  The general guideline is to design the stack effect such
 1792: that the word is simple to use in most cases, even if that complicates
 1793: the implementation of the word.  Some concrete rules are:
 1794: 
 1795: @itemize @bullet
 1796: 
 1797: @item
 1798: Words consume all of their parameters (e.g., @code{.}).
 1799: 
 1800: @item
 1801: If there is a convention on the order of parameters (e.g., from
 1802: mathematics or another programming language), stick with it (e.g.,
 1803: @code{-}).
 1804: 
 1805: @item
 1806: If one parameter usually requires only a short computation (e.g., it is
 1807: a constant), pass it on the top of the stack.  Conversely, parameters
 1808: that usually require a long sequence of code to compute should be passed
 1809: as the bottom (i.e., first) parameter.  This makes the code easier to
 1810: read, because the reader does not need to keep track of the bottom item
 1811: through a long sequence of code (or, alternatively, through stack
 1812: manipulations). E.g., @code{!} (store, @pxref{Memory}) expects the
 1813: address on top of the stack because it is usually simpler to compute
 1814: than the stored value (often the address is just a variable).
 1815: 
 1816: @item
 1817: Similarly, results that are usually consumed quickly should be returned
 1818: on the top of stack, whereas a result that is often used in long
 1819: computations should be passed as bottom result.  E.g., the file words
 1820: like @code{open-file} return the error code on the top of stack, because
 1821: it is usually consumed quickly by @code{throw}; moreover, the error code
 1822: has to be checked before doing anything with the other results.
 1823: 
 1824: @end itemize
 1825: 
 1826: These rules are just general guidelines, don't lose sight of the overall
 1827: goal to make the words easy to use.  E.g., if the convention rule
 1828: conflicts with the computation-length rule, you might decide in favour
 1829: of the convention if the word will be used rarely, and in favour of the
 1830: computation-length rule if the word will be used frequently (because
 1831: with frequent use the cost of breaking the computation-length rule would
 1832: be quite high, and frequent use makes it easier to remember an
 1833: unconventional order).
 1834: 
 1835: @c example !! structure package
 1836: 
 1837: 
 1838: @node Local Variables Tutorial, Conditional execution Tutorial, Designing the stack effect Tutorial, Tutorial
 1839: @section Local Variables
 1840: @cindex local variables, tutorial
 1841: 
 1842: You can define local variables (@emph{locals}) in a colon definition:
 1843: 
 1844: @example
 1845: : swap @{ a b -- b a @}
 1846:   b a ;
 1847: 1 2 swap .s 2drop
 1848: @end example
 1849: 
 1850: (If your Forth system does not support this syntax, include
 1851: @file{compat/anslocals.fs} first).
 1852: 
 1853: In this example @code{@{ a b -- b a @}} is the locals definition; it
 1854: takes two cells from the stack, puts the top of stack in @code{b} and
 1855: the next stack element in @code{a}.  @code{--} starts a comment ending
 1856: with @code{@}}.  After the locals definition, using the name of the
 1857: local will push its value on the stack.  You can leave the comment
 1858: part (@code{-- b a}) away:
 1859: 
 1860: @example
 1861: : swap ( x1 x2 -- x2 x1 )
 1862:   @{ a b @} b a ;
 1863: @end example
 1864: 
 1865: In Gforth you can have several locals definitions, anywhere in a colon
 1866: definition; in contrast, in a standard program you can have only one
 1867: locals definition per colon definition, and that locals definition must
 1868: be outside any control structure.
 1869: 
 1870: With locals you can write slightly longer definitions without running
 1871: into stack trouble.  However, I recommend trying to write colon
 1872: definitions without locals for exercise purposes to help you gain the
 1873: essential factoring skills.
 1874: 
 1875: @quotation Assignment
 1876: Rewrite your definitions until now with locals
 1877: @end quotation
 1878: 
 1879: Reference: @ref{Locals}.
 1880: 
 1881: 
 1882: @node Conditional execution Tutorial, Flags and Comparisons Tutorial, Local Variables Tutorial, Tutorial
 1883: @section Conditional execution
 1884: @cindex conditionals, tutorial
 1885: @cindex if, tutorial
 1886: 
 1887: In Forth you can use control structures only inside colon definitions.
 1888: An @code{if}-structure looks like this:
 1889: 
 1890: @example
 1891: : abs ( n1 -- +n2 )
 1892:     dup 0 < if
 1893:         negate
 1894:     endif ;
 1895: 5 abs .
 1896: -5 abs .
 1897: @end example
 1898: 
 1899: @code{if} takes a flag from the stack.  If the flag is non-zero (true),
 1900: the following code is performed, otherwise execution continues after the
 1901: @code{endif} (or @code{else}).  @code{<} compares the top two stack
 1902: elements and produces a flag:
 1903: 
 1904: @example
 1905: 1 2 < .
 1906: 2 1 < .
 1907: 1 1 < .
 1908: @end example
 1909: 
 1910: Actually the standard name for @code{endif} is @code{then}.  This
 1911: tutorial presents the examples using @code{endif}, because this is often
 1912: less confusing for people familiar with other programming languages
 1913: where @code{then} has a different meaning.  If your system does not have
 1914: @code{endif}, define it with
 1915: 
 1916: @example
 1917: : endif postpone then ; immediate
 1918: @end example
 1919: 
 1920: You can optionally use an @code{else}-part:
 1921: 
 1922: @example
 1923: : min ( n1 n2 -- n )
 1924:   2dup < if
 1925:     drop
 1926:   else
 1927:     nip
 1928:   endif ;
 1929: 2 3 min .
 1930: 3 2 min .
 1931: @end example
 1932: 
 1933: @quotation Assignment
 1934: Write @code{min} without @code{else}-part (hint: what's the definition
 1935: of @code{nip}?).
 1936: @end quotation
 1937: 
 1938: Reference: @ref{Selection}.
 1939: 
 1940: 
 1941: @node Flags and Comparisons Tutorial, General Loops Tutorial, Conditional execution Tutorial, Tutorial
 1942: @section Flags and Comparisons
 1943: @cindex flags tutorial
 1944: @cindex comparison tutorial
 1945: 
 1946: In a false-flag all bits are clear (0 when interpreted as integer).  In
 1947: a canonical true-flag all bits are set (-1 as a twos-complement signed
 1948: integer); in many contexts (e.g., @code{if}) any non-zero value is
 1949: treated as true flag.
 1950: 
 1951: @example
 1952: false .
 1953: true .
 1954: true hex u. decimal
 1955: @end example
 1956: 
 1957: Comparison words produce canonical flags:
 1958: 
 1959: @example
 1960: 1 1 = .
 1961: 1 0= .
 1962: 0 1 < .
 1963: 0 0 < .
 1964: -1 1 u< . \ type error, u< interprets -1 as large unsigned number
 1965: -1 1 < .
 1966: @end example
 1967: 
 1968: Gforth supports all combinations of the prefixes @code{0 u d d0 du f f0}
 1969: (or none) and the comparisons @code{= <> < > <= >=}.  Only a part of
 1970: these combinations are standard (for details see the standard,
 1971: @ref{Numeric comparison}, @ref{Floating Point} or @ref{Word Index}).
 1972: 
 1973: You can use @code{and or xor invert} as operations on canonical flags.
 1974: Actually they are bitwise operations:
 1975: 
 1976: @example
 1977: 1 2 and .
 1978: 1 2 or .
 1979: 1 3 xor .
 1980: 1 invert .
 1981: @end example
 1982: 
 1983: You can convert a zero/non-zero flag into a canonical flag with
 1984: @code{0<>} (and complement it on the way with @code{0=}).
 1985: 
 1986: @example
 1987: 1 0= .
 1988: 1 0<> .
 1989: @end example
 1990: 
 1991: You can use the all-bits-set feature of canonical flags and the bitwise
 1992: operation of the Boolean operations to avoid @code{if}s:
 1993: 
 1994: @example
 1995: : foo ( n1 -- n2 )
 1996:   0= if
 1997:     14
 1998:   else
 1999:     0
 2000:   endif ;
 2001: 0 foo .
 2002: 1 foo .
 2003: 
 2004: : foo ( n1 -- n2 )
 2005:   0= 14 and ;
 2006: 0 foo .
 2007: 1 foo .
 2008: @end example
 2009: 
 2010: @quotation Assignment
 2011: Write @code{min} without @code{if}.
 2012: @end quotation
 2013: 
 2014: For reference, see @ref{Boolean Flags}, @ref{Numeric comparison}, and
 2015: @ref{Bitwise operations}.
 2016: 
 2017: 
 2018: @node General Loops Tutorial, Counted loops Tutorial, Flags and Comparisons Tutorial, Tutorial
 2019: @section General Loops
 2020: @cindex loops, indefinite, tutorial
 2021: 
 2022: The endless loop is the most simple one:
 2023: 
 2024: @example
 2025: : endless ( -- )
 2026:   0 begin
 2027:     dup . 1+
 2028:   again ;
 2029: endless
 2030: @end example
 2031: 
 2032: Terminate this loop by pressing @kbd{Ctrl-C} (in Gforth).  @code{begin}
 2033: does nothing at run-time, @code{again} jumps back to @code{begin}.
 2034: 
 2035: A loop with one exit at any place looks like this:
 2036: 
 2037: @example
 2038: : log2 ( +n1 -- n2 )
 2039: \ logarithmus dualis of n1>0, rounded down to the next integer
 2040:   assert( dup 0> )
 2041:   2/ 0 begin
 2042:     over 0> while
 2043:       1+ swap 2/ swap
 2044:   repeat
 2045:   nip ;
 2046: 7 log2 .
 2047: 8 log2 .
 2048: @end example
 2049: 
 2050: At run-time @code{while} consumes a flag; if it is 0, execution
 2051: continues behind the @code{repeat}; if the flag is non-zero, execution
 2052: continues behind the @code{while}.  @code{Repeat} jumps back to
 2053: @code{begin}, just like @code{again}.
 2054: 
 2055: In Forth there are many combinations/abbreviations, like @code{1+}.
 2056: However, @code{2/} is not one of them; it shifts its argument right by
 2057: one bit (arithmetic shift right):
 2058: 
 2059: @example
 2060: -5 2 / .
 2061: -5 2/ .
 2062: @end example
 2063: 
 2064: @code{assert(} is no standard word, but you can get it on systems other
 2065: then Gforth by including @file{compat/assert.fs}.  You can see what it
 2066: does by trying
 2067: 
 2068: @example
 2069: 0 log2 .
 2070: @end example
 2071: 
 2072: Here's a loop with an exit at the end:
 2073: 
 2074: @example
 2075: : log2 ( +n1 -- n2 )
 2076: \ logarithmus dualis of n1>0, rounded down to the next integer
 2077:   assert( dup 0 > )
 2078:   -1 begin
 2079:     1+ swap 2/ swap
 2080:     over 0 <=
 2081:   until
 2082:   nip ;
 2083: @end example
 2084: 
 2085: @code{Until} consumes a flag; if it is non-zero, execution continues at
 2086: the @code{begin}, otherwise after the @code{until}.
 2087: 
 2088: @quotation Assignment
 2089: Write a definition for computing the greatest common divisor.
 2090: @end quotation
 2091: 
 2092: Reference: @ref{Simple Loops}.
 2093: 
 2094: 
 2095: @node Counted loops Tutorial, Recursion Tutorial, General Loops Tutorial, Tutorial
 2096: @section Counted loops
 2097: @cindex loops, counted, tutorial
 2098: 
 2099: @example
 2100: : ^ ( n1 u -- n )
 2101: \ n = the uth power of n1
 2102:   1 swap 0 u+do
 2103:     over *
 2104:   loop
 2105:   nip ;
 2106: 3 2 ^ .
 2107: 4 3 ^ .
 2108: @end example
 2109: 
 2110: @code{U+do} (from @file{compat/loops.fs}, if your Forth system doesn't
 2111: have it) takes two numbers of the stack @code{( u3 u4 -- )}, and then
 2112: performs the code between @code{u+do} and @code{loop} for @code{u3-u4}
 2113: times (or not at all, if @code{u3-u4<0}).
 2114: 
 2115: You can see the stack effect design rules at work in the stack effect of
 2116: the loop start words: Since the start value of the loop is more
 2117: frequently constant than the end value, the start value is passed on
 2118: the top-of-stack.
 2119: 
 2120: You can access the counter of a counted loop with @code{i}:
 2121: 
 2122: @example
 2123: : fac ( u -- u! )
 2124:   1 swap 1+ 1 u+do
 2125:     i *
 2126:   loop ;
 2127: 5 fac .
 2128: 7 fac .
 2129: @end example
 2130: 
 2131: There is also @code{+do}, which expects signed numbers (important for
 2132: deciding whether to enter the loop).
 2133: 
 2134: @quotation Assignment
 2135: Write a definition for computing the nth Fibonacci number.
 2136: @end quotation
 2137: 
 2138: You can also use increments other than 1:
 2139: 
 2140: @example
 2141: : up2 ( n1 n2 -- )
 2142:   +do
 2143:     i .
 2144:   2 +loop ;
 2145: 10 0 up2
 2146: 
 2147: : down2 ( n1 n2 -- )
 2148:   -do
 2149:     i .
 2150:   2 -loop ;
 2151: 0 10 down2
 2152: @end example
 2153: 
 2154: Reference: @ref{Counted Loops}.
 2155: 
 2156: 
 2157: @node Recursion Tutorial, Leaving definitions or loops Tutorial, Counted loops Tutorial, Tutorial
 2158: @section Recursion
 2159: @cindex recursion tutorial
 2160: 
 2161: Usually the name of a definition is not visible in the definition; but
 2162: earlier definitions are usually visible:
 2163: 
 2164: @example
 2165: 1 0 / . \ "Floating-point unidentified fault" in Gforth on some platforms
 2166: : / ( n1 n2 -- n )
 2167:   dup 0= if
 2168:     -10 throw \ report division by zero
 2169:   endif
 2170:   /           \ old version
 2171: ;
 2172: 1 0 /
 2173: @end example
 2174: 
 2175: For recursive definitions you can use @code{recursive} (non-standard) or
 2176: @code{recurse}:
 2177: 
 2178: @example
 2179: : fac1 ( n -- n! ) recursive
 2180:  dup 0> if
 2181:    dup 1- fac1 *
 2182:  else
 2183:    drop 1
 2184:  endif ;
 2185: 7 fac1 .
 2186: 
 2187: : fac2 ( n -- n! )
 2188:  dup 0> if
 2189:    dup 1- recurse *
 2190:  else
 2191:    drop 1
 2192:  endif ;
 2193: 8 fac2 .
 2194: @end example
 2195: 
 2196: @quotation Assignment
 2197: Write a recursive definition for computing the nth Fibonacci number.
 2198: @end quotation
 2199: 
 2200: Reference (including indirect recursion): @xref{Calls and returns}.
 2201: 
 2202: 
 2203: @node Leaving definitions or loops Tutorial, Return Stack Tutorial, Recursion Tutorial, Tutorial
 2204: @section Leaving definitions or loops
 2205: @cindex leaving definitions, tutorial
 2206: @cindex leaving loops, tutorial
 2207: 
 2208: @code{EXIT} exits the current definition right away.  For every counted
 2209: loop that is left in this way, an @code{UNLOOP} has to be performed
 2210: before the @code{EXIT}:
 2211: 
 2212: @c !! real examples
 2213: @example
 2214: : ...
 2215:  ... u+do
 2216:    ... if
 2217:      ... unloop exit
 2218:    endif
 2219:    ...
 2220:  loop
 2221:  ... ;
 2222: @end example
 2223: 
 2224: @code{LEAVE} leaves the innermost counted loop right away:
 2225: 
 2226: @example
 2227: : ...
 2228:  ... u+do
 2229:    ... if
 2230:      ... leave
 2231:    endif
 2232:    ...
 2233:  loop
 2234:  ... ;
 2235: @end example
 2236: 
 2237: @c !! example
 2238: 
 2239: Reference: @ref{Calls and returns}, @ref{Counted Loops}.
 2240: 
 2241: 
 2242: @node Return Stack Tutorial, Memory Tutorial, Leaving definitions or loops Tutorial, Tutorial
 2243: @section Return Stack
 2244: @cindex return stack tutorial
 2245: 
 2246: In addition to the data stack Forth also has a second stack, the return
 2247: stack; most Forth systems store the return addresses of procedure calls
 2248: there (thus its name).  Programmers can also use this stack:
 2249: 
 2250: @example
 2251: : foo ( n1 n2 -- )
 2252:  .s
 2253:  >r .s
 2254:  r@@ .
 2255:  >r .s
 2256:  r@@ .
 2257:  r> .
 2258:  r@@ .
 2259:  r> . ;
 2260: 1 2 foo
 2261: @end example
 2262: 
 2263: @code{>r} takes an element from the data stack and pushes it onto the
 2264: return stack; conversely, @code{r>} moves an elementm from the return to
 2265: the data stack; @code{r@@} pushes a copy of the top of the return stack
 2266: on the data stack.
 2267: 
 2268: Forth programmers usually use the return stack for storing data
 2269: temporarily, if using the data stack alone would be too complex, and
 2270: factoring and locals are not an option:
 2271: 
 2272: @example
 2273: : 2swap ( x1 x2 x3 x4 -- x3 x4 x1 x2 )
 2274:  rot >r rot r> ;
 2275: @end example
 2276: 
 2277: The return address of the definition and the loop control parameters of
 2278: counted loops usually reside on the return stack, so you have to take
 2279: all items, that you have pushed on the return stack in a colon
 2280: definition or counted loop, from the return stack before the definition
 2281: or loop ends.  You cannot access items that you pushed on the return
 2282: stack outside some definition or loop within the definition of loop.
 2283: 
 2284: If you miscount the return stack items, this usually ends in a crash:
 2285: 
 2286: @example
 2287: : crash ( n -- )
 2288:   >r ;
 2289: 5 crash
 2290: @end example
 2291: 
 2292: You cannot mix using locals and using the return stack (according to the
 2293: standard; Gforth has no problem).  However, they solve the same
 2294: problems, so this shouldn't be an issue.
 2295: 
 2296: @quotation Assignment
 2297: Can you rewrite any of the definitions you wrote until now in a better
 2298: way using the return stack?
 2299: @end quotation
 2300: 
 2301: Reference: @ref{Return stack}.
 2302: 
 2303: 
 2304: @node Memory Tutorial, Characters and Strings Tutorial, Return Stack Tutorial, Tutorial
 2305: @section Memory
 2306: @cindex memory access/allocation tutorial
 2307: 
 2308: You can create a global variable @code{v} with
 2309: 
 2310: @example
 2311: variable v ( -- addr )
 2312: @end example
 2313: 
 2314: @code{v} pushes the address of a cell in memory on the stack.  This cell
 2315: was reserved by @code{variable}.  You can use @code{!} (store) to store
 2316: values into this cell and @code{@@} (fetch) to load the value from the
 2317: stack into memory:
 2318: 
 2319: @example
 2320: v .
 2321: 5 v ! .s
 2322: v @@ .
 2323: @end example
 2324: 
 2325: You can see a raw dump of memory with @code{dump}:
 2326: 
 2327: @example
 2328: v 1 cells .s dump
 2329: @end example
 2330: 
 2331: @code{Cells ( n1 -- n2 )} gives you the number of bytes (or, more
 2332: generally, address units (aus)) that @code{n1 cells} occupy.  You can
 2333: also reserve more memory:
 2334: 
 2335: @example
 2336: create v2 20 cells allot
 2337: v2 20 cells dump
 2338: @end example
 2339: 
 2340: creates a word @code{v2} and reserves 20 uninitialized cells; the
 2341: address pushed by @code{v2} points to the start of these 20 cells.  You
 2342: can use address arithmetic to access these cells:
 2343: 
 2344: @example
 2345: 3 v2 5 cells + !
 2346: v2 20 cells dump
 2347: @end example
 2348: 
 2349: You can reserve and initialize memory with @code{,}:
 2350: 
 2351: @example
 2352: create v3
 2353:   5 , 4 , 3 , 2 , 1 ,
 2354: v3 @@ .
 2355: v3 cell+ @@ .
 2356: v3 2 cells + @@ .
 2357: v3 5 cells dump
 2358: @end example
 2359: 
 2360: @quotation Assignment
 2361: Write a definition @code{vsum ( addr u -- n )} that computes the sum of
 2362: @code{u} cells, with the first of these cells at @code{addr}, the next
 2363: one at @code{addr cell+} etc.
 2364: @end quotation
 2365: 
 2366: You can also reserve memory without creating a new word:
 2367: 
 2368: @example
 2369: here 10 cells allot .
 2370: here .
 2371: @end example
 2372: 
 2373: @code{Here} pushes the start address of the memory area.  You should
 2374: store it somewhere, or you will have a hard time finding the memory area
 2375: again.
 2376: 
 2377: @code{Allot} manages dictionary memory.  The dictionary memory contains
 2378: the system's data structures for words etc. on Gforth and most other
 2379: Forth systems.  It is managed like a stack: You can free the memory that
 2380: you have just @code{allot}ed with
 2381: 
 2382: @example
 2383: -10 cells allot
 2384: here .
 2385: @end example
 2386: 
 2387: Note that you cannot do this if you have created a new word in the
 2388: meantime (because then your @code{allot}ed memory is no longer on the
 2389: top of the dictionary ``stack'').
 2390: 
 2391: Alternatively, you can use @code{allocate} and @code{free} which allow
 2392: freeing memory in any order:
 2393: 
 2394: @example
 2395: 10 cells allocate throw .s
 2396: 20 cells allocate throw .s
 2397: swap
 2398: free throw
 2399: free throw
 2400: @end example
 2401: 
 2402: The @code{throw}s deal with errors (e.g., out of memory).
 2403: 
 2404: And there is also a
 2405: @uref{http://www.complang.tuwien.ac.at/forth/garbage-collection.zip,
 2406: garbage collector}, which eliminates the need to @code{free} memory
 2407: explicitly.
 2408: 
 2409: Reference: @ref{Memory}.
 2410: 
 2411: 
 2412: @node Characters and Strings Tutorial, Alignment Tutorial, Memory Tutorial, Tutorial
 2413: @section Characters and Strings
 2414: @cindex strings tutorial
 2415: @cindex characters tutorial
 2416: 
 2417: On the stack characters take up a cell, like numbers.  In memory they
 2418: have their own size (one 8-bit byte on most systems), and therefore
 2419: require their own words for memory access:
 2420: 
 2421: @example
 2422: create v4 
 2423:   104 c, 97 c, 108 c, 108 c, 111 c,
 2424: v4 4 chars + c@@ .
 2425: v4 5 chars dump
 2426: @end example
 2427: 
 2428: The preferred representation of strings on the stack is @code{addr
 2429: u-count}, where @code{addr} is the address of the first character and
 2430: @code{u-count} is the number of characters in the string.
 2431: 
 2432: @example
 2433: v4 5 type
 2434: @end example
 2435: 
 2436: You get a string constant with
 2437: 
 2438: @example
 2439: s" hello, world" .s
 2440: type
 2441: @end example
 2442: 
 2443: Make sure you have a space between @code{s"} and the string; @code{s"}
 2444: is a normal Forth word and must be delimited with white space (try what
 2445: happens when you remove the space).
 2446: 
 2447: However, this interpretive use of @code{s"} is quite restricted: the
 2448: string exists only until the next call of @code{s"} (some Forth systems
 2449: keep more than one of these strings, but usually they still have a
 2450: limited lifetime).
 2451: 
 2452: @example
 2453: s" hello," s" world" .s
 2454: type
 2455: type
 2456: @end example
 2457: 
 2458: You can also use @code{s"} in a definition, and the resulting
 2459: strings then live forever (well, for as long as the definition):
 2460: 
 2461: @example
 2462: : foo s" hello," s" world" ;
 2463: foo .s
 2464: type
 2465: type
 2466: @end example
 2467: 
 2468: @quotation Assignment
 2469: @code{Emit ( c -- )} types @code{c} as character (not a number).
 2470: Implement @code{type ( addr u -- )}.
 2471: @end quotation
 2472: 
 2473: Reference: @ref{Memory Blocks}.
 2474: 
 2475: 
 2476: @node Alignment Tutorial, Files Tutorial, Characters and Strings Tutorial, Tutorial
 2477: @section Alignment
 2478: @cindex alignment tutorial
 2479: @cindex memory alignment tutorial
 2480: 
 2481: On many processors cells have to be aligned in memory, if you want to
 2482: access them with @code{@@} and @code{!} (and even if the processor does
 2483: not require alignment, access to aligned cells is faster).
 2484: 
 2485: @code{Create} aligns @code{here} (i.e., the place where the next
 2486: allocation will occur, and that the @code{create}d word points to).
 2487: Likewise, the memory produced by @code{allocate} starts at an aligned
 2488: address.  Adding a number of @code{cells} to an aligned address produces
 2489: another aligned address.
 2490: 
 2491: However, address arithmetic involving @code{char+} and @code{chars} can
 2492: create an address that is not cell-aligned.  @code{Aligned ( addr --
 2493: a-addr )} produces the next aligned address:
 2494: 
 2495: @example
 2496: v3 char+ aligned .s @@ .
 2497: v3 char+ .s @@ .
 2498: @end example
 2499: 
 2500: Similarly, @code{align} advances @code{here} to the next aligned
 2501: address:
 2502: 
 2503: @example
 2504: create v5 97 c,
 2505: here .
 2506: align here .
 2507: 1000 ,
 2508: @end example
 2509: 
 2510: Note that you should use aligned addresses even if your processor does
 2511: not require them, if you want your program to be portable.
 2512: 
 2513: Reference: @ref{Address arithmetic}.
 2514: 
 2515: 
 2516: @node Files Tutorial, Interpretation and Compilation Semantics and Immediacy Tutorial, Alignment Tutorial, Tutorial
 2517: @section Files
 2518: @cindex files tutorial
 2519: 
 2520: This section gives a short introduction into how to use files inside
 2521: Forth. It's broken up into five easy steps:
 2522: 
 2523: @enumerate 1
 2524: @item Opened an ASCII text file for input
 2525: @item Opened a file for output
 2526: @item Read input file until string matched (or some other condition matched)
 2527: @item Wrote some lines from input ( modified or not) to output
 2528: @item Closed the files.
 2529: @end enumerate
 2530: 
 2531: Reference: @ref{General files}.
 2532: 
 2533: @subsection Open file for input
 2534: 
 2535: @example
 2536: s" foo.in"  r/o open-file throw Value fd-in
 2537: @end example
 2538: 
 2539: @subsection Create file for output
 2540: 
 2541: @example
 2542: s" foo.out" w/o create-file throw Value fd-out
 2543: @end example
 2544: 
 2545: The available file modes are r/o for read-only access, r/w for
 2546: read-write access, and w/o for write-only access. You could open both
 2547: files with r/w, too, if you like. All file words return error codes; for
 2548: most applications, it's best to pass there error codes with @code{throw}
 2549: to the outer error handler.
 2550: 
 2551: If you want words for opening and assigning, define them as follows:
 2552: 
 2553: @example
 2554: 0 Value fd-in
 2555: 0 Value fd-out
 2556: : open-input ( addr u -- )  r/o open-file throw to fd-in ;
 2557: : open-output ( addr u -- )  w/o create-file throw to fd-out ;
 2558: @end example
 2559: 
 2560: Usage example:
 2561: 
 2562: @example
 2563: s" foo.in" open-input
 2564: s" foo.out" open-output
 2565: @end example
 2566: 
 2567: @subsection Scan file for a particular line
 2568: 
 2569: @example
 2570: 256 Constant max-line
 2571: Create line-buffer  max-line 2 + allot
 2572: 
 2573: : scan-file ( addr u -- )
 2574:   begin
 2575:       line-buffer max-line fd-in read-line throw
 2576:   while
 2577:          >r 2dup line-buffer r> compare 0=
 2578:      until
 2579:   else
 2580:      drop
 2581:   then
 2582:   2drop ;
 2583: @end example
 2584: 
 2585: @code{read-line ( addr u1 fd -- u2 flag ior )} reads up to u1 bytes into
 2586: the buffer at addr, and returns the number of bytes read, a flag that is
 2587: false when the end of file is reached, and an error code.
 2588: 
 2589: @code{compare ( addr1 u1 addr2 u2 -- n )} compares two strings and
 2590: returns zero if both strings are equal. It returns a positive number if
 2591: the first string is lexically greater, a negative if the second string
 2592: is lexically greater.
 2593: 
 2594: We haven't seen this loop here; it has two exits. Since the @code{while}
 2595: exits with the number of bytes read on the stack, we have to clean up
 2596: that separately; that's after the @code{else}.
 2597: 
 2598: Usage example:
 2599: 
 2600: @example
 2601: s" The text I search is here" scan-file
 2602: @end example
 2603: 
 2604: @subsection Copy input to output
 2605: 
 2606: @example
 2607: : copy-file ( -- )
 2608:   begin
 2609:       line-buffer max-line fd-in read-line throw
 2610:   while
 2611:       line-buffer swap fd-out write-file throw
 2612:   repeat ;
 2613: @end example
 2614: 
 2615: @subsection Close files
 2616: 
 2617: @example
 2618: fd-in close-file throw
 2619: fd-out close-file throw
 2620: @end example
 2621: 
 2622: Likewise, you can put that into definitions, too:
 2623: 
 2624: @example
 2625: : close-input ( -- )  fd-in close-file throw ;
 2626: : close-output ( -- )  fd-out close-file throw ;
 2627: @end example
 2628: 
 2629: @quotation Assignment
 2630: How could you modify @code{copy-file} so that it copies until a second line is
 2631: matched? Can you write a program that extracts a section of a text file,
 2632: given the line that starts and the line that terminates that section?
 2633: @end quotation
 2634: 
 2635: @node Interpretation and Compilation Semantics and Immediacy Tutorial, Execution Tokens Tutorial, Files Tutorial, Tutorial
 2636: @section Interpretation and Compilation Semantics and Immediacy
 2637: @cindex semantics tutorial
 2638: @cindex interpretation semantics tutorial
 2639: @cindex compilation semantics tutorial
 2640: @cindex immediate, tutorial
 2641: 
 2642: When a word is compiled, it behaves differently from being interpreted.
 2643: E.g., consider @code{+}:
 2644: 
 2645: @example
 2646: 1 2 + .
 2647: : foo + ;
 2648: @end example
 2649: 
 2650: These two behaviours are known as compilation and interpretation
 2651: semantics.  For normal words (e.g., @code{+}), the compilation semantics
 2652: is to append the interpretation semantics to the currently defined word
 2653: (@code{foo} in the example above).  I.e., when @code{foo} is executed
 2654: later, the interpretation semantics of @code{+} (i.e., adding two
 2655: numbers) will be performed.
 2656: 
 2657: However, there are words with non-default compilation semantics, e.g.,
 2658: the control-flow words like @code{if}.  You can use @code{immediate} to
 2659: change the compilation semantics of the last defined word to be equal to
 2660: the interpretation semantics:
 2661: 
 2662: @example
 2663: : [FOO] ( -- )
 2664:  5 . ; immediate
 2665: 
 2666: [FOO]
 2667: : bar ( -- )
 2668:   [FOO] ;
 2669: bar
 2670: see bar
 2671: @end example
 2672: 
 2673: Two conventions to mark words with non-default compilation semnatics are
 2674: names with brackets (more frequently used) and to write them all in
 2675: upper case (less frequently used).
 2676: 
 2677: In Gforth (and many other systems) you can also remove the
 2678: interpretation semantics with @code{compile-only} (the compilation
 2679: semantics is derived from the original interpretation semantics):
 2680: 
 2681: @example
 2682: : flip ( -- )
 2683:  6 . ; compile-only \ but not immediate
 2684: flip
 2685: 
 2686: : flop ( -- )
 2687:  flip ;
 2688: flop
 2689: @end example
 2690: 
 2691: In this example the interpretation semantics of @code{flop} is equal to
 2692: the original interpretation semantics of @code{flip}.
 2693: 
 2694: The text interpreter has two states: in interpret state, it performs the
 2695: interpretation semantics of words it encounters; in compile state, it
 2696: performs the compilation semantics of these words.
 2697: 
 2698: Among other things, @code{:} switches into compile state, and @code{;}
 2699: switches back to interpret state.  They contain the factors @code{]}
 2700: (switch to compile state) and @code{[} (switch to interpret state), that
 2701: do nothing but switch the state.
 2702: 
 2703: @example
 2704: : xxx ( -- )
 2705:   [ 5 . ]
 2706: ;
 2707: 
 2708: xxx
 2709: see xxx
 2710: @end example
 2711: 
 2712: These brackets are also the source of the naming convention mentioned
 2713: above.
 2714: 
 2715: Reference: @ref{Interpretation and Compilation Semantics}.
 2716: 
 2717: 
 2718: @node Execution Tokens Tutorial, Exceptions Tutorial, Interpretation and Compilation Semantics and Immediacy Tutorial, Tutorial
 2719: @section Execution Tokens
 2720: @cindex execution tokens tutorial
 2721: @cindex XT tutorial
 2722: 
 2723: @code{' word} gives you the execution token (XT) of a word.  The XT is a
 2724: cell representing the interpretation semantics of a word.  You can
 2725: execute this semantics with @code{execute}:
 2726: 
 2727: @example
 2728: ' + .s
 2729: 1 2 rot execute .
 2730: @end example
 2731: 
 2732: The XT is similar to a function pointer in C.  However, parameter
 2733: passing through the stack makes it a little more flexible:
 2734: 
 2735: @example
 2736: : map-array ( ... addr u xt -- ... )
 2737: \ executes xt ( ... x -- ... ) for every element of the array starting
 2738: \ at addr and containing u elements
 2739:   @{ xt @}
 2740:   cells over + swap ?do
 2741:     i @@ xt execute
 2742:   1 cells +loop ;
 2743: 
 2744: create a 3 , 4 , 2 , -1 , 4 ,
 2745: a 5 ' . map-array .s
 2746: 0 a 5 ' + map-array .
 2747: s" max-n" environment? drop .s
 2748: a 5 ' min map-array .
 2749: @end example
 2750: 
 2751: You can use map-array with the XTs of words that consume one element
 2752: more than they produce.  In theory you can also use it with other XTs,
 2753: but the stack effect then depends on the size of the array, which is
 2754: hard to understand.
 2755: 
 2756: Since XTs are cell-sized, you can store them in memory and manipulate
 2757: them on the stack like other cells.  You can also compile the XT into a
 2758: word with @code{compile,}:
 2759: 
 2760: @example
 2761: : foo1 ( n1 n2 -- n )
 2762:    [ ' + compile, ] ;
 2763: see foo
 2764: @end example
 2765: 
 2766: This is non-standard, because @code{compile,} has no compilation
 2767: semantics in the standard, but it works in good Forth systems.  For the
 2768: broken ones, use
 2769: 
 2770: @example
 2771: : [compile,] compile, ; immediate
 2772: 
 2773: : foo1 ( n1 n2 -- n )
 2774:    [ ' + ] [compile,] ;
 2775: see foo
 2776: @end example
 2777: 
 2778: @code{'} is a word with default compilation semantics; it parses the
 2779: next word when its interpretation semantics are executed, not during
 2780: compilation:
 2781: 
 2782: @example
 2783: : foo ( -- xt )
 2784:   ' ;
 2785: see foo
 2786: : bar ( ... "word" -- ... )
 2787:   ' execute ;
 2788: see bar
 2789: 1 2 bar + .
 2790: @end example
 2791: 
 2792: You often want to parse a word during compilation and compile its XT so
 2793: it will be pushed on the stack at run-time.  @code{[']} does this:
 2794: 
 2795: @example
 2796: : xt-+ ( -- xt )
 2797:   ['] + ;
 2798: see xt-+
 2799: 1 2 xt-+ execute .
 2800: @end example
 2801: 
 2802: Many programmers tend to see @code{'} and the word it parses as one
 2803: unit, and expect it to behave like @code{[']} when compiled, and are
 2804: confused by the actual behaviour.  If you are, just remember that the
 2805: Forth system just takes @code{'} as one unit and has no idea that it is
 2806: a parsing word (attempts to convenience programmers in this issue have
 2807: usually resulted in even worse pitfalls, see
 2808: @uref{http://www.complang.tuwien.ac.at/papers/ertl98.ps.gz,
 2809: @code{State}-smartness---Why it is evil and How to Exorcise it}).
 2810: 
 2811: Note that the state of the interpreter does not come into play when
 2812: creating and executing XTs.  I.e., even when you execute @code{'} in
 2813: compile state, it still gives you the interpretation semantics.  And
 2814: whatever that state is, @code{execute} performs the semantics
 2815: represented by the XT (i.e., for XTs produced with @code{'} the
 2816: interpretation semantics).
 2817: 
 2818: Reference: @ref{Tokens for Words}.
 2819: 
 2820: 
 2821: @node Exceptions Tutorial, Defining Words Tutorial, Execution Tokens Tutorial, Tutorial
 2822: @section Exceptions
 2823: @cindex exceptions tutorial
 2824: 
 2825: @code{throw ( n -- )} causes an exception unless n is zero.
 2826: 
 2827: @example
 2828: 100 throw .s
 2829: 0 throw .s
 2830: @end example
 2831: 
 2832: @code{catch ( ... xt -- ... n )} behaves similar to @code{execute}, but
 2833: it catches exceptions and pushes the number of the exception on the
 2834: stack (or 0, if the xt executed without exception).  If there was an
 2835: exception, the stacks have the same depth as when entering @code{catch}:
 2836: 
 2837: @example
 2838: .s
 2839: 3 0 ' / catch .s
 2840: 3 2 ' / catch .s
 2841: @end example
 2842: 
 2843: @quotation Assignment
 2844: Try the same with @code{execute} instead of @code{catch}.
 2845: @end quotation
 2846: 
 2847: @code{Throw} always jumps to the dynamically next enclosing
 2848: @code{catch}, even if it has to leave several call levels to achieve
 2849: this:
 2850: 
 2851: @example
 2852: : foo 100 throw ;
 2853: : foo1 foo ." after foo" ;
 2854: : bar ['] foo1 catch ;
 2855: bar .
 2856: @end example
 2857: 
 2858: It is often important to restore a value upon leaving a definition, even
 2859: if the definition is left through an exception.  You can ensure this
 2860: like this:
 2861: 
 2862: @example
 2863: : ...
 2864:    save-x
 2865:    ['] word-changing-x catch ( ... n )
 2866:    restore-x
 2867:    ( ... n ) throw ;
 2868: @end example
 2869: 
 2870: However, this is still not safe against, e.g., the user pressing
 2871: @kbd{Ctrl-C} when execution is between the @code{catch} and
 2872: @code{restore-x}.
 2873: 
 2874: Gforth provides an alternative exception handling syntax that is safe
 2875: against such cases: @code{try ... restore ... endtry}.  If the code
 2876: between @code{try} and @code{endtry} has an exception, the stack
 2877: depths are restored, the exception number is pushed on the stack, and
 2878: the execution continues right after @code{restore}.
 2879: 
 2880: The safer equivalent to the restoration code above is
 2881: 
 2882: @example
 2883: : ...
 2884:   save-x
 2885:   try
 2886:     word-changing-x 0
 2887:   restore
 2888:     restore-x
 2889:   endtry
 2890:   throw ;
 2891: @end example
 2892: 
 2893: Reference: @ref{Exception Handling}.
 2894: 
 2895: 
 2896: @node Defining Words Tutorial, Arrays and Records Tutorial, Exceptions Tutorial, Tutorial
 2897: @section Defining Words
 2898: @cindex defining words tutorial
 2899: @cindex does> tutorial
 2900: @cindex create...does> tutorial
 2901: 
 2902: @c before semantics?
 2903: 
 2904: @code{:}, @code{create}, and @code{variable} are definition words: They
 2905: define other words.  @code{Constant} is another definition word:
 2906: 
 2907: @example
 2908: 5 constant foo
 2909: foo .
 2910: @end example
 2911: 
 2912: You can also use the prefixes @code{2} (double-cell) and @code{f}
 2913: (floating point) with @code{variable} and @code{constant}.
 2914: 
 2915: You can also define your own defining words.  E.g.:
 2916: 
 2917: @example
 2918: : variable ( "name" -- )
 2919:   create 0 , ;
 2920: @end example
 2921: 
 2922: You can also define defining words that create words that do something
 2923: other than just producing their address:
 2924: 
 2925: @example
 2926: : constant ( n "name" -- )
 2927:   create ,
 2928: does> ( -- n )
 2929:   ( addr ) @@ ;
 2930: 
 2931: 5 constant foo
 2932: foo .
 2933: @end example
 2934: 
 2935: The definition of @code{constant} above ends at the @code{does>}; i.e.,
 2936: @code{does>} replaces @code{;}, but it also does something else: It
 2937: changes the last defined word such that it pushes the address of the
 2938: body of the word and then performs the code after the @code{does>}
 2939: whenever it is called.
 2940: 
 2941: In the example above, @code{constant} uses @code{,} to store 5 into the
 2942: body of @code{foo}.  When @code{foo} executes, it pushes the address of
 2943: the body onto the stack, then (in the code after the @code{does>})
 2944: fetches the 5 from there.
 2945: 
 2946: The stack comment near the @code{does>} reflects the stack effect of the
 2947: defined word, not the stack effect of the code after the @code{does>}
 2948: (the difference is that the code expects the address of the body that
 2949: the stack comment does not show).
 2950: 
 2951: You can use these definition words to do factoring in cases that involve
 2952: (other) definition words.  E.g., a field offset is always added to an
 2953: address.  Instead of defining
 2954: 
 2955: @example
 2956: 2 cells constant offset-field1
 2957: @end example
 2958: 
 2959: and using this like
 2960: 
 2961: @example
 2962: ( addr ) offset-field1 +
 2963: @end example
 2964: 
 2965: you can define a definition word
 2966: 
 2967: @example
 2968: : simple-field ( n "name" -- )
 2969:   create ,
 2970: does> ( n1 -- n1+n )
 2971:   ( addr ) @@ + ;
 2972: @end example
 2973: 
 2974: Definition and use of field offsets now look like this:
 2975: 
 2976: @example
 2977: 2 cells simple-field field1
 2978: create mystruct 4 cells allot
 2979: mystruct .s field1 .s drop
 2980: @end example
 2981: 
 2982: If you want to do something with the word without performing the code
 2983: after the @code{does>}, you can access the body of a @code{create}d word
 2984: with @code{>body ( xt -- addr )}:
 2985: 
 2986: @example
 2987: : value ( n "name" -- )
 2988:   create ,
 2989: does> ( -- n1 )
 2990:   @@ ;
 2991: : to ( n "name" -- )
 2992:   ' >body ! ;
 2993: 
 2994: 5 value foo
 2995: foo .
 2996: 7 to foo
 2997: foo .
 2998: @end example
 2999: 
 3000: @quotation Assignment
 3001: Define @code{defer ( "name" -- )}, which creates a word that stores an
 3002: XT (at the start the XT of @code{abort}), and upon execution
 3003: @code{execute}s the XT.  Define @code{is ( xt "name" -- )} that stores
 3004: @code{xt} into @code{name}, a word defined with @code{defer}.  Indirect
 3005: recursion is one application of @code{defer}.
 3006: @end quotation
 3007: 
 3008: Reference: @ref{User-defined Defining Words}.
 3009: 
 3010: 
 3011: @node Arrays and Records Tutorial, POSTPONE Tutorial, Defining Words Tutorial, Tutorial
 3012: @section Arrays and Records
 3013: @cindex arrays tutorial
 3014: @cindex records tutorial
 3015: @cindex structs tutorial
 3016: 
 3017: Forth has no standard words for defining data structures such as arrays
 3018: and records (structs in C terminology), but you can build them yourself
 3019: based on address arithmetic.  You can also define words for defining
 3020: arrays and records (@pxref{Defining Words Tutorial,, Defining Words}).
 3021: 
 3022: One of the first projects a Forth newcomer sets out upon when learning
 3023: about defining words is an array defining word (possibly for
 3024: n-dimensional arrays).  Go ahead and do it, I did it, too; you will
 3025: learn something from it.  However, don't be disappointed when you later
 3026: learn that you have little use for these words (inappropriate use would
 3027: be even worse).  I have not yet found a set of useful array words yet;
 3028: the needs are just too diverse, and named, global arrays (the result of
 3029: naive use of defining words) are often not flexible enough (e.g.,
 3030: consider how to pass them as parameters).  Another such project is a set
 3031: of words to help dealing with strings.
 3032: 
 3033: On the other hand, there is a useful set of record words, and it has
 3034: been defined in @file{compat/struct.fs}; these words are predefined in
 3035: Gforth.  They are explained in depth elsewhere in this manual (see
 3036: @pxref{Structures}).  The @code{simple-field} example above is
 3037: simplified variant of fields in this package.
 3038: 
 3039: 
 3040: @node POSTPONE Tutorial, Literal Tutorial, Arrays and Records Tutorial, Tutorial
 3041: @section @code{POSTPONE}
 3042: @cindex postpone tutorial
 3043: 
 3044: You can compile the compilation semantics (instead of compiling the
 3045: interpretation semantics) of a word with @code{POSTPONE}:
 3046: 
 3047: @example
 3048: : MY-+ ( Compilation: -- ; Run-time of compiled code: n1 n2 -- n )
 3049:  POSTPONE + ; immediate
 3050: : foo ( n1 n2 -- n )
 3051:  MY-+ ;
 3052: 1 2 foo .
 3053: see foo
 3054: @end example
 3055: 
 3056: During the definition of @code{foo} the text interpreter performs the
 3057: compilation semantics of @code{MY-+}, which performs the compilation
 3058: semantics of @code{+}, i.e., it compiles @code{+} into @code{foo}.
 3059: 
 3060: This example also displays separate stack comments for the compilation
 3061: semantics and for the stack effect of the compiled code.  For words with
 3062: default compilation semantics these stack effects are usually not
 3063: displayed; the stack effect of the compilation semantics is always
 3064: @code{( -- )} for these words, the stack effect for the compiled code is
 3065: the stack effect of the interpretation semantics.
 3066: 
 3067: Note that the state of the interpreter does not come into play when
 3068: performing the compilation semantics in this way.  You can also perform
 3069: it interpretively, e.g.:
 3070: 
 3071: @example
 3072: : foo2 ( n1 n2 -- n )
 3073:  [ MY-+ ] ;
 3074: 1 2 foo .
 3075: see foo
 3076: @end example
 3077: 
 3078: However, there are some broken Forth systems where this does not always
 3079: work, and therefore this practice was been declared non-standard in
 3080: 1999.
 3081: @c !! repair.fs
 3082: 
 3083: Here is another example for using @code{POSTPONE}:
 3084: 
 3085: @example
 3086: : MY-- ( Compilation: -- ; Run-time of compiled code: n1 n2 -- n )
 3087:  POSTPONE negate POSTPONE + ; immediate compile-only
 3088: : bar ( n1 n2 -- n )
 3089:   MY-- ;
 3090: 2 1 bar .
 3091: see bar
 3092: @end example
 3093: 
 3094: You can define @code{ENDIF} in this way:
 3095: 
 3096: @example
 3097: : ENDIF ( Compilation: orig -- )
 3098:   POSTPONE then ; immediate
 3099: @end example
 3100: 
 3101: @quotation Assignment
 3102: Write @code{MY-2DUP} that has compilation semantics equivalent to
 3103: @code{2dup}, but compiles @code{over over}.
 3104: @end quotation
 3105: 
 3106: @c !! @xref{Macros} for reference
 3107: 
 3108: 
 3109: @node Literal Tutorial, Advanced macros Tutorial, POSTPONE Tutorial, Tutorial
 3110: @section @code{Literal}
 3111: @cindex literal tutorial
 3112: 
 3113: You cannot @code{POSTPONE} numbers:
 3114: 
 3115: @example
 3116: : [FOO] POSTPONE 500 ; immediate
 3117: @end example
 3118: 
 3119: Instead, you can use @code{LITERAL (compilation: n --; run-time: -- n )}:
 3120: 
 3121: @example
 3122: : [FOO] ( compilation: --; run-time: -- n )
 3123:   500 POSTPONE literal ; immediate
 3124: 
 3125: : flip [FOO] ;
 3126: flip .
 3127: see flip
 3128: @end example
 3129: 
 3130: @code{LITERAL} consumes a number at compile-time (when it's compilation
 3131: semantics are executed) and pushes it at run-time (when the code it
 3132: compiled is executed).  A frequent use of @code{LITERAL} is to compile a
 3133: number computed at compile time into the current word:
 3134: 
 3135: @example
 3136: : bar ( -- n )
 3137:   [ 2 2 + ] literal ;
 3138: see bar
 3139: @end example
 3140: 
 3141: @quotation Assignment
 3142: Write @code{]L} which allows writing the example above as @code{: bar (
 3143: -- n ) [ 2 2 + ]L ;}
 3144: @end quotation
 3145: 
 3146: @c !! @xref{Macros} for reference
 3147: 
 3148: 
 3149: @node Advanced macros Tutorial, Compilation Tokens Tutorial, Literal Tutorial, Tutorial
 3150: @section Advanced macros
 3151: @cindex macros, advanced tutorial
 3152: @cindex run-time code generation, tutorial
 3153: 
 3154: Reconsider @code{map-array} from @ref{Execution Tokens Tutorial,,
 3155: Execution Tokens}.  It frequently performs @code{execute}, a relatively
 3156: expensive operation in some Forth implementations.  You can use
 3157: @code{compile,} and @code{POSTPONE} to eliminate these @code{execute}s
 3158: and produce a word that contains the word to be performed directly:
 3159: 
 3160: @c use ]] ... [[
 3161: @example
 3162: : compile-map-array ( compilation: xt -- ; run-time: ... addr u -- ... )
 3163: \ at run-time, execute xt ( ... x -- ... ) for each element of the
 3164: \ array beginning at addr and containing u elements
 3165:   @{ xt @}
 3166:   POSTPONE cells POSTPONE over POSTPONE + POSTPONE swap POSTPONE ?do
 3167:     POSTPONE i POSTPONE @@ xt compile,
 3168:   1 cells POSTPONE literal POSTPONE +loop ;
 3169: 
 3170: : sum-array ( addr u -- n )
 3171:  0 rot rot [ ' + compile-map-array ] ;
 3172: see sum-array
 3173: a 5 sum-array .
 3174: @end example
 3175: 
 3176: You can use the full power of Forth for generating the code; here's an
 3177: example where the code is generated in a loop:
 3178: 
 3179: @example
 3180: : compile-vmul-step ( compilation: n --; run-time: n1 addr1 -- n2 addr2 )
 3181: \ n2=n1+(addr1)*n, addr2=addr1+cell
 3182:   POSTPONE tuck POSTPONE @@
 3183:   POSTPONE literal POSTPONE * POSTPONE +
 3184:   POSTPONE swap POSTPONE cell+ ;
 3185: 
 3186: : compile-vmul ( compilation: addr1 u -- ; run-time: addr2 -- n )
 3187: \ n=v1*v2 (inner product), where the v_i are represented as addr_i u
 3188:   0 postpone literal postpone swap
 3189:   [ ' compile-vmul-step compile-map-array ]
 3190:   postpone drop ;
 3191: see compile-vmul
 3192: 
 3193: : a-vmul ( addr -- n )
 3194: \ n=a*v, where v is a vector that's as long as a and starts at addr
 3195:  [ a 5 compile-vmul ] ;
 3196: see a-vmul
 3197: a a-vmul .
 3198: @end example
 3199: 
 3200: This example uses @code{compile-map-array} to show off, but you could
 3201: also use @code{map-array} instead (try it now!).
 3202: 
 3203: You can use this technique for efficient multiplication of large
 3204: matrices.  In matrix multiplication, you multiply every line of one
 3205: matrix with every column of the other matrix.  You can generate the code
 3206: for one line once, and use it for every column.  The only downside of
 3207: this technique is that it is cumbersome to recover the memory consumed
 3208: by the generated code when you are done (and in more complicated cases
 3209: it is not possible portably).
 3210: 
 3211: @c !! @xref{Macros} for reference
 3212: 
 3213: 
 3214: @node Compilation Tokens Tutorial, Wordlists and Search Order Tutorial, Advanced macros Tutorial, Tutorial
 3215: @section Compilation Tokens
 3216: @cindex compilation tokens, tutorial
 3217: @cindex CT, tutorial
 3218: 
 3219: This section is Gforth-specific.  You can skip it.
 3220: 
 3221: @code{' word compile,} compiles the interpretation semantics.  For words
 3222: with default compilation semantics this is the same as performing the
 3223: compilation semantics.  To represent the compilation semantics of other
 3224: words (e.g., words like @code{if} that have no interpretation
 3225: semantics), Gforth has the concept of a compilation token (CT,
 3226: consisting of two cells), and words @code{comp'} and @code{[comp']}.
 3227: You can perform the compilation semantics represented by a CT with
 3228: @code{execute}:
 3229: 
 3230: @example
 3231: : foo2 ( n1 n2 -- n )
 3232:    [ comp' + execute ] ;
 3233: see foo
 3234: @end example
 3235: 
 3236: You can compile the compilation semantics represented by a CT with
 3237: @code{postpone,}:
 3238: 
 3239: @example
 3240: : foo3 ( -- )
 3241:   [ comp' + postpone, ] ;
 3242: see foo3
 3243: @end example
 3244: 
 3245: @code{[ comp' word postpone, ]} is equivalent to @code{POSTPONE word}.
 3246: @code{comp'} is particularly useful for words that have no
 3247: interpretation semantics:
 3248: 
 3249: @example
 3250: ' if
 3251: comp' if .s 2drop
 3252: @end example
 3253: 
 3254: Reference: @ref{Tokens for Words}.
 3255: 
 3256: 
 3257: @node Wordlists and Search Order Tutorial,  , Compilation Tokens Tutorial, Tutorial
 3258: @section Wordlists and Search Order
 3259: @cindex wordlists tutorial
 3260: @cindex search order, tutorial
 3261: 
 3262: The dictionary is not just a memory area that allows you to allocate
 3263: memory with @code{allot}, it also contains the Forth words, arranged in
 3264: several wordlists.  When searching for a word in a wordlist,
 3265: conceptually you start searching at the youngest and proceed towards
 3266: older words (in reality most systems nowadays use hash-tables); i.e., if
 3267: you define a word with the same name as an older word, the new word
 3268: shadows the older word.
 3269: 
 3270: Which wordlists are searched in which order is determined by the search
 3271: order.  You can display the search order with @code{order}.  It displays
 3272: first the search order, starting with the wordlist searched first, then
 3273: it displays the wordlist that will contain newly defined words.
 3274: 
 3275: You can create a new, empty wordlist with @code{wordlist ( -- wid )}:
 3276: 
 3277: @example
 3278: wordlist constant mywords
 3279: @end example
 3280: 
 3281: @code{Set-current ( wid -- )} sets the wordlist that will contain newly
 3282: defined words (the @emph{current} wordlist):
 3283: 
 3284: @example
 3285: mywords set-current
 3286: order
 3287: @end example
 3288: 
 3289: Gforth does not display a name for the wordlist in @code{mywords}
 3290: because this wordlist was created anonymously with @code{wordlist}.
 3291: 
 3292: You can get the current wordlist with @code{get-current ( -- wid)}.  If
 3293: you want to put something into a specific wordlist without overall
 3294: effect on the current wordlist, this typically looks like this:
 3295: 
 3296: @example
 3297: get-current mywords set-current ( wid )
 3298: create someword
 3299: ( wid ) set-current
 3300: @end example
 3301: 
 3302: You can write the search order with @code{set-order ( wid1 .. widn n --
 3303: )} and read it with @code{get-order ( -- wid1 .. widn n )}.  The first
 3304: searched wordlist is topmost.
 3305: 
 3306: @example
 3307: get-order mywords swap 1+ set-order
 3308: order
 3309: @end example
 3310: 
 3311: Yes, the order of wordlists in the output of @code{order} is reversed
 3312: from stack comments and the output of @code{.s} and thus unintuitive.
 3313: 
 3314: @quotation Assignment
 3315: Define @code{>order ( wid -- )} with adds @code{wid} as first searched
 3316: wordlist to the search order.  Define @code{previous ( -- )}, which
 3317: removes the first searched wordlist from the search order.  Experiment
 3318: with boundary conditions (you will see some crashes or situations that
 3319: are hard or impossible to leave).
 3320: @end quotation
 3321: 
 3322: The search order is a powerful foundation for providing features similar
 3323: to Modula-2 modules and C++ namespaces.  However, trying to modularize
 3324: programs in this way has disadvantages for debugging and reuse/factoring
 3325: that overcome the advantages in my experience (I don't do huge projects,
 3326: though).  These disadvantages are not so clear in other
 3327: languages/programming environments, because these languages are not so
 3328: strong in debugging and reuse.
 3329: 
 3330: @c !! example
 3331: 
 3332: Reference: @ref{Word Lists}.
 3333: 
 3334: @c ******************************************************************
 3335: @node Introduction, Words, Tutorial, Top
 3336: @comment node-name,     next,           previous, up
 3337: @chapter An Introduction to ANS Forth
 3338: @cindex Forth - an introduction
 3339: 
 3340: The difference of this chapter from the Tutorial (@pxref{Tutorial}) is
 3341: that it is slower-paced in its examples, but uses them to dive deep into
 3342: explaining Forth internals (not covered by the Tutorial).  Apart from
 3343: that, this chapter covers far less material.  It is suitable for reading
 3344: without using a computer.
 3345: 
 3346: The primary purpose of this manual is to document Gforth. However, since
 3347: Forth is not a widely-known language and there is a lack of up-to-date
 3348: teaching material, it seems worthwhile to provide some introductory
 3349: material.  For other sources of Forth-related
 3350: information, see @ref{Forth-related information}.
 3351: 
 3352: The examples in this section should work on any ANS Forth; the
 3353: output shown was produced using Gforth. Each example attempts to
 3354: reproduce the exact output that Gforth produces. If you try out the
 3355: examples (and you should), what you should type is shown @kbd{like this}
 3356: and Gforth's response is shown @code{like this}. The single exception is
 3357: that, where the example shows @key{RET} it means that you should
 3358: press the ``carriage return'' key. Unfortunately, some output formats for
 3359: this manual cannot show the difference between @kbd{this} and
 3360: @code{this} which will make trying out the examples harder (but not
 3361: impossible).
 3362: 
 3363: Forth is an unusual language. It provides an interactive development
 3364: environment which includes both an interpreter and compiler. Forth
 3365: programming style encourages you to break a problem down into many
 3366: @cindex factoring
 3367: small fragments (@dfn{factoring}), and then to develop and test each
 3368: fragment interactively. Forth advocates assert that breaking the
 3369: edit-compile-test cycle used by conventional programming languages can
 3370: lead to great productivity improvements.
 3371: 
 3372: @menu
 3373: * Introducing the Text Interpreter::  
 3374: * Stacks and Postfix notation::  
 3375: * Your first definition::       
 3376: * How does that work?::         
 3377: * Forth is written in Forth::   
 3378: * Review - elements of a Forth system::  
 3379: * Where to go next::            
 3380: * Exercises::                   
 3381: @end menu
 3382: 
 3383: @comment ----------------------------------------------
 3384: @node Introducing the Text Interpreter, Stacks and Postfix notation, Introduction, Introduction
 3385: @section Introducing the Text Interpreter
 3386: @cindex text interpreter
 3387: @cindex outer interpreter
 3388: 
 3389: @c IMO this is too detailed and the pace is too slow for
 3390: @c an introduction.  If you know German, take a look at
 3391: @c http://www.complang.tuwien.ac.at/anton/lvas/skriptum-stack.html 
 3392: @c to see how I do it - anton 
 3393: 
 3394: @c nac-> Where I have accepted your comments 100% and modified the text
 3395: @c accordingly, I have deleted your comments. Elsewhere I have added a
 3396: @c response like this to attempt to rationalise what I have done. Of
 3397: @c course, this is a very clumsy mechanism for something that would be
 3398: @c done far more efficiently over a beer. Please delete any dialogue
 3399: @c you consider closed.
 3400: 
 3401: When you invoke the Forth image, you will see a startup banner printed
 3402: and nothing else (if you have Gforth installed on your system, try
 3403: invoking it now, by typing @kbd{gforth@key{RET}}). Forth is now running
 3404: its command line interpreter, which is called the @dfn{Text Interpreter}
 3405: (also known as the @dfn{Outer Interpreter}).  (You will learn a lot
 3406: about the text interpreter as you read through this chapter, for more
 3407: detail @pxref{The Text Interpreter}).
 3408: 
 3409: Although it's not obvious, Forth is actually waiting for your
 3410: input. Type a number and press the @key{RET} key:
 3411: 
 3412: @example
 3413: @kbd{45@key{RET}}  ok
 3414: @end example
 3415: 
 3416: Rather than give you a prompt to invite you to input something, the text
 3417: interpreter prints a status message @i{after} it has processed a line
 3418: of input. The status message in this case (``@code{ ok}'' followed by
 3419: carriage-return) indicates that the text interpreter was able to process
 3420: all of your input successfully. Now type something illegal:
 3421: 
 3422: @example
 3423: @kbd{qwer341@key{RET}}
 3424: *the terminal*:2: Undefined word
 3425: >>>qwer341<<<
 3426: Backtrace:
 3427: $2A95B42A20 throw 
 3428: $2A95B57FB8 no.extensions 
 3429: @end example
 3430: 
 3431: The exact text, other than the ``Undefined word'' may differ slightly
 3432: on your system, but the effect is the same; when the text interpreter
 3433: detects an error, it discards any remaining text on a line, resets
 3434: certain internal state and prints an error message. For a detailed
 3435: description of error messages see @ref{Error messages}.
 3436: 
 3437: The text interpreter waits for you to press carriage-return, and then
 3438: processes your input line. Starting at the beginning of the line, it
 3439: breaks the line into groups of characters separated by spaces. For each
 3440: group of characters in turn, it makes two attempts to do something:
 3441: 
 3442: @itemize @bullet
 3443: @item
 3444: @cindex name dictionary
 3445: It tries to treat it as a command. It does this by searching a @dfn{name
 3446: dictionary}. If the group of characters matches an entry in the name
 3447: dictionary, the name dictionary provides the text interpreter with
 3448: information that allows the text interpreter perform some actions. In
 3449: Forth jargon, we say that the group
 3450: @cindex word
 3451: @cindex definition
 3452: @cindex execution token
 3453: @cindex xt
 3454: of characters names a @dfn{word}, that the dictionary search returns an
 3455: @dfn{execution token (xt)} corresponding to the @dfn{definition} of the
 3456: word, and that the text interpreter executes the xt. Often, the terms
 3457: @dfn{word} and @dfn{definition} are used interchangeably.
 3458: @item
 3459: If the text interpreter fails to find a match in the name dictionary, it
 3460: tries to treat the group of characters as a number in the current number
 3461: base (when you start up Forth, the current number base is base 10). If
 3462: the group of characters legitimately represents a number, the text
 3463: interpreter pushes the number onto a stack (we'll learn more about that
 3464: in the next section).
 3465: @end itemize
 3466: 
 3467: If the text interpreter is unable to do either of these things with any
 3468: group of characters, it discards the group of characters and the rest of
 3469: the line, then prints an error message. If the text interpreter reaches
 3470: the end of the line without error, it prints the status message ``@code{ ok}''
 3471: followed by carriage-return.
 3472: 
 3473: This is the simplest command we can give to the text interpreter:
 3474: 
 3475: @example
 3476: @key{RET}  ok
 3477: @end example
 3478: 
 3479: The text interpreter did everything we asked it to do (nothing) without
 3480: an error, so it said that everything is ``@code{ ok}''. Try a slightly longer
 3481: command:
 3482: 
 3483: @example
 3484: @kbd{12 dup fred dup@key{RET}}
 3485: *the terminal*:3: Undefined word
 3486: 12 dup >>>fred<<< dup
 3487: Backtrace:
 3488: $2A95B42A20 throw 
 3489: $2A95B57FB8 no.extensions 
 3490: @end example
 3491: 
 3492: When you press the carriage-return key, the text interpreter starts to
 3493: work its way along the line:
 3494: 
 3495: @itemize @bullet
 3496: @item
 3497: When it gets to the space after the @code{2}, it takes the group of
 3498: characters @code{12} and looks them up in the name
 3499: dictionary@footnote{We can't tell if it found them or not, but assume
 3500: for now that it did not}. There is no match for this group of characters
 3501: in the name dictionary, so it tries to treat them as a number. It is
 3502: able to do this successfully, so it puts the number, 12, ``on the stack''
 3503: (whatever that means).
 3504: @item
 3505: The text interpreter resumes scanning the line and gets the next group
 3506: of characters, @code{dup}. It looks it up in the name dictionary and
 3507: (you'll have to take my word for this) finds it, and executes the word
 3508: @code{dup} (whatever that means).
 3509: @item
 3510: Once again, the text interpreter resumes scanning the line and gets the
 3511: group of characters @code{fred}. It looks them up in the name
 3512: dictionary, but can't find them. It tries to treat them as a number, but
 3513: they don't represent any legal number.
 3514: @end itemize
 3515: 
 3516: At this point, the text interpreter gives up and prints an error
 3517: message. The error message shows exactly how far the text interpreter
 3518: got in processing the line. In particular, it shows that the text
 3519: interpreter made no attempt to do anything with the final character
 3520: group, @code{dup}, even though we have good reason to believe that the
 3521: text interpreter would have no problem looking that word up and
 3522: executing it a second time.
 3523: 
 3524: 
 3525: @comment ----------------------------------------------
 3526: @node Stacks and Postfix notation, Your first definition, Introducing the Text Interpreter, Introduction
 3527: @section Stacks, postfix notation and parameter passing
 3528: @cindex text interpreter
 3529: @cindex outer interpreter
 3530: 
 3531: In procedural programming languages (like C and Pascal), the
 3532: building-block of programs is the @dfn{function} or @dfn{procedure}. These
 3533: functions or procedures are called with @dfn{explicit parameters}. For
 3534: example, in C we might write:
 3535: 
 3536: @example
 3537: total = total + new_volume(length,height,depth);
 3538: @end example
 3539: 
 3540: @noindent
 3541: where new_volume is a function-call to another piece of code, and total,
 3542: length, height and depth are all variables. length, height and depth are
 3543: parameters to the function-call.
 3544: 
 3545: In Forth, the equivalent of the function or procedure is the
 3546: @dfn{definition} and parameters are implicitly passed between
 3547: definitions using a shared stack that is visible to the
 3548: programmer. Although Forth does support variables, the existence of the
 3549: stack means that they are used far less often than in most other
 3550: programming languages. When the text interpreter encounters a number, it
 3551: will place (@dfn{push}) it on the stack. There are several stacks (the
 3552: actual number is implementation-dependent ...) and the particular stack
 3553: used for any operation is implied unambiguously by the operation being
 3554: performed. The stack used for all integer operations is called the @dfn{data
 3555: stack} and, since this is the stack used most commonly, references to
 3556: ``the data stack'' are often abbreviated to ``the stack''.
 3557: 
 3558: The stacks have a last-in, first-out (LIFO) organisation. If you type:
 3559: 
 3560: @example
 3561: @kbd{1 2 3@key{RET}}  ok
 3562: @end example
 3563: 
 3564: Then this instructs the text interpreter to placed three numbers on the
 3565: (data) stack. An analogy for the behaviour of the stack is to take a
 3566: pack of playing cards and deal out the ace (1), 2 and 3 into a pile on
 3567: the table. The 3 was the last card onto the pile (``last-in'') and if
 3568: you take a card off the pile then, unless you're prepared to fiddle a
 3569: bit, the card that you take off will be the 3 (``first-out''). The
 3570: number that will be first-out of the stack is called the @dfn{top of
 3571: stack}, which
 3572: @cindex TOS definition
 3573: is often abbreviated to @dfn{TOS}.
 3574: 
 3575: To understand how parameters are passed in Forth, consider the
 3576: behaviour of the definition @code{+} (pronounced ``plus''). You will not
 3577: be surprised to learn that this definition performs addition. More
 3578: precisely, it adds two number together and produces a result. Where does
 3579: it get the two numbers from? It takes the top two numbers off the
 3580: stack. Where does it place the result? On the stack. You can act-out the
 3581: behaviour of @code{+} with your playing cards like this:
 3582: 
 3583: @itemize @bullet
 3584: @item
 3585: Pick up two cards from the stack on the table
 3586: @item
 3587: Stare at them intently and ask yourself ``what @i{is} the sum of these two
 3588: numbers''
 3589: @item
 3590: Decide that the answer is 5
 3591: @item
 3592: Shuffle the two cards back into the pack and find a 5
 3593: @item
 3594: Put a 5 on the remaining ace that's on the table.
 3595: @end itemize
 3596: 
 3597: If you don't have a pack of cards handy but you do have Forth running,
 3598: you can use the definition @code{.s} to show the current state of the stack,
 3599: without affecting the stack. Type:
 3600: 
 3601: @example
 3602: @kbd{clearstacks 1 2 3@key{RET}} ok
 3603: @kbd{.s@key{RET}} <3> 1 2 3  ok
 3604: @end example
 3605: 
 3606: The text interpreter looks up the word @code{clearstacks} and executes
 3607: it; it tidies up the stacks and removes any entries that may have been
 3608: left on it by earlier examples. The text interpreter pushes each of the
 3609: three numbers in turn onto the stack. Finally, the text interpreter
 3610: looks up the word @code{.s} and executes it. The effect of executing
 3611: @code{.s} is to print the ``<3>'' (the total number of items on the stack)
 3612: followed by a list of all the items on the stack; the item on the far
 3613: right-hand side is the TOS.
 3614: 
 3615: You can now type:
 3616: 
 3617: @example
 3618: @kbd{+ .s@key{RET}} <2> 1 5  ok
 3619: @end example
 3620: 
 3621: @noindent
 3622: which is correct; there are now 2 items on the stack and the result of
 3623: the addition is 5.
 3624: 
 3625: If you're playing with cards, try doing a second addition: pick up the
 3626: two cards, work out that their sum is 6, shuffle them into the pack,
 3627: look for a 6 and place that on the table. You now have just one item on
 3628: the stack. What happens if you try to do a third addition? Pick up the
 3629: first card, pick up the second card -- ah! There is no second card. This
 3630: is called a @dfn{stack underflow} and consitutes an error. If you try to
 3631: do the same thing with Forth it often reports an error (probably a Stack
 3632: Underflow or an Invalid Memory Address error).
 3633: 
 3634: The opposite situation to a stack underflow is a @dfn{stack overflow},
 3635: which simply accepts that there is a finite amount of storage space
 3636: reserved for the stack. To stretch the playing card analogy, if you had
 3637: enough packs of cards and you piled the cards up on the table, you would
 3638: eventually be unable to add another card; you'd hit the ceiling. Gforth
 3639: allows you to set the maximum size of the stacks. In general, the only
 3640: time that you will get a stack overflow is because a definition has a
 3641: bug in it and is generating data on the stack uncontrollably.
 3642: 
 3643: There's one final use for the playing card analogy. If you model your
 3644: stack using a pack of playing cards, the maximum number of items on
 3645: your stack will be 52 (I assume you didn't use the Joker). The maximum
 3646: @i{value} of any item on the stack is 13 (the King). In fact, the only
 3647: possible numbers are positive integer numbers 1 through 13; you can't
 3648: have (for example) 0 or 27 or 3.52 or -2. If you change the way you
 3649: think about some of the cards, you can accommodate different
 3650: numbers. For example, you could think of the Jack as representing 0,
 3651: the Queen as representing -1 and the King as representing -2. Your
 3652: @i{range} remains unchanged (you can still only represent a total of 13
 3653: numbers) but the numbers that you can represent are -2 through 10.
 3654: 
 3655: In that analogy, the limit was the amount of information that a single
 3656: stack entry could hold, and Forth has a similar limit. In Forth, the
 3657: size of a stack entry is called a @dfn{cell}. The actual size of a cell is
 3658: implementation dependent and affects the maximum value that a stack
 3659: entry can hold. A Standard Forth provides a cell size of at least
 3660: 16-bits, and most desktop systems use a cell size of 32-bits.
 3661: 
 3662: Forth does not do any type checking for you, so you are free to
 3663: manipulate and combine stack items in any way you wish. A convenient way
 3664: of treating stack items is as 2's complement signed integers, and that
 3665: is what Standard words like @code{+} do. Therefore you can type:
 3666: 
 3667: @example
 3668: @kbd{-5 12 + .s@key{RET}} <1> 7  ok
 3669: @end example
 3670: 
 3671: If you use numbers and definitions like @code{+} in order to turn Forth
 3672: into a great big pocket calculator, you will realise that it's rather
 3673: different from a normal calculator. Rather than typing 2 + 3 = you had
 3674: to type 2 3 + (ignore the fact that you had to use @code{.s} to see the
 3675: result). The terminology used to describe this difference is to say that
 3676: your calculator uses @dfn{Infix Notation} (parameters and operators are
 3677: mixed) whilst Forth uses @dfn{Postfix Notation} (parameters and
 3678: operators are separate), also called @dfn{Reverse Polish Notation}.
 3679: 
 3680: Whilst postfix notation might look confusing to begin with, it has
 3681: several important advantages:
 3682: 
 3683: @itemize @bullet
 3684: @item
 3685: it is unambiguous
 3686: @item
 3687: it is more concise
 3688: @item
 3689: it fits naturally with a stack-based system
 3690: @end itemize
 3691: 
 3692: To examine these claims in more detail, consider these sums:
 3693: 
 3694: @example
 3695: 6 + 5 * 4 =
 3696: 4 * 5 + 6 =
 3697: @end example
 3698: 
 3699: If you're just learning maths or your maths is very rusty, you will
 3700: probably come up with the answer 44 for the first and 26 for the
 3701: second. If you are a bit of a whizz at maths you will remember the
 3702: @i{convention} that multiplication takes precendence over addition, and
 3703: you'd come up with the answer 26 both times. To explain the answer 26
 3704: to someone who got the answer 44, you'd probably rewrite the first sum
 3705: like this:
 3706: 
 3707: @example
 3708: 6 + (5 * 4) =
 3709: @end example
 3710: 
 3711: If what you really wanted was to perform the addition before the
 3712: multiplication, you would have to use parentheses to force it.
 3713: 
 3714: If you did the first two sums on a pocket calculator you would probably
 3715: get the right answers, unless you were very cautious and entered them using
 3716: these keystroke sequences:
 3717: 
 3718: 6 + 5 = * 4 =
 3719: 4 * 5 = + 6 =
 3720: 
 3721: Postfix notation is unambiguous because the order that the operators
 3722: are applied is always explicit; that also means that parentheses are
 3723: never required. The operators are @i{active} (the act of quoting the
 3724: operator makes the operation occur) which removes the need for ``=''.
 3725: 
 3726: The sum 6 + 5 * 4 can be written (in postfix notation) in two
 3727: equivalent ways:
 3728: 
 3729: @example
 3730: 6 5 4 * +      or:
 3731: 5 4 * 6 +
 3732: @end example
 3733: 
 3734: An important thing that you should notice about this notation is that
 3735: the @i{order} of the numbers does not change; if you want to subtract
 3736: 2 from 10 you type @code{10 2 -}.
 3737: 
 3738: The reason that Forth uses postfix notation is very simple to explain: it
 3739: makes the implementation extremely simple, and it follows naturally from
 3740: using the stack as a mechanism for passing parameters. Another way of
 3741: thinking about this is to realise that all Forth definitions are
 3742: @i{active}; they execute as they are encountered by the text
 3743: interpreter. The result of this is that the syntax of Forth is trivially
 3744: simple.
 3745: 
 3746: 
 3747: 
 3748: @comment ----------------------------------------------
 3749: @node Your first definition, How does that work?, Stacks and Postfix notation, Introduction
 3750: @section Your first Forth definition
 3751: @cindex first definition
 3752: 
 3753: Until now, the examples we've seen have been trivial; we've just been
 3754: using Forth as a bigger-than-pocket calculator. Also, each calculation
 3755: we've shown has been a ``one-off'' -- to repeat it we'd need to type it in
 3756: again@footnote{That's not quite true. If you press the up-arrow key on
 3757: your keyboard you should be able to scroll back to any earlier command,
 3758: edit it and re-enter it.} In this section we'll see how to add new
 3759: words to Forth's vocabulary.
 3760: 
 3761: The easiest way to create a new word is to use a @dfn{colon
 3762: definition}. We'll define a few and try them out before worrying too
 3763: much about how they work. Try typing in these examples; be careful to
 3764: copy the spaces accurately:
 3765: 
 3766: @example
 3767: : add-two 2 + . ;
 3768: : greet ." Hello and welcome" ;
 3769: : demo 5 add-two ;
 3770: @end example
 3771: 
 3772: @noindent
 3773: Now try them out:
 3774: 
 3775: @example
 3776: @kbd{greet@key{RET}} Hello and welcome  ok
 3777: @kbd{greet greet@key{RET}} Hello and welcomeHello and welcome  ok
 3778: @kbd{4 add-two@key{RET}} 6  ok
 3779: @kbd{demo@key{RET}} 7  ok
 3780: @kbd{9 greet demo add-two@key{RET}} Hello and welcome7 11  ok
 3781: @end example
 3782: 
 3783: The first new thing that we've introduced here is the pair of words
 3784: @code{:} and @code{;}. These are used to start and terminate a new
 3785: definition, respectively. The first word after the @code{:} is the name
 3786: for the new definition.
 3787: 
 3788: As you can see from the examples, a definition is built up of words that
 3789: have already been defined; Forth makes no distinction between
 3790: definitions that existed when you started the system up, and those that
 3791: you define yourself.
 3792: 
 3793: The examples also introduce the words @code{.} (dot), @code{."}
 3794: (dot-quote) and @code{dup} (dewp). Dot takes the value from the top of
 3795: the stack and displays it. It's like @code{.s} except that it only
 3796: displays the top item of the stack and it is destructive; after it has
 3797: executed, the number is no longer on the stack. There is always one
 3798: space printed after the number, and no spaces before it. Dot-quote
 3799: defines a string (a sequence of characters) that will be printed when
 3800: the word is executed. The string can contain any printable characters
 3801: except @code{"}. A @code{"} has a special function; it is not a Forth
 3802: word but it acts as a delimiter (the way that delimiters work is
 3803: described in the next section). Finally, @code{dup} duplicates the value
 3804: at the top of the stack. Try typing @code{5 dup .s} to see what it does.
 3805: 
 3806: We already know that the text interpreter searches through the
 3807: dictionary to locate names. If you've followed the examples earlier, you
 3808: will already have a definition called @code{add-two}. Lets try modifying
 3809: it by typing in a new definition:
 3810: 
 3811: @example
 3812: @kbd{: add-two dup . ." + 2 =" 2 + . ;@key{RET}} redefined add-two  ok
 3813: @end example
 3814: 
 3815: Forth recognised that we were defining a word that already exists, and
 3816: printed a message to warn us of that fact. Let's try out the new
 3817: definition:
 3818: 
 3819: @example
 3820: @kbd{9 add-two@key{RET}} 9 + 2 =11  ok
 3821: @end example
 3822: 
 3823: @noindent
 3824: All that we've actually done here, though, is to create a new
 3825: definition, with a particular name. The fact that there was already a
 3826: definition with the same name did not make any difference to the way
 3827: that the new definition was created (except that Forth printed a warning
 3828: message). The old definition of add-two still exists (try @code{demo}
 3829: again to see that this is true). Any new definition will use the new
 3830: definition of @code{add-two}, but old definitions continue to use the
 3831: version that already existed at the time that they were @code{compiled}.
 3832: 
 3833: Before you go on to the next section, try defining and redefining some
 3834: words of your own.
 3835: 
 3836: @comment ----------------------------------------------
 3837: @node How does that work?, Forth is written in Forth, Your first definition, Introduction
 3838: @section How does that work?
 3839: @cindex parsing words
 3840: 
 3841: @c That's pretty deep (IMO way too deep) for an introduction. - anton
 3842: 
 3843: @c Is it a good idea to talk about the interpretation semantics of a
 3844: @c number? We don't have an xt to go along with it. - anton
 3845: 
 3846: @c Now that I have eliminated execution semantics, I wonder if it would not
 3847: @c be better to keep them (or add run-time semantics), to make it easier to
 3848: @c explain what compilation semantics usually does. - anton
 3849: 
 3850: @c nac-> I removed the term ``default compilation sematics'' from the
 3851: @c introductory chapter. Removing ``execution semantics'' was making
 3852: @c everything simpler to explain, then I think the use of this term made
 3853: @c everything more complex again. I replaced it with ``default
 3854: @c semantics'' (which is used elsewhere in the manual) by which I mean
 3855: @c ``a definition that has neither the immediate nor the compile-only
 3856: @c flag set''.
 3857: 
 3858: @c anton: I have eliminated default semantics (except in one place where it
 3859: @c means "default interpretation and compilation semantics"), because it
 3860: @c makes no sense in the presence of combined words.  I reverted to
 3861: @c "execution semantics" where necessary.
 3862: 
 3863: @c nac-> I reworded big chunks of the ``how does that work''
 3864: @c section (and, unusually for me, I think I even made it shorter!).  See
 3865: @c what you think -- I know I have not addressed your primary concern
 3866: @c that it is too heavy-going for an introduction. From what I understood
 3867: @c of your course notes it looks as though they might be a good framework. 
 3868: @c Things that I've tried to capture here are some things that came as a
 3869: @c great revelation here when I first understood them. Also, I like the
 3870: @c fact that a very simple code example shows up almost all of the issues
 3871: @c that you need to understand to see how Forth works. That's unique and
 3872: @c worthwhile to emphasise.
 3873: 
 3874: @c anton: I think it's a good idea to present the details, especially those
 3875: @c that you found to be a revelation, and probably the tutorial tries to be
 3876: @c too superficial and does not get some of the things across that make
 3877: @c Forth special.  I do believe that most of the time these things should
 3878: @c be discussed at the end of a section or in separate sections instead of
 3879: @c in the middle of a section (e.g., the stuff you added in "User-defined
 3880: @c defining words" leads in a completely different direction from the rest
 3881: @c of the section).
 3882: 
 3883: Now we're going to take another look at the definition of @code{add-two}
 3884: from the previous section. From our knowledge of the way that the text
 3885: interpreter works, we would have expected this result when we tried to
 3886: define @code{add-two}:
 3887: 
 3888: @example
 3889: @kbd{: add-two 2 + . ;@key{RET}}
 3890: *the terminal*:4: Undefined word
 3891: : >>>add-two<<< 2 + . ;
 3892: @end example
 3893: 
 3894: The reason that this didn't happen is bound up in the way that @code{:}
 3895: works. The word @code{:} does two special things. The first special
 3896: thing that it does prevents the text interpreter from ever seeing the
 3897: characters @code{add-two}. The text interpreter uses a variable called
 3898: @cindex modifying >IN
 3899: @code{>IN} (pronounced ``to-in'') to keep track of where it is in the
 3900: input line. When it encounters the word @code{:} it behaves in exactly
 3901: the same way as it does for any other word; it looks it up in the name
 3902: dictionary, finds its xt and executes it. When @code{:} executes, it
 3903: looks at the input buffer, finds the word @code{add-two} and advances the
 3904: value of @code{>IN} to point past it. It then does some other stuff
 3905: associated with creating the new definition (including creating an entry
 3906: for @code{add-two} in the name dictionary). When the execution of @code{:}
 3907: completes, control returns to the text interpreter, which is oblivious
 3908: to the fact that it has been tricked into ignoring part of the input
 3909: line.
 3910: 
 3911: @cindex parsing words
 3912: Words like @code{:} -- words that advance the value of @code{>IN} and so
 3913: prevent the text interpreter from acting on the whole of the input line
 3914: -- are called @dfn{parsing words}.
 3915: 
 3916: @cindex @code{state} - effect on the text interpreter
 3917: @cindex text interpreter - effect of state
 3918: The second special thing that @code{:} does is change the value of a
 3919: variable called @code{state}, which affects the way that the text
 3920: interpreter behaves. When Gforth starts up, @code{state} has the value
 3921: 0, and the text interpreter is said to be @dfn{interpreting}. During a
 3922: colon definition (started with @code{:}), @code{state} is set to -1 and
 3923: the text interpreter is said to be @dfn{compiling}.
 3924: 
 3925: In this example, the text interpreter is compiling when it processes the
 3926: string ``@code{2 + . ;}''. It still breaks the string down into
 3927: character sequences in the same way. However, instead of pushing the
 3928: number @code{2} onto the stack, it lays down (@dfn{compiles}) some magic
 3929: into the definition of @code{add-two} that will make the number @code{2} get
 3930: pushed onto the stack when @code{add-two} is @dfn{executed}. Similarly,
 3931: the behaviours of @code{+} and @code{.} are also compiled into the
 3932: definition.
 3933: 
 3934: One category of words don't get compiled. These so-called @dfn{immediate
 3935: words} get executed (performed @i{now}) regardless of whether the text
 3936: interpreter is interpreting or compiling. The word @code{;} is an
 3937: immediate word. Rather than being compiled into the definition, it
 3938: executes. Its effect is to terminate the current definition, which
 3939: includes changing the value of @code{state} back to 0.
 3940: 
 3941: When you execute @code{add-two}, it has a @dfn{run-time effect} that is
 3942: exactly the same as if you had typed @code{2 + . @key{RET}} outside of a
 3943: definition.
 3944: 
 3945: In Forth, every word or number can be described in terms of two
 3946: properties:
 3947: 
 3948: @itemize @bullet
 3949: @item
 3950: @cindex interpretation semantics
 3951: Its @dfn{interpretation semantics} describe how it will behave when the
 3952: text interpreter encounters it in @dfn{interpret} state. The
 3953: interpretation semantics of a word are represented by an @dfn{execution
 3954: token}.
 3955: @item
 3956: @cindex compilation semantics
 3957: Its @dfn{compilation semantics} describe how it will behave when the
 3958: text interpreter encounters it in @dfn{compile} state. The compilation
 3959: semantics of a word are represented in an implementation-dependent way;
 3960: Gforth uses a @dfn{compilation token}.
 3961: @end itemize
 3962: 
 3963: @noindent
 3964: Numbers are always treated in a fixed way:
 3965: 
 3966: @itemize @bullet
 3967: @item
 3968: When the number is @dfn{interpreted}, its behaviour is to push the
 3969: number onto the stack.
 3970: @item
 3971: When the number is @dfn{compiled}, a piece of code is appended to the
 3972: current definition that pushes the number when it runs. (In other words,
 3973: the compilation semantics of a number are to postpone its interpretation
 3974: semantics until the run-time of the definition that it is being compiled
 3975: into.)
 3976: @end itemize
 3977: 
 3978: Words don't behave in such a regular way, but most have @i{default
 3979: semantics} which means that they behave like this:
 3980: 
 3981: @itemize @bullet
 3982: @item
 3983: The @dfn{interpretation semantics} of the word are to do something useful.
 3984: @item
 3985: The @dfn{compilation semantics} of the word are to append its
 3986: @dfn{interpretation semantics} to the current definition (so that its
 3987: run-time behaviour is to do something useful).
 3988: @end itemize
 3989: 
 3990: @cindex immediate words
 3991: The actual behaviour of any particular word can be controlled by using
 3992: the words @code{immediate} and @code{compile-only} when the word is
 3993: defined. These words set flags in the name dictionary entry of the most
 3994: recently defined word, and these flags are retrieved by the text
 3995: interpreter when it finds the word in the name dictionary.
 3996: 
 3997: A word that is marked as @dfn{immediate} has compilation semantics that
 3998: are identical to its interpretation semantics. In other words, it
 3999: behaves like this:
 4000: 
 4001: @itemize @bullet
 4002: @item
 4003: The @dfn{interpretation semantics} of the word are to do something useful.
 4004: @item
 4005: The @dfn{compilation semantics} of the word are to do something useful
 4006: (and actually the same thing); i.e., it is executed during compilation.
 4007: @end itemize
 4008: 
 4009: Marking a word as @dfn{compile-only} prohibits the text interpreter from
 4010: performing the interpretation semantics of the word directly; an attempt
 4011: to do so will generate an error. It is never necessary to use
 4012: @code{compile-only} (and it is not even part of ANS Forth, though it is
 4013: provided by many implementations) but it is good etiquette to apply it
 4014: to a word that will not behave correctly (and might have unexpected
 4015: side-effects) in interpret state. For example, it is only legal to use
 4016: the conditional word @code{IF} within a definition. If you forget this
 4017: and try to use it elsewhere, the fact that (in Gforth) it is marked as
 4018: @code{compile-only} allows the text interpreter to generate a helpful
 4019: error message rather than subjecting you to the consequences of your
 4020: folly.
 4021: 
 4022: This example shows the difference between an immediate and a
 4023: non-immediate word:
 4024: 
 4025: @example
 4026: : show-state state @@ . ;
 4027: : show-state-now show-state ; immediate
 4028: : word1 show-state ;
 4029: : word2 show-state-now ;
 4030: @end example
 4031: 
 4032: The word @code{immediate} after the definition of @code{show-state-now}
 4033: makes that word an immediate word. These definitions introduce a new
 4034: word: @code{@@} (pronounced ``fetch''). This word fetches the value of a
 4035: variable, and leaves it on the stack. Therefore, the behaviour of
 4036: @code{show-state} is to print a number that represents the current value
 4037: of @code{state}.
 4038: 
 4039: When you execute @code{word1}, it prints the number 0, indicating that
 4040: the system is interpreting. When the text interpreter compiled the
 4041: definition of @code{word1}, it encountered @code{show-state} whose
 4042: compilation semantics are to append its interpretation semantics to the
 4043: current definition. When you execute @code{word1}, it performs the
 4044: interpretation semantics of @code{show-state}.  At the time that @code{word1}
 4045: (and therefore @code{show-state}) are executed, the system is
 4046: interpreting.
 4047: 
 4048: When you pressed @key{RET} after entering the definition of @code{word2},
 4049: you should have seen the number -1 printed, followed by ``@code{
 4050: ok}''. When the text interpreter compiled the definition of
 4051: @code{word2}, it encountered @code{show-state-now}, an immediate word,
 4052: whose compilation semantics are therefore to perform its interpretation
 4053: semantics. It is executed straight away (even before the text
 4054: interpreter has moved on to process another group of characters; the
 4055: @code{;} in this example). The effect of executing it are to display the
 4056: value of @code{state} @i{at the time that the definition of}
 4057: @code{word2} @i{is being defined}. Printing -1 demonstrates that the
 4058: system is compiling at this time. If you execute @code{word2} it does
 4059: nothing at all.
 4060: 
 4061: @cindex @code{."}, how it works
 4062: Before leaving the subject of immediate words, consider the behaviour of
 4063: @code{."} in the definition of @code{greet}, in the previous
 4064: section. This word is both a parsing word and an immediate word. Notice
 4065: that there is a space between @code{."} and the start of the text
 4066: @code{Hello and welcome}, but that there is no space between the last
 4067: letter of @code{welcome} and the @code{"} character. The reason for this
 4068: is that @code{."} is a Forth word; it must have a space after it so that
 4069: the text interpreter can identify it. The @code{"} is not a Forth word;
 4070: it is a @dfn{delimiter}. The examples earlier show that, when the string
 4071: is displayed, there is neither a space before the @code{H} nor after the
 4072: @code{e}. Since @code{."} is an immediate word, it executes at the time
 4073: that @code{greet} is defined. When it executes, its behaviour is to
 4074: search forward in the input line looking for the delimiter. When it
 4075: finds the delimiter, it updates @code{>IN} to point past the
 4076: delimiter. It also compiles some magic code into the definition of
 4077: @code{greet}; the xt of a run-time routine that prints a text string. It
 4078: compiles the string @code{Hello and welcome} into memory so that it is
 4079: available to be printed later. When the text interpreter gains control,
 4080: the next word it finds in the input stream is @code{;} and so it
 4081: terminates the definition of @code{greet}.
 4082: 
 4083: 
 4084: @comment ----------------------------------------------
 4085: @node Forth is written in Forth, Review - elements of a Forth system, How does that work?, Introduction
 4086: @section Forth is written in Forth
 4087: @cindex structure of Forth programs
 4088: 
 4089: When you start up a Forth compiler, a large number of definitions
 4090: already exist. In Forth, you develop a new application using bottom-up
 4091: programming techniques to create new definitions that are defined in
 4092: terms of existing definitions. As you create each definition you can
 4093: test and debug it interactively.
 4094: 
 4095: If you have tried out the examples in this section, you will probably
 4096: have typed them in by hand; when you leave Gforth, your definitions will
 4097: be lost. You can avoid this by using a text editor to enter Forth source
 4098: code into a file, and then loading code from the file using
 4099: @code{include} (@pxref{Forth source files}). A Forth source file is
 4100: processed by the text interpreter, just as though you had typed it in by
 4101: hand@footnote{Actually, there are some subtle differences -- see
 4102: @ref{The Text Interpreter}.}.
 4103: 
 4104: Gforth also supports the traditional Forth alternative to using text
 4105: files for program entry (@pxref{Blocks}).
 4106: 
 4107: In common with many, if not most, Forth compilers, most of Gforth is
 4108: actually written in Forth. All of the @file{.fs} files in the
 4109: installation directory@footnote{For example,
 4110: @file{/usr/local/share/gforth...}} are Forth source files, which you can
 4111: study to see examples of Forth programming.
 4112: 
 4113: Gforth maintains a history file that records every line that you type to
 4114: the text interpreter. This file is preserved between sessions, and is
 4115: used to provide a command-line recall facility. If you enter long
 4116: definitions by hand, you can use a text editor to paste them out of the
 4117: history file into a Forth source file for reuse at a later time
 4118: (for more information @pxref{Command-line editing}).
 4119: 
 4120: 
 4121: @comment ----------------------------------------------
 4122: @node Review - elements of a Forth system, Where to go next, Forth is written in Forth, Introduction
 4123: @section Review - elements of a Forth system
 4124: @cindex elements of a Forth system
 4125: 
 4126: To summarise this chapter:
 4127: 
 4128: @itemize @bullet
 4129: @item
 4130: Forth programs use @dfn{factoring} to break a problem down into small
 4131: fragments called @dfn{words} or @dfn{definitions}.
 4132: @item
 4133: Forth program development is an interactive process.
 4134: @item
 4135: The main command loop that accepts input, and controls both
 4136: interpretation and compilation, is called the @dfn{text interpreter}
 4137: (also known as the @dfn{outer interpreter}).
 4138: @item
 4139: Forth has a very simple syntax, consisting of words and numbers
 4140: separated by spaces or carriage-return characters. Any additional syntax
 4141: is imposed by @dfn{parsing words}.
 4142: @item
 4143: Forth uses a stack to pass parameters between words. As a result, it
 4144: uses postfix notation.
 4145: @item
 4146: To use a word that has previously been defined, the text interpreter
 4147: searches for the word in the @dfn{name dictionary}.
 4148: @item
 4149: Words have @dfn{interpretation semantics} and @dfn{compilation semantics}.
 4150: @item
 4151: The text interpreter uses the value of @code{state} to select between
 4152: the use of the @dfn{interpretation semantics} and the  @dfn{compilation
 4153: semantics} of a word that it encounters.
 4154: @item
 4155: The relationship between the @dfn{interpretation semantics} and
 4156: @dfn{compilation semantics} for a word
 4157: depend upon the way in which the word was defined (for example, whether
 4158: it is an @dfn{immediate} word).
 4159: @item
 4160: Forth definitions can be implemented in Forth (called @dfn{high-level
 4161: definitions}) or in some other way (usually a lower-level language and
 4162: as a result often called @dfn{low-level definitions}, @dfn{code
 4163: definitions} or @dfn{primitives}).
 4164: @item
 4165: Many Forth systems are implemented mainly in Forth.
 4166: @end itemize
 4167: 
 4168: 
 4169: @comment ----------------------------------------------
 4170: @node Where to go next, Exercises, Review - elements of a Forth system, Introduction
 4171: @section Where To Go Next
 4172: @cindex where to go next
 4173: 
 4174: Amazing as it may seem, if you have read (and understood) this far, you
 4175: know almost all the fundamentals about the inner workings of a Forth
 4176: system. You certainly know enough to be able to read and understand the
 4177: rest of this manual and the ANS Forth document, to learn more about the
 4178: facilities that Forth in general and Gforth in particular provide. Even
 4179: scarier, you know almost enough to implement your own Forth system.
 4180: However, that's not a good idea just yet... better to try writing some
 4181: programs in Gforth.
 4182: 
 4183: Forth has such a rich vocabulary that it can be hard to know where to
 4184: start in learning it. This section suggests a few sets of words that are
 4185: enough to write small but useful programs. Use the word index in this
 4186: document to learn more about each word, then try it out and try to write
 4187: small definitions using it. Start by experimenting with these words:
 4188: 
 4189: @itemize @bullet
 4190: @item
 4191: Arithmetic: @code{+ - * / /MOD */ ABS INVERT}
 4192: @item
 4193: Comparison: @code{MIN MAX =}
 4194: @item
 4195: Logic: @code{AND OR XOR NOT}
 4196: @item
 4197: Stack manipulation: @code{DUP DROP SWAP OVER}
 4198: @item
 4199: Loops and decisions: @code{IF ELSE ENDIF ?DO I LOOP}
 4200: @item
 4201: Input/Output: @code{. ." EMIT CR KEY}
 4202: @item
 4203: Defining words: @code{: ; CREATE}
 4204: @item
 4205: Memory allocation words: @code{ALLOT ,}
 4206: @item
 4207: Tools: @code{SEE WORDS .S MARKER}
 4208: @end itemize
 4209: 
 4210: When you have mastered those, go on to:
 4211: 
 4212: @itemize @bullet
 4213: @item
 4214: More defining words: @code{VARIABLE CONSTANT VALUE TO CREATE DOES>}
 4215: @item
 4216: Memory access: @code{@@ !}
 4217: @end itemize
 4218: 
 4219: When you have mastered these, there's nothing for it but to read through
 4220: the whole of this manual and find out what you've missed.
 4221: 
 4222: @comment ----------------------------------------------
 4223: @node Exercises,  , Where to go next, Introduction
 4224: @section Exercises
 4225: @cindex exercises
 4226: 
 4227: TODO: provide a set of programming excercises linked into the stuff done
 4228: already and into other sections of the manual. Provide solutions to all
 4229: the exercises in a .fs file in the distribution.
 4230: 
 4231: @c Get some inspiration from Starting Forth and Kelly&Spies.
 4232: 
 4233: @c excercises:
 4234: @c 1. take inches and convert to feet and inches.
 4235: @c 2. take temperature and convert from fahrenheight to celcius;
 4236: @c    may need to care about symmetric vs floored??
 4237: @c 3. take input line and do character substitution
 4238: @c    to encipher or decipher
 4239: @c 4. as above but work on a file for in and out
 4240: @c 5. take input line and convert to pig-latin 
 4241: @c
 4242: @c thing of sets of things to exercise then come up with
 4243: @c problems that need those things.
 4244: 
 4245: 
 4246: @c ******************************************************************
 4247: @node Words, Error messages, Introduction, Top
 4248: @chapter Forth Words
 4249: @cindex words
 4250: 
 4251: @menu
 4252: * Notation::                    
 4253: * Case insensitivity::          
 4254: * Comments::                    
 4255: * Boolean Flags::               
 4256: * Arithmetic::                  
 4257: * Stack Manipulation::          
 4258: * Memory::                      
 4259: * Control Structures::          
 4260: * Defining Words::              
 4261: * Interpretation and Compilation Semantics::  
 4262: * Tokens for Words::            
 4263: * Compiling words::             
 4264: * The Text Interpreter::        
 4265: * The Input Stream::            
 4266: * Word Lists::                  
 4267: * Environmental Queries::       
 4268: * Files::                       
 4269: * Blocks::                      
 4270: * Other I/O::                   
 4271: * OS command line arguments::   
 4272: * Locals::                      
 4273: * Structures::                  
 4274: * Object-oriented Forth::       
 4275: * Programming Tools::           
 4276: * C Interface::                 
 4277: * Assembler and Code Words::    
 4278: * Threading Words::             
 4279: * Passing Commands to the OS::  
 4280: * Keeping track of Time::       
 4281: * Miscellaneous Words::         
 4282: @end menu
 4283: 
 4284: @node Notation, Case insensitivity, Words, Words
 4285: @section Notation
 4286: @cindex notation of glossary entries
 4287: @cindex format of glossary entries
 4288: @cindex glossary notation format
 4289: @cindex word glossary entry format
 4290: 
 4291: The Forth words are described in this section in the glossary notation
 4292: that has become a de-facto standard for Forth texts:
 4293: 
 4294: @format
 4295: @i{word}     @i{Stack effect}   @i{wordset}   @i{pronunciation}
 4296: @end format
 4297: @i{Description}
 4298: 
 4299: @table @var
 4300: @item word
 4301: The name of the word.
 4302: 
 4303: @item Stack effect
 4304: @cindex stack effect
 4305: The stack effect is written in the notation @code{@i{before} --
 4306: @i{after}}, where @i{before} and @i{after} describe the top of
 4307: stack entries before and after the execution of the word. The rest of
 4308: the stack is not touched by the word. The top of stack is rightmost,
 4309: i.e., a stack sequence is written as it is typed in. Note that Gforth
 4310: uses a separate floating point stack, but a unified stack
 4311: notation. Also, return stack effects are not shown in @i{stack
 4312: effect}, but in @i{Description}. The name of a stack item describes
 4313: the type and/or the function of the item. See below for a discussion of
 4314: the types.
 4315: 
 4316: All words have two stack effects: A compile-time stack effect and a
 4317: run-time stack effect. The compile-time stack-effect of most words is
 4318: @i{ -- }. If the compile-time stack-effect of a word deviates from
 4319: this standard behaviour, or the word does other unusual things at
 4320: compile time, both stack effects are shown; otherwise only the run-time
 4321: stack effect is shown.
 4322: 
 4323: @cindex pronounciation of words
 4324: @item pronunciation
 4325: How the word is pronounced.
 4326: 
 4327: @cindex wordset
 4328: @cindex environment wordset
 4329: @item wordset
 4330: The ANS Forth standard is divided into several word sets. A standard
 4331: system need not support all of them. Therefore, in theory, the fewer
 4332: word sets your program uses the more portable it will be. However, we
 4333: suspect that most ANS Forth systems on personal machines will feature
 4334: all word sets. Words that are not defined in ANS Forth have
 4335: @code{gforth} or @code{gforth-internal} as word set. @code{gforth}
 4336: describes words that will work in future releases of Gforth;
 4337: @code{gforth-internal} words are more volatile. Environmental query
 4338: strings are also displayed like words; you can recognize them by the
 4339: @code{environment} in the word set field.
 4340: 
 4341: @item Description
 4342: A description of the behaviour of the word.
 4343: @end table
 4344: 
 4345: @cindex types of stack items
 4346: @cindex stack item types
 4347: The type of a stack item is specified by the character(s) the name
 4348: starts with:
 4349: 
 4350: @table @code
 4351: @item f
 4352: @cindex @code{f}, stack item type
 4353: Boolean flags, i.e. @code{false} or @code{true}.
 4354: @item c
 4355: @cindex @code{c}, stack item type
 4356: Char
 4357: @item w
 4358: @cindex @code{w}, stack item type
 4359: Cell, can contain an integer or an address
 4360: @item n
 4361: @cindex @code{n}, stack item type
 4362: signed integer
 4363: @item u
 4364: @cindex @code{u}, stack item type
 4365: unsigned integer
 4366: @item d
 4367: @cindex @code{d}, stack item type
 4368: double sized signed integer
 4369: @item ud
 4370: @cindex @code{ud}, stack item type
 4371: double sized unsigned integer
 4372: @item r
 4373: @cindex @code{r}, stack item type
 4374: Float (on the FP stack)
 4375: @item a-
 4376: @cindex @code{a_}, stack item type
 4377: Cell-aligned address
 4378: @item c-
 4379: @cindex @code{c_}, stack item type
 4380: Char-aligned address (note that a Char may have two bytes in Windows NT)
 4381: @item f-
 4382: @cindex @code{f_}, stack item type
 4383: Float-aligned address
 4384: @item df-
 4385: @cindex @code{df_}, stack item type
 4386: Address aligned for IEEE double precision float
 4387: @item sf-
 4388: @cindex @code{sf_}, stack item type
 4389: Address aligned for IEEE single precision float
 4390: @item xt
 4391: @cindex @code{xt}, stack item type
 4392: Execution token, same size as Cell
 4393: @item wid
 4394: @cindex @code{wid}, stack item type
 4395: Word list ID, same size as Cell
 4396: @item ior, wior
 4397: @cindex ior type description
 4398: @cindex wior type description
 4399: I/O result code, cell-sized.  In Gforth, you can @code{throw} iors.
 4400: @item f83name
 4401: @cindex @code{f83name}, stack item type
 4402: Pointer to a name structure
 4403: @item "
 4404: @cindex @code{"}, stack item type
 4405: string in the input stream (not on the stack). The terminating character
 4406: is a blank by default. If it is not a blank, it is shown in @code{<>}
 4407: quotes.
 4408: @end table
 4409: 
 4410: @comment ----------------------------------------------
 4411: @node Case insensitivity, Comments, Notation, Words
 4412: @section Case insensitivity
 4413: @cindex case sensitivity
 4414: @cindex upper and lower case
 4415: 
 4416: Gforth is case-insensitive; you can enter definitions and invoke
 4417: Standard words using upper, lower or mixed case (however,
 4418: @pxref{core-idef, Implementation-defined options, Implementation-defined
 4419: options}).
 4420: 
 4421: ANS Forth only @i{requires} implementations to recognise Standard words
 4422: when they are typed entirely in upper case. Therefore, a Standard
 4423: program must use upper case for all Standard words. You can use whatever
 4424: case you like for words that you define, but in a Standard program you
 4425: have to use the words in the same case that you defined them.
 4426: 
 4427: Gforth supports case sensitivity through @code{table}s (case-sensitive
 4428: wordlists, @pxref{Word Lists}).
 4429: 
 4430: Two people have asked how to convert Gforth to be case-sensitive; while
 4431: we think this is a bad idea, you can change all wordlists into tables
 4432: like this:
 4433: 
 4434: @example
 4435: ' table-find forth-wordlist wordlist-map @ !
 4436: @end example
 4437: 
 4438: Note that you now have to type the predefined words in the same case
 4439: that we defined them, which are varying.  You may want to convert them
 4440: to your favourite case before doing this operation (I won't explain how,
 4441: because if you are even contemplating doing this, you'd better have
 4442: enough knowledge of Forth systems to know this already).
 4443: 
 4444: @node Comments, Boolean Flags, Case insensitivity, Words
 4445: @section Comments
 4446: @cindex comments
 4447: 
 4448: Forth supports two styles of comment; the traditional @i{in-line} comment,
 4449: @code{(} and its modern cousin, the @i{comment to end of line}; @code{\}.
 4450: 
 4451: 
 4452: doc-(
 4453: doc-\
 4454: doc-\G
 4455: 
 4456: 
 4457: @node Boolean Flags, Arithmetic, Comments, Words
 4458: @section Boolean Flags
 4459: @cindex Boolean flags
 4460: 
 4461: A Boolean flag is cell-sized. A cell with all bits clear represents the
 4462: flag @code{false} and a flag with all bits set represents the flag
 4463: @code{true}. Words that check a flag (for example, @code{IF}) will treat
 4464: a cell that has @i{any} bit set as @code{true}.
 4465: @c on and off to Memory? 
 4466: @c true and false to "Bitwise operations" or "Numeric comparison"?
 4467: 
 4468: doc-true
 4469: doc-false
 4470: doc-on
 4471: doc-off
 4472: 
 4473: 
 4474: @node Arithmetic, Stack Manipulation, Boolean Flags, Words
 4475: @section Arithmetic
 4476: @cindex arithmetic words
 4477: 
 4478: @cindex division with potentially negative operands
 4479: Forth arithmetic is not checked, i.e., you will not hear about integer
 4480: overflow on addition or multiplication, you may hear about division by
 4481: zero if you are lucky. The operator is written after the operands, but
 4482: the operands are still in the original order. I.e., the infix @code{2-1}
 4483: corresponds to @code{2 1 -}. Forth offers a variety of division
 4484: operators. If you perform division with potentially negative operands,
 4485: you do not want to use @code{/} or @code{/mod} with its undefined
 4486: behaviour, but rather @code{fm/mod} or @code{sm/mod} (probably the
 4487: former, @pxref{Mixed precision}).
 4488: @comment TODO discuss the different division forms and the std approach
 4489: 
 4490: @menu
 4491: * Single precision::            
 4492: * Double precision::            Double-cell integer arithmetic
 4493: * Bitwise operations::          
 4494: * Numeric comparison::          
 4495: * Mixed precision::             Operations with single and double-cell integers
 4496: * Floating Point::              
 4497: @end menu
 4498: 
 4499: @node Single precision, Double precision, Arithmetic, Arithmetic
 4500: @subsection Single precision
 4501: @cindex single precision arithmetic words
 4502: 
 4503: @c !! cell undefined
 4504: 
 4505: By default, numbers in Forth are single-precision integers that are one
 4506: cell in size. They can be signed or unsigned, depending upon how you
 4507: treat them. For the rules used by the text interpreter for recognising
 4508: single-precision integers see @ref{Number Conversion}.
 4509: 
 4510: These words are all defined for signed operands, but some of them also
 4511: work for unsigned numbers: @code{+}, @code{1+}, @code{-}, @code{1-},
 4512: @code{*}.
 4513: 
 4514: doc-+
 4515: doc-1+
 4516: doc-under+
 4517: doc--
 4518: doc-1-
 4519: doc-*
 4520: doc-/
 4521: doc-mod
 4522: doc-/mod
 4523: doc-negate
 4524: doc-abs
 4525: doc-min
 4526: doc-max
 4527: doc-floored
 4528: 
 4529: 
 4530: @node Double precision, Bitwise operations, Single precision, Arithmetic
 4531: @subsection Double precision
 4532: @cindex double precision arithmetic words
 4533: 
 4534: For the rules used by the text interpreter for
 4535: recognising double-precision integers, see @ref{Number Conversion}.
 4536: 
 4537: A double precision number is represented by a cell pair, with the most
 4538: significant cell at the TOS. It is trivial to convert an unsigned single
 4539: to a double: simply push a @code{0} onto the TOS. Since numbers are
 4540: represented by Gforth using 2's complement arithmetic, converting a
 4541: signed single to a (signed) double requires sign-extension across the
 4542: most significant cell. This can be achieved using @code{s>d}. The moral
 4543: of the story is that you cannot convert a number without knowing whether
 4544: it represents an unsigned or a signed number.
 4545: 
 4546: These words are all defined for signed operands, but some of them also
 4547: work for unsigned numbers: @code{d+}, @code{d-}.
 4548: 
 4549: doc-s>d
 4550: doc-d>s
 4551: doc-d+
 4552: doc-d-
 4553: doc-dnegate
 4554: doc-dabs
 4555: doc-dmin
 4556: doc-dmax
 4557: 
 4558: 
 4559: @node Bitwise operations, Numeric comparison, Double precision, Arithmetic
 4560: @subsection Bitwise operations
 4561: @cindex bitwise operation words
 4562: 
 4563: 
 4564: doc-and
 4565: doc-or
 4566: doc-xor
 4567: doc-invert
 4568: doc-lshift
 4569: doc-rshift
 4570: doc-2*
 4571: doc-d2*
 4572: doc-2/
 4573: doc-d2/
 4574: 
 4575: 
 4576: @node Numeric comparison, Mixed precision, Bitwise operations, Arithmetic
 4577: @subsection Numeric comparison
 4578: @cindex numeric comparison words
 4579: 
 4580: Note that the words that compare for equality (@code{= <> 0= 0<> d= d<>
 4581: d0= d0<>}) work for for both signed and unsigned numbers.
 4582: 
 4583: doc-<
 4584: doc-<=
 4585: doc-<>
 4586: doc-=
 4587: doc->
 4588: doc->=
 4589: 
 4590: doc-0<
 4591: doc-0<=
 4592: doc-0<>
 4593: doc-0=
 4594: doc-0>
 4595: doc-0>=
 4596: 
 4597: doc-u<
 4598: doc-u<=
 4599: @c u<> and u= exist but are the same as <> and =
 4600: @c doc-u<>
 4601: @c doc-u=
 4602: doc-u>
 4603: doc-u>=
 4604: 
 4605: doc-within
 4606: 
 4607: doc-d<
 4608: doc-d<=
 4609: doc-d<>
 4610: doc-d=
 4611: doc-d>
 4612: doc-d>=
 4613: 
 4614: doc-d0<
 4615: doc-d0<=
 4616: doc-d0<>
 4617: doc-d0=
 4618: doc-d0>
 4619: doc-d0>=
 4620: 
 4621: doc-du<
 4622: doc-du<=
 4623: @c du<> and du= exist but are the same as d<> and d=
 4624: @c doc-du<>
 4625: @c doc-du=
 4626: doc-du>
 4627: doc-du>=
 4628: 
 4629: 
 4630: @node Mixed precision, Floating Point, Numeric comparison, Arithmetic
 4631: @subsection Mixed precision
 4632: @cindex mixed precision arithmetic words
 4633: 
 4634: 
 4635: doc-m+
 4636: doc-*/
 4637: doc-*/mod
 4638: doc-m*
 4639: doc-um*
 4640: doc-m*/
 4641: doc-um/mod
 4642: doc-fm/mod
 4643: doc-sm/rem
 4644: 
 4645: 
 4646: @node Floating Point,  , Mixed precision, Arithmetic
 4647: @subsection Floating Point
 4648: @cindex floating point arithmetic words
 4649: 
 4650: For the rules used by the text interpreter for
 4651: recognising floating-point numbers see @ref{Number Conversion}.
 4652: 
 4653: Gforth has a separate floating point stack, but the documentation uses
 4654: the unified notation.@footnote{It's easy to generate the separate
 4655: notation from that by just separating the floating-point numbers out:
 4656: e.g. @code{( n r1 u r2 -- r3 )} becomes @code{( n u -- ) ( F: r1 r2 --
 4657: r3 )}.}
 4658: 
 4659: @cindex floating-point arithmetic, pitfalls
 4660: Floating point numbers have a number of unpleasant surprises for the
 4661: unwary (e.g., floating point addition is not associative) and even a few
 4662: for the wary. You should not use them unless you know what you are doing
 4663: or you don't care that the results you get are totally bogus. If you
 4664: want to learn about the problems of floating point numbers (and how to
 4665: avoid them), you might start with @cite{David Goldberg,
 4666: @uref{http://www.validgh.com/goldberg/paper.ps,What Every Computer
 4667: Scientist Should Know About Floating-Point Arithmetic}, ACM Computing
 4668: Surveys 23(1):5@minus{}48, March 1991}.
 4669: 
 4670: 
 4671: doc-d>f
 4672: doc-f>d
 4673: doc-f+
 4674: doc-f-
 4675: doc-f*
 4676: doc-f/
 4677: doc-fnegate
 4678: doc-fabs
 4679: doc-fmax
 4680: doc-fmin
 4681: doc-floor
 4682: doc-fround
 4683: doc-f**
 4684: doc-fsqrt
 4685: doc-fexp
 4686: doc-fexpm1
 4687: doc-fln
 4688: doc-flnp1
 4689: doc-flog
 4690: doc-falog
 4691: doc-f2*
 4692: doc-f2/
 4693: doc-1/f
 4694: doc-precision
 4695: doc-set-precision
 4696: 
 4697: @cindex angles in trigonometric operations
 4698: @cindex trigonometric operations
 4699: Angles in floating point operations are given in radians (a full circle
 4700: has 2 pi radians).
 4701: 
 4702: doc-fsin
 4703: doc-fcos
 4704: doc-fsincos
 4705: doc-ftan
 4706: doc-fasin
 4707: doc-facos
 4708: doc-fatan
 4709: doc-fatan2
 4710: doc-fsinh
 4711: doc-fcosh
 4712: doc-ftanh
 4713: doc-fasinh
 4714: doc-facosh
 4715: doc-fatanh
 4716: doc-pi
 4717: 
 4718: @cindex equality of floats
 4719: @cindex floating-point comparisons
 4720: One particular problem with floating-point arithmetic is that comparison
 4721: for equality often fails when you would expect it to succeed.  For this
 4722: reason approximate equality is often preferred (but you still have to
 4723: know what you are doing).  Also note that IEEE NaNs may compare
 4724: differently from what you might expect.  The comparison words are:
 4725: 
 4726: doc-f~rel
 4727: doc-f~abs
 4728: doc-f~
 4729: doc-f=
 4730: doc-f<>
 4731: 
 4732: doc-f<
 4733: doc-f<=
 4734: doc-f>
 4735: doc-f>=
 4736: 
 4737: doc-f0<
 4738: doc-f0<=
 4739: doc-f0<>
 4740: doc-f0=
 4741: doc-f0>
 4742: doc-f0>=
 4743: 
 4744: 
 4745: @node Stack Manipulation, Memory, Arithmetic, Words
 4746: @section Stack Manipulation
 4747: @cindex stack manipulation words
 4748: 
 4749: @cindex floating-point stack in the standard
 4750: Gforth maintains a number of separate stacks:
 4751: 
 4752: @cindex data stack
 4753: @cindex parameter stack
 4754: @itemize @bullet
 4755: @item
 4756: A data stack (also known as the @dfn{parameter stack}) -- for
 4757: characters, cells, addresses, and double cells.
 4758: 
 4759: @cindex floating-point stack
 4760: @item
 4761: A floating point stack -- for holding floating point (FP) numbers.
 4762: 
 4763: @cindex return stack
 4764: @item
 4765: A return stack -- for holding the return addresses of colon
 4766: definitions and other (non-FP) data.
 4767: 
 4768: @cindex locals stack
 4769: @item
 4770: A locals stack -- for holding local variables.
 4771: @end itemize
 4772: 
 4773: @menu
 4774: * Data stack::                  
 4775: * Floating point stack::        
 4776: * Return stack::                
 4777: * Locals stack::                
 4778: * Stack pointer manipulation::  
 4779: @end menu
 4780: 
 4781: @node Data stack, Floating point stack, Stack Manipulation, Stack Manipulation
 4782: @subsection Data stack
 4783: @cindex data stack manipulation words
 4784: @cindex stack manipulations words, data stack
 4785: 
 4786: 
 4787: doc-drop
 4788: doc-nip
 4789: doc-dup
 4790: doc-over
 4791: doc-tuck
 4792: doc-swap
 4793: doc-pick
 4794: doc-rot
 4795: doc--rot
 4796: doc-?dup
 4797: doc-roll
 4798: doc-2drop
 4799: doc-2nip
 4800: doc-2dup
 4801: doc-2over
 4802: doc-2tuck
 4803: doc-2swap
 4804: doc-2rot
 4805: 
 4806: 
 4807: @node Floating point stack, Return stack, Data stack, Stack Manipulation
 4808: @subsection Floating point stack
 4809: @cindex floating-point stack manipulation words
 4810: @cindex stack manipulation words, floating-point stack
 4811: 
 4812: Whilst every sane Forth has a separate floating-point stack, it is not
 4813: strictly required; an ANS Forth system could theoretically keep
 4814: floating-point numbers on the data stack. As an additional difficulty,
 4815: you don't know how many cells a floating-point number takes. It is
 4816: reportedly possible to write words in a way that they work also for a
 4817: unified stack model, but we do not recommend trying it. Instead, just
 4818: say that your program has an environmental dependency on a separate
 4819: floating-point stack.
 4820: 
 4821: doc-floating-stack
 4822: 
 4823: doc-fdrop
 4824: doc-fnip
 4825: doc-fdup
 4826: doc-fover
 4827: doc-ftuck
 4828: doc-fswap
 4829: doc-fpick
 4830: doc-frot
 4831: 
 4832: 
 4833: @node Return stack, Locals stack, Floating point stack, Stack Manipulation
 4834: @subsection Return stack
 4835: @cindex return stack manipulation words
 4836: @cindex stack manipulation words, return stack
 4837: 
 4838: @cindex return stack and locals
 4839: @cindex locals and return stack
 4840: A Forth system is allowed to keep local variables on the
 4841: return stack. This is reasonable, as local variables usually eliminate
 4842: the need to use the return stack explicitly. So, if you want to produce
 4843: a standard compliant program and you are using local variables in a
 4844: word, forget about return stack manipulations in that word (refer to the
 4845: standard document for the exact rules).
 4846: 
 4847: doc->r
 4848: doc-r>
 4849: doc-r@
 4850: doc-rdrop
 4851: doc-2>r
 4852: doc-2r>
 4853: doc-2r@
 4854: doc-2rdrop
 4855: 
 4856: 
 4857: @node Locals stack, Stack pointer manipulation, Return stack, Stack Manipulation
 4858: @subsection Locals stack
 4859: 
 4860: Gforth uses an extra locals stack.  It is described, along with the
 4861: reasons for its existence, in @ref{Locals implementation}.
 4862: 
 4863: @node Stack pointer manipulation,  , Locals stack, Stack Manipulation
 4864: @subsection Stack pointer manipulation
 4865: @cindex stack pointer manipulation words
 4866: 
 4867: @c removed s0 r0 l0 -- they are obsolete aliases for sp0 rp0 lp0
 4868: doc-sp0
 4869: doc-sp@
 4870: doc-sp!
 4871: doc-fp0
 4872: doc-fp@
 4873: doc-fp!
 4874: doc-rp0
 4875: doc-rp@
 4876: doc-rp!
 4877: doc-lp0
 4878: doc-lp@
 4879: doc-lp!
 4880: 
 4881: 
 4882: @node Memory, Control Structures, Stack Manipulation, Words
 4883: @section Memory
 4884: @cindex memory words
 4885: 
 4886: @menu
 4887: * Memory model::                
 4888: * Dictionary allocation::       
 4889: * Heap Allocation::             
 4890: * Memory Access::               
 4891: * Address arithmetic::          
 4892: * Memory Blocks::               
 4893: @end menu
 4894: 
 4895: In addition to the standard Forth memory allocation words, there is also
 4896: a @uref{http://www.complang.tuwien.ac.at/forth/garbage-collection.zip,
 4897: garbage collector}.
 4898: 
 4899: @node Memory model, Dictionary allocation, Memory, Memory
 4900: @subsection ANS Forth and Gforth memory models
 4901: 
 4902: @c The ANS Forth description is a mess (e.g., is the heap part of
 4903: @c the dictionary?), so let's not stick to closely with it.
 4904: 
 4905: ANS Forth considers a Forth system as consisting of several address
 4906: spaces, of which only @dfn{data space} is managed and accessible with
 4907: the memory words.  Memory not necessarily in data space includes the
 4908: stacks, the code (called code space) and the headers (called name
 4909: space). In Gforth everything is in data space, but the code for the
 4910: primitives is usually read-only.
 4911: 
 4912: Data space is divided into a number of areas: The (data space portion of
 4913: the) dictionary@footnote{Sometimes, the term @dfn{dictionary} is used to
 4914: refer to the search data structure embodied in word lists and headers,
 4915: because it is used for looking up names, just as you would in a
 4916: conventional dictionary.}, the heap, and a number of system-allocated
 4917: buffers.
 4918: 
 4919: @cindex address arithmetic restrictions, ANS vs. Gforth
 4920: @cindex contiguous regions, ANS vs. Gforth
 4921: In ANS Forth data space is also divided into contiguous regions.  You
 4922: can only use address arithmetic within a contiguous region, not between
 4923: them.  Usually each allocation gives you one contiguous region, but the
 4924: dictionary allocation words have additional rules (@pxref{Dictionary
 4925: allocation}).
 4926: 
 4927: Gforth provides one big address space, and address arithmetic can be
 4928: performed between any addresses. However, in the dictionary headers or
 4929: code are interleaved with data, so almost the only contiguous data space
 4930: regions there are those described by ANS Forth as contiguous; but you
 4931: can be sure that the dictionary is allocated towards increasing
 4932: addresses even between contiguous regions.  The memory order of
 4933: allocations in the heap is platform-dependent (and possibly different
 4934: from one run to the next).
 4935: 
 4936: 
 4937: @node Dictionary allocation, Heap Allocation, Memory model, Memory
 4938: @subsection Dictionary allocation
 4939: @cindex reserving data space
 4940: @cindex data space - reserving some
 4941: 
 4942: Dictionary allocation is a stack-oriented allocation scheme, i.e., if
 4943: you want to deallocate X, you also deallocate everything
 4944: allocated after X.
 4945: 
 4946: @cindex contiguous regions in dictionary allocation
 4947: The allocations using the words below are contiguous and grow the region
 4948: towards increasing addresses.  Other words that allocate dictionary
 4949: memory of any kind (i.e., defining words including @code{:noname}) end
 4950: the contiguous region and start a new one.
 4951: 
 4952: In ANS Forth only @code{create}d words are guaranteed to produce an
 4953: address that is the start of the following contiguous region.  In
 4954: particular, the cell allocated by @code{variable} is not guaranteed to
 4955: be contiguous with following @code{allot}ed memory.
 4956: 
 4957: You can deallocate memory by using @code{allot} with a negative argument
 4958: (with some restrictions, see @code{allot}). For larger deallocations use
 4959: @code{marker}.
 4960: 
 4961: 
 4962: doc-here
 4963: doc-unused
 4964: doc-allot
 4965: doc-c,
 4966: doc-f,
 4967: doc-,
 4968: doc-2,
 4969: 
 4970: Memory accesses have to be aligned (@pxref{Address arithmetic}). So of
 4971: course you should allocate memory in an aligned way, too. I.e., before
 4972: allocating allocating a cell, @code{here} must be cell-aligned, etc.
 4973: The words below align @code{here} if it is not already.  Basically it is
 4974: only already aligned for a type, if the last allocation was a multiple
 4975: of the size of this type and if @code{here} was aligned for this type
 4976: before.
 4977: 
 4978: After freshly @code{create}ing a word, @code{here} is @code{align}ed in
 4979: ANS Forth (@code{maxalign}ed in Gforth).
 4980: 
 4981: doc-align
 4982: doc-falign
 4983: doc-sfalign
 4984: doc-dfalign
 4985: doc-maxalign
 4986: doc-cfalign
 4987: 
 4988: 
 4989: @node Heap Allocation, Memory Access, Dictionary allocation, Memory
 4990: @subsection Heap allocation
 4991: @cindex heap allocation
 4992: @cindex dynamic allocation of memory
 4993: @cindex memory-allocation word set
 4994: 
 4995: @cindex contiguous regions and heap allocation
 4996: Heap allocation supports deallocation of allocated memory in any
 4997: order. Dictionary allocation is not affected by it (i.e., it does not
 4998: end a contiguous region). In Gforth, these words are implemented using
 4999: the standard C library calls malloc(), free() and resize().
 5000: 
 5001: The memory region produced by one invocation of @code{allocate} or
 5002: @code{resize} is internally contiguous.  There is no contiguity between
 5003: such a region and any other region (including others allocated from the
 5004: heap).
 5005: 
 5006: doc-allocate
 5007: doc-free
 5008: doc-resize
 5009: 
 5010: 
 5011: @node Memory Access, Address arithmetic, Heap Allocation, Memory
 5012: @subsection Memory Access
 5013: @cindex memory access words
 5014: 
 5015: doc-@
 5016: doc-!
 5017: doc-+!
 5018: doc-c@
 5019: doc-c!
 5020: doc-2@
 5021: doc-2!
 5022: doc-f@
 5023: doc-f!
 5024: doc-sf@
 5025: doc-sf!
 5026: doc-df@
 5027: doc-df!
 5028: doc-sw@
 5029: doc-uw@
 5030: doc-w!
 5031: doc-sl@
 5032: doc-ul@
 5033: doc-l!
 5034: 
 5035: @node Address arithmetic, Memory Blocks, Memory Access, Memory
 5036: @subsection Address arithmetic
 5037: @cindex address arithmetic words
 5038: 
 5039: Address arithmetic is the foundation on which you can build data
 5040: structures like arrays, records (@pxref{Structures}) and objects
 5041: (@pxref{Object-oriented Forth}).
 5042: 
 5043: @cindex address unit
 5044: @cindex au (address unit)
 5045: ANS Forth does not specify the sizes of the data types. Instead, it
 5046: offers a number of words for computing sizes and doing address
 5047: arithmetic. Address arithmetic is performed in terms of address units
 5048: (aus); on most systems the address unit is one byte. Note that a
 5049: character may have more than one au, so @code{chars} is no noop (on
 5050: platforms where it is a noop, it compiles to nothing).
 5051: 
 5052: The basic address arithmetic words are @code{+} and @code{-}.  E.g., if
 5053: you have the address of a cell, perform @code{1 cells +}, and you will
 5054: have the address of the next cell.
 5055: 
 5056: @cindex contiguous regions and address arithmetic
 5057: In ANS Forth you can perform address arithmetic only within a contiguous
 5058: region, i.e., if you have an address into one region, you can only add
 5059: and subtract such that the result is still within the region; you can
 5060: only subtract or compare addresses from within the same contiguous
 5061: region.  Reasons: several contiguous regions can be arranged in memory
 5062: in any way; on segmented systems addresses may have unusual
 5063: representations, such that address arithmetic only works within a
 5064: region.  Gforth provides a few more guarantees (linear address space,
 5065: dictionary grows upwards), but in general I have found it easy to stay
 5066: within contiguous regions (exception: computing and comparing to the
 5067: address just beyond the end of an array).
 5068: 
 5069: @cindex alignment of addresses for types
 5070: ANS Forth also defines words for aligning addresses for specific
 5071: types. Many computers require that accesses to specific data types
 5072: must only occur at specific addresses; e.g., that cells may only be
 5073: accessed at addresses divisible by 4. Even if a machine allows unaligned
 5074: accesses, it can usually perform aligned accesses faster. 
 5075: 
 5076: For the performance-conscious: alignment operations are usually only
 5077: necessary during the definition of a data structure, not during the
 5078: (more frequent) accesses to it.
 5079: 
 5080: ANS Forth defines no words for character-aligning addresses. This is not
 5081: an oversight, but reflects the fact that addresses that are not
 5082: char-aligned have no use in the standard and therefore will not be
 5083: created.
 5084: 
 5085: @cindex @code{CREATE} and alignment
 5086: ANS Forth guarantees that addresses returned by @code{CREATE}d words
 5087: are cell-aligned; in addition, Gforth guarantees that these addresses
 5088: are aligned for all purposes.
 5089: 
 5090: Note that the ANS Forth word @code{char} has nothing to do with address
 5091: arithmetic.
 5092: 
 5093: 
 5094: doc-chars
 5095: doc-char+
 5096: doc-cells
 5097: doc-cell+
 5098: doc-cell
 5099: doc-aligned
 5100: doc-floats
 5101: doc-float+
 5102: doc-float
 5103: doc-faligned
 5104: doc-sfloats
 5105: doc-sfloat+
 5106: doc-sfaligned
 5107: doc-dfloats
 5108: doc-dfloat+
 5109: doc-dfaligned
 5110: doc-maxaligned
 5111: doc-cfaligned
 5112: doc-address-unit-bits
 5113: doc-/w
 5114: doc-/l
 5115: 
 5116: @node Memory Blocks,  , Address arithmetic, Memory
 5117: @subsection Memory Blocks
 5118: @cindex memory block words
 5119: @cindex character strings - moving and copying
 5120: 
 5121: Memory blocks often represent character strings; For ways of storing
 5122: character strings in memory see @ref{String Formats}.  For other
 5123: string-processing words see @ref{Displaying characters and strings}.
 5124: 
 5125: A few of these words work on address unit blocks.  In that case, you
 5126: usually have to insert @code{CHARS} before the word when working on
 5127: character strings.  Most words work on character blocks, and expect a
 5128: char-aligned address.
 5129: 
 5130: When copying characters between overlapping memory regions, use
 5131: @code{chars move} or choose carefully between @code{cmove} and
 5132: @code{cmove>}.
 5133: 
 5134: doc-move
 5135: doc-erase
 5136: doc-cmove
 5137: doc-cmove>
 5138: doc-fill
 5139: doc-blank
 5140: doc-compare
 5141: doc-str=
 5142: doc-str<
 5143: doc-string-prefix?
 5144: doc-search
 5145: doc--trailing
 5146: doc-/string
 5147: doc-bounds
 5148: doc-pad
 5149: 
 5150: @comment TODO examples
 5151: 
 5152: 
 5153: @node Control Structures, Defining Words, Memory, Words
 5154: @section Control Structures
 5155: @cindex control structures
 5156: 
 5157: Control structures in Forth cannot be used interpretively, only in a
 5158: colon definition@footnote{To be precise, they have no interpretation
 5159: semantics (@pxref{Interpretation and Compilation Semantics}).}. We do
 5160: not like this limitation, but have not seen a satisfying way around it
 5161: yet, although many schemes have been proposed.
 5162: 
 5163: @menu
 5164: * Selection::                   IF ... ELSE ... ENDIF
 5165: * Simple Loops::                BEGIN ...
 5166: * Counted Loops::               DO
 5167: * Arbitrary control structures::  
 5168: * Calls and returns::           
 5169: * Exception Handling::          
 5170: @end menu
 5171: 
 5172: @node Selection, Simple Loops, Control Structures, Control Structures
 5173: @subsection Selection
 5174: @cindex selection control structures
 5175: @cindex control structures for selection
 5176: 
 5177: @cindex @code{IF} control structure
 5178: @example
 5179: @i{flag}
 5180: IF
 5181:   @i{code}
 5182: ENDIF
 5183: @end example
 5184: @noindent
 5185: 
 5186: If @i{flag} is non-zero (as far as @code{IF} etc. are concerned, a cell
 5187: with any bit set represents truth) @i{code} is executed.
 5188: 
 5189: @example
 5190: @i{flag}
 5191: IF
 5192:   @i{code1}
 5193: ELSE
 5194:   @i{code2}
 5195: ENDIF
 5196: @end example
 5197: 
 5198: If @var{flag} is true, @i{code1} is executed, otherwise @i{code2} is
 5199: executed.
 5200: 
 5201: You can use @code{THEN} instead of @code{ENDIF}. Indeed, @code{THEN} is
 5202: standard, and @code{ENDIF} is not, although it is quite popular. We
 5203: recommend using @code{ENDIF}, because it is less confusing for people
 5204: who also know other languages (and is not prone to reinforcing negative
 5205: prejudices against Forth in these people). Adding @code{ENDIF} to a
 5206: system that only supplies @code{THEN} is simple:
 5207: @example
 5208: : ENDIF   POSTPONE then ; immediate
 5209: @end example
 5210: 
 5211: [According to @cite{Webster's New Encyclopedic Dictionary}, @dfn{then
 5212: (adv.)}  has the following meanings:
 5213: @quotation
 5214: ... 2b: following next after in order ... 3d: as a necessary consequence
 5215: (if you were there, then you saw them).
 5216: @end quotation
 5217: Forth's @code{THEN} has the meaning 2b, whereas @code{THEN} in Pascal
 5218: and many other programming languages has the meaning 3d.]
 5219: 
 5220: Gforth also provides the words @code{?DUP-IF} and @code{?DUP-0=-IF}, so
 5221: you can avoid using @code{?dup}. Using these alternatives is also more
 5222: efficient than using @code{?dup}. Definitions in ANS Forth
 5223: for @code{ENDIF}, @code{?DUP-IF} and @code{?DUP-0=-IF} are provided in
 5224: @file{compat/control.fs}.
 5225: 
 5226: @cindex @code{CASE} control structure
 5227: @example
 5228: @i{n}
 5229: CASE
 5230:   @i{n1} OF @i{code1} ENDOF
 5231:   @i{n2} OF @i{code2} ENDOF
 5232:   @dots{}
 5233:   ( n ) @i{default-code} ( n )
 5234: ENDCASE ( )
 5235: @end example
 5236: 
 5237: Executes the first @i{codei}, where the @i{ni} is equal to @i{n}.  If
 5238: no @i{ni} matches, the optional @i{default-code} is executed. The
 5239: optional default case can be added by simply writing the code after
 5240: the last @code{ENDOF}. It may use @i{n}, which is on top of the stack,
 5241: but must not consume it.  The value @i{n} is consumed by this
 5242: construction (either by a OF that matches, or by the ENDCASE, if no OF
 5243: matches).
 5244: 
 5245: @progstyle
 5246: To keep the code understandable, you should ensure that you change the
 5247: stack in the same way (wrt. number and types of stack items consumed
 5248: and pushed) on all paths through a selection construct.
 5249: 
 5250: @node Simple Loops, Counted Loops, Selection, Control Structures
 5251: @subsection Simple Loops
 5252: @cindex simple loops
 5253: @cindex loops without count 
 5254: 
 5255: @cindex @code{WHILE} loop
 5256: @example
 5257: BEGIN
 5258:   @i{code1}
 5259:   @i{flag}
 5260: WHILE
 5261:   @i{code2}
 5262: REPEAT
 5263: @end example
 5264: 
 5265: @i{code1} is executed and @i{flag} is computed. If it is true,
 5266: @i{code2} is executed and the loop is restarted; If @i{flag} is
 5267: false, execution continues after the @code{REPEAT}.
 5268: 
 5269: @cindex @code{UNTIL} loop
 5270: @example
 5271: BEGIN
 5272:   @i{code}
 5273:   @i{flag}
 5274: UNTIL
 5275: @end example
 5276: 
 5277: @i{code} is executed. The loop is restarted if @code{flag} is false.
 5278: 
 5279: @progstyle
 5280: To keep the code understandable, a complete iteration of the loop should
 5281: not change the number and types of the items on the stacks.
 5282: 
 5283: @cindex endless loop
 5284: @cindex loops, endless
 5285: @example
 5286: BEGIN
 5287:   @i{code}
 5288: AGAIN
 5289: @end example
 5290: 
 5291: This is an endless loop.
 5292: 
 5293: @node Counted Loops, Arbitrary control structures, Simple Loops, Control Structures
 5294: @subsection Counted Loops
 5295: @cindex counted loops
 5296: @cindex loops, counted
 5297: @cindex @code{DO} loops
 5298: 
 5299: The basic counted loop is:
 5300: @example
 5301: @i{limit} @i{start}
 5302: ?DO
 5303:   @i{body}
 5304: LOOP
 5305: @end example
 5306: 
 5307: This performs one iteration for every integer, starting from @i{start}
 5308: and up to, but excluding @i{limit}. The counter, or @i{index}, can be
 5309: accessed with @code{i}. For example, the loop:
 5310: @example
 5311: 10 0 ?DO
 5312:   i .
 5313: LOOP
 5314: @end example
 5315: @noindent
 5316: prints @code{0 1 2 3 4 5 6 7 8 9}
 5317: 
 5318: The index of the innermost loop can be accessed with @code{i}, the index
 5319: of the next loop with @code{j}, and the index of the third loop with
 5320: @code{k}.
 5321: 
 5322: 
 5323: doc-i
 5324: doc-j
 5325: doc-k
 5326: 
 5327: 
 5328: The loop control data are kept on the return stack, so there are some
 5329: restrictions on mixing return stack accesses and counted loop words. In
 5330: particuler, if you put values on the return stack outside the loop, you
 5331: cannot read them inside the loop@footnote{well, not in a way that is
 5332: portable.}. If you put values on the return stack within a loop, you
 5333: have to remove them before the end of the loop and before accessing the
 5334: index of the loop.
 5335: 
 5336: There are several variations on the counted loop:
 5337: 
 5338: @itemize @bullet
 5339: @item
 5340: @code{LEAVE} leaves the innermost counted loop immediately; execution
 5341: continues after the associated @code{LOOP} or @code{NEXT}. For example:
 5342: 
 5343: @example
 5344: 10 0 ?DO  i DUP . 3 = IF LEAVE THEN LOOP
 5345: @end example
 5346: prints @code{0 1 2 3}
 5347: 
 5348: 
 5349: @item
 5350: @code{UNLOOP} prepares for an abnormal loop exit, e.g., via
 5351: @code{EXIT}. @code{UNLOOP} removes the loop control parameters from the
 5352: return stack so @code{EXIT} can get to its return address. For example:
 5353: 
 5354: @example
 5355: : demo 10 0 ?DO i DUP . 3 = IF UNLOOP EXIT THEN LOOP ." Done" ;
 5356: @end example
 5357: prints @code{0 1 2 3}
 5358: 
 5359: 
 5360: @item
 5361: If @i{start} is greater than @i{limit}, a @code{?DO} loop is entered
 5362: (and @code{LOOP} iterates until they become equal by wrap-around
 5363: arithmetic). This behaviour is usually not what you want. Therefore,
 5364: Gforth offers @code{+DO} and @code{U+DO} (as replacements for
 5365: @code{?DO}), which do not enter the loop if @i{start} is greater than
 5366: @i{limit}; @code{+DO} is for signed loop parameters, @code{U+DO} for
 5367: unsigned loop parameters.
 5368: 
 5369: @item
 5370: @code{?DO} can be replaced by @code{DO}. @code{DO} always enters
 5371: the loop, independent of the loop parameters. Do not use @code{DO}, even
 5372: if you know that the loop is entered in any case. Such knowledge tends
 5373: to become invalid during maintenance of a program, and then the
 5374: @code{DO} will make trouble.
 5375: 
 5376: @item
 5377: @code{LOOP} can be replaced with @code{@i{n} +LOOP}; this updates the
 5378: index by @i{n} instead of by 1. The loop is terminated when the border
 5379: between @i{limit-1} and @i{limit} is crossed. E.g.:
 5380: 
 5381: @example
 5382: 4 0 +DO  i .  2 +LOOP
 5383: @end example
 5384: @noindent
 5385: prints @code{0 2}
 5386: 
 5387: @example
 5388: 4 1 +DO  i .  2 +LOOP
 5389: @end example
 5390: @noindent
 5391: prints @code{1 3}
 5392: 
 5393: @item
 5394: @cindex negative increment for counted loops
 5395: @cindex counted loops with negative increment
 5396: The behaviour of @code{@i{n} +LOOP} is peculiar when @i{n} is negative:
 5397: 
 5398: @example
 5399: -1 0 ?DO  i .  -1 +LOOP
 5400: @end example
 5401: @noindent
 5402: prints @code{0 -1}
 5403: 
 5404: @example
 5405: 0 0 ?DO  i .  -1 +LOOP
 5406: @end example
 5407: prints nothing.
 5408: 
 5409: Therefore we recommend avoiding @code{@i{n} +LOOP} with negative
 5410: @i{n}. One alternative is @code{@i{u} -LOOP}, which reduces the
 5411: index by @i{u} each iteration. The loop is terminated when the border
 5412: between @i{limit+1} and @i{limit} is crossed. Gforth also provides
 5413: @code{-DO} and @code{U-DO} for down-counting loops. E.g.:
 5414: 
 5415: @example
 5416: -2 0 -DO  i .  1 -LOOP
 5417: @end example
 5418: @noindent
 5419: prints @code{0 -1}
 5420: 
 5421: @example
 5422: -1 0 -DO  i .  1 -LOOP
 5423: @end example
 5424: @noindent
 5425: prints @code{0}
 5426: 
 5427: @example
 5428: 0 0 -DO  i .  1 -LOOP
 5429: @end example
 5430: @noindent
 5431: prints nothing.
 5432: 
 5433: @end itemize
 5434: 
 5435: Unfortunately, @code{+DO}, @code{U+DO}, @code{-DO}, @code{U-DO} and
 5436: @code{-LOOP} are not defined in ANS Forth. However, an implementation
 5437: for these words that uses only standard words is provided in
 5438: @file{compat/loops.fs}.
 5439: 
 5440: 
 5441: @cindex @code{FOR} loops
 5442: Another counted loop is:
 5443: @example
 5444: @i{n}
 5445: FOR
 5446:   @i{body}
 5447: NEXT
 5448: @end example
 5449: This is the preferred loop of native code compiler writers who are too
 5450: lazy to optimize @code{?DO} loops properly. This loop structure is not
 5451: defined in ANS Forth. In Gforth, this loop iterates @i{n+1} times;
 5452: @code{i} produces values starting with @i{n} and ending with 0. Other
 5453: Forth systems may behave differently, even if they support @code{FOR}
 5454: loops. To avoid problems, don't use @code{FOR} loops.
 5455: 
 5456: @node Arbitrary control structures, Calls and returns, Counted Loops, Control Structures
 5457: @subsection Arbitrary control structures
 5458: @cindex control structures, user-defined
 5459: 
 5460: @cindex control-flow stack
 5461: ANS Forth permits and supports using control structures in a non-nested
 5462: way. Information about incomplete control structures is stored on the
 5463: control-flow stack. This stack may be implemented on the Forth data
 5464: stack, and this is what we have done in Gforth.
 5465: 
 5466: @cindex @code{orig}, control-flow stack item
 5467: @cindex @code{dest}, control-flow stack item
 5468: An @i{orig} entry represents an unresolved forward branch, a @i{dest}
 5469: entry represents a backward branch target. A few words are the basis for
 5470: building any control structure possible (except control structures that
 5471: need storage, like calls, coroutines, and backtracking).
 5472: 
 5473: 
 5474: doc-if
 5475: doc-ahead
 5476: doc-then
 5477: doc-begin
 5478: doc-until
 5479: doc-again
 5480: doc-cs-pick
 5481: doc-cs-roll
 5482: 
 5483: 
 5484: The Standard words @code{CS-PICK} and @code{CS-ROLL} allow you to
 5485: manipulate the control-flow stack in a portable way. Without them, you
 5486: would need to know how many stack items are occupied by a control-flow
 5487: entry (many systems use one cell. In Gforth they currently take three,
 5488: but this may change in the future).
 5489: 
 5490: Some standard control structure words are built from these words:
 5491: 
 5492: 
 5493: doc-else
 5494: doc-while
 5495: doc-repeat
 5496: 
 5497: 
 5498: @noindent
 5499: Gforth adds some more control-structure words:
 5500: 
 5501: 
 5502: doc-endif
 5503: doc-?dup-if
 5504: doc-?dup-0=-if
 5505: 
 5506: 
 5507: @noindent
 5508: Counted loop words constitute a separate group of words:
 5509: 
 5510: 
 5511: doc-?do
 5512: doc-+do
 5513: doc-u+do
 5514: doc--do
 5515: doc-u-do
 5516: doc-do
 5517: doc-for
 5518: doc-loop
 5519: doc-+loop
 5520: doc--loop
 5521: doc-next
 5522: doc-leave
 5523: doc-?leave
 5524: doc-unloop
 5525: doc-done
 5526: 
 5527: 
 5528: The standard does not allow using @code{CS-PICK} and @code{CS-ROLL} on
 5529: @i{do-sys}. Gforth allows it, but it's your job to ensure that for
 5530: every @code{?DO} etc. there is exactly one @code{UNLOOP} on any path
 5531: through the definition (@code{LOOP} etc. compile an @code{UNLOOP} on the
 5532: fall-through path). Also, you have to ensure that all @code{LEAVE}s are
 5533: resolved (by using one of the loop-ending words or @code{DONE}).
 5534: 
 5535: @noindent
 5536: Another group of control structure words are:
 5537: 
 5538: 
 5539: doc-case
 5540: doc-endcase
 5541: doc-of
 5542: doc-endof
 5543: 
 5544: 
 5545: @i{case-sys} and @i{of-sys} cannot be processed using @code{CS-PICK} and
 5546: @code{CS-ROLL}.
 5547: 
 5548: @subsubsection Programming Style
 5549: @cindex control structures programming style
 5550: @cindex programming style, arbitrary control structures
 5551: 
 5552: In order to ensure readability we recommend that you do not create
 5553: arbitrary control structures directly, but define new control structure
 5554: words for the control structure you want and use these words in your
 5555: program. For example, instead of writing:
 5556: 
 5557: @example
 5558: BEGIN
 5559:   ...
 5560: IF [ 1 CS-ROLL ]
 5561:   ...
 5562: AGAIN THEN
 5563: @end example
 5564: 
 5565: @noindent
 5566: we recommend defining control structure words, e.g.,
 5567: 
 5568: @example
 5569: : WHILE ( DEST -- ORIG DEST )
 5570:  POSTPONE IF
 5571:  1 CS-ROLL ; immediate
 5572: 
 5573: : REPEAT ( orig dest -- )
 5574:  POSTPONE AGAIN
 5575:  POSTPONE THEN ; immediate
 5576: @end example
 5577: 
 5578: @noindent
 5579: and then using these to create the control structure:
 5580: 
 5581: @example
 5582: BEGIN
 5583:   ...
 5584: WHILE
 5585:   ...
 5586: REPEAT
 5587: @end example
 5588: 
 5589: That's much easier to read, isn't it? Of course, @code{REPEAT} and
 5590: @code{WHILE} are predefined, so in this example it would not be
 5591: necessary to define them.
 5592: 
 5593: @node Calls and returns, Exception Handling, Arbitrary control structures, Control Structures
 5594: @subsection Calls and returns
 5595: @cindex calling a definition
 5596: @cindex returning from a definition
 5597: 
 5598: @cindex recursive definitions
 5599: A definition can be called simply be writing the name of the definition
 5600: to be called. Normally a definition is invisible during its own
 5601: definition. If you want to write a directly recursive definition, you
 5602: can use @code{recursive} to make the current definition visible, or
 5603: @code{recurse} to call the current definition directly.
 5604: 
 5605: 
 5606: doc-recursive
 5607: doc-recurse
 5608: 
 5609: 
 5610: @comment TODO add example of the two recursion methods
 5611: @quotation
 5612: @progstyle
 5613: I prefer using @code{recursive} to @code{recurse}, because calling the
 5614: definition by name is more descriptive (if the name is well-chosen) than
 5615: the somewhat cryptic @code{recurse}.  E.g., in a quicksort
 5616: implementation, it is much better to read (and think) ``now sort the
 5617: partitions'' than to read ``now do a recursive call''.
 5618: @end quotation
 5619: 
 5620: For mutual recursion, use @code{Defer}red words, like this:
 5621: 
 5622: @example
 5623: Defer foo
 5624: 
 5625: : bar ( ... -- ... )
 5626:  ... foo ... ;
 5627: 
 5628: :noname ( ... -- ... )
 5629:  ... bar ... ;
 5630: IS foo
 5631: @end example
 5632: 
 5633: Deferred words are discussed in more detail in @ref{Deferred Words}.
 5634: 
 5635: The current definition returns control to the calling definition when
 5636: the end of the definition is reached or @code{EXIT} is encountered.
 5637: 
 5638: doc-exit
 5639: doc-;s
 5640: 
 5641: 
 5642: @node Exception Handling,  , Calls and returns, Control Structures
 5643: @subsection Exception Handling
 5644: @cindex exceptions
 5645: 
 5646: @c quit is a very bad idea for error handling, 
 5647: @c because it does not translate into a THROW
 5648: @c it also does not belong into this chapter
 5649: 
 5650: If a word detects an error condition that it cannot handle, it can
 5651: @code{throw} an exception.  In the simplest case, this will terminate
 5652: your program, and report an appropriate error.
 5653: 
 5654: doc-throw
 5655: 
 5656: @code{Throw} consumes a cell-sized error number on the stack. There are
 5657: some predefined error numbers in ANS Forth (see @file{errors.fs}).  In
 5658: Gforth (and most other systems) you can use the iors produced by various
 5659: words as error numbers (e.g., a typical use of @code{allocate} is
 5660: @code{allocate throw}).  Gforth also provides the word @code{exception}
 5661: to define your own error numbers (with decent error reporting); an ANS
 5662: Forth version of this word (but without the error messages) is available
 5663: in @code{compat/except.fs}.  And finally, you can use your own error
 5664: numbers (anything outside the range -4095..0), but won't get nice error
 5665: messages, only numbers.  For example, try:
 5666: 
 5667: @example
 5668: -10 throw                    \ ANS defined
 5669: -267 throw                   \ system defined
 5670: s" my error" exception throw \ user defined
 5671: 7 throw                      \ arbitrary number
 5672: @end example
 5673: 
 5674: doc---exception-exception
 5675: 
 5676: A common idiom to @code{THROW} a specific error if a flag is true is
 5677: this:
 5678: 
 5679: @example
 5680: @code{( flag ) 0<> @i{errno} and throw}
 5681: @end example
 5682: 
 5683: Your program can provide exception handlers to catch exceptions.  An
 5684: exception handler can be used to correct the problem, or to clean up
 5685: some data structures and just throw the exception to the next exception
 5686: handler.  Note that @code{throw} jumps to the dynamically innermost
 5687: exception handler.  The system's exception handler is outermost, and just
 5688: prints an error and restarts command-line interpretation (or, in batch
 5689: mode (i.e., while processing the shell command line), leaves Gforth).
 5690: 
 5691: The ANS Forth way to catch exceptions is @code{catch}:
 5692: 
 5693: doc-catch
 5694: doc-nothrow
 5695: 
 5696: The most common use of exception handlers is to clean up the state when
 5697: an error happens.  E.g.,
 5698: 
 5699: @example
 5700: base @ >r hex \ actually the hex should be inside foo, or we h
 5701: ['] foo catch ( nerror|0 )
 5702: r> base !
 5703: ( nerror|0 ) throw \ pass it on
 5704: @end example
 5705: 
 5706: A use of @code{catch} for handling the error @code{myerror} might look
 5707: like this:
 5708: 
 5709: @example
 5710: ['] foo catch
 5711: CASE
 5712:   myerror OF ... ( do something about it ) nothrow ENDOF
 5713:   dup throw \ default: pass other errors on, do nothing on non-errors
 5714: ENDCASE
 5715: @end example
 5716: 
 5717: Having to wrap the code into a separate word is often cumbersome,
 5718: therefore Gforth provides an alternative syntax:
 5719: 
 5720: @example
 5721: TRY
 5722:   @i{code1}
 5723:   IFERROR
 5724:     @i{code2}
 5725:   THEN
 5726:   @i{code3}
 5727: ENDTRY
 5728: @end example
 5729: 
 5730: This performs @i{code1}.  If @i{code1} completes normally, execution
 5731: continues with @i{code3}.  If @i{code1} or there is an exception
 5732: before @code{endtry}, the stacks are reset to the state during
 5733: @code{try}, the throw value is pushed on the data stack, and execution
 5734: constinues at @i{code2}, and finally falls through the @i{code3}.
 5735: 
 5736: doc-try
 5737: doc-endtry
 5738: doc-iferror
 5739: 
 5740: If you don't need @i{code2}, you can write @code{restore} instead of
 5741: @code{iferror then}:
 5742: 
 5743: @example
 5744: TRY
 5745:   @i{code1}
 5746: RESTORE
 5747:   @i{code3}
 5748: ENDTRY
 5749: @end example
 5750: 
 5751: @cindex unwind-protect
 5752: The cleanup example from above in this syntax:
 5753: 
 5754: @example
 5755: base @@ @{ oldbase @}
 5756: TRY
 5757:   hex foo \ now the hex is placed correctly
 5758:   0       \ value for throw
 5759: RESTORE
 5760:   oldbase base !
 5761: ENDTRY
 5762: throw
 5763: @end example
 5764: 
 5765: An additional advantage of this variant is that an exception between
 5766: @code{restore} and @code{endtry} (e.g., from the user pressing
 5767: @kbd{Ctrl-C}) restarts the execution of the code after @code{restore},
 5768: so the base will be restored under all circumstances.
 5769: 
 5770: However, you have to ensure that this code does not cause an exception
 5771: itself, otherwise the @code{iferror}/@code{restore} code will loop.
 5772: Moreover, you should also make sure that the stack contents needed by
 5773: the @code{iferror}/@code{restore} code exist everywhere between
 5774: @code{try} and @code{endtry}; in our example this is achived by
 5775: putting the data in a local before the @code{try} (you cannot use the
 5776: return stack because the exception frame (@i{sys1}) is in the way
 5777: there).
 5778: 
 5779: This kind of usage corresponds to Lisp's @code{unwind-protect}.
 5780: 
 5781: @cindex @code{recover} (old Gforth versions)
 5782: If you do not want this exception-restarting behaviour, you achieve
 5783: this as follows:
 5784: 
 5785: @example
 5786: TRY
 5787:   @i{code1}
 5788: ENDTRY-IFERROR
 5789:   @i{code2}
 5790: THEN
 5791: @end example
 5792: 
 5793: If there is an exception in @i{code1}, then @i{code2} is executed,
 5794: otherwise execution continues behind the @code{then} (or in a possible
 5795: @code{else} branch).  This corresponds to the construct
 5796: 
 5797: @example
 5798: TRY
 5799:   @i{code1}
 5800: RECOVER
 5801:   @i{code2}
 5802: ENDTRY
 5803: @end example
 5804: 
 5805: in Gforth before version 0.7.  So you can directly replace
 5806: @code{recover}-using code; however, we recommend that you check if it
 5807: would not be better to use one of the other @code{try} variants while
 5808: you are at it.
 5809: 
 5810: To ease the transition, Gforth provides two compatibility files:
 5811: @file{endtry-iferror.fs} provides the @code{try ... endtry-iferror
 5812: ... then} syntax (but not @code{iferror} or @code{restore}) for old
 5813: systems; @file{recover-endtry.fs} provides the @code{try ... recover
 5814: ... endtry} syntax on new systems, so you can use that file as a
 5815: stopgap to run old programs.  Both files work on any system (they just
 5816: do nothing if the system already has the syntax it implements), so you
 5817: can unconditionally @code{require} one of these files, even if you use
 5818: a mix old and new systems.
 5819: 
 5820: doc-restore
 5821: doc-endtry-iferror
 5822: 
 5823: Here's the error handling example:
 5824: 
 5825: @example
 5826: TRY
 5827:   foo
 5828: ENDTRY-IFERROR
 5829:   CASE
 5830:     myerror OF ... ( do something about it ) nothrow ENDOF
 5831:     throw \ pass other errors on
 5832:   ENDCASE
 5833: THEN
 5834: @end example
 5835: 
 5836: @progstyle
 5837: As usual, you should ensure that the stack depth is statically known at
 5838: the end: either after the @code{throw} for passing on errors, or after
 5839: the @code{ENDTRY} (or, if you use @code{catch}, after the end of the
 5840: selection construct for handling the error).
 5841: 
 5842: There are two alternatives to @code{throw}: @code{Abort"} is conditional
 5843: and you can provide an error message.  @code{Abort} just produces an
 5844: ``Aborted'' error.
 5845: 
 5846: The problem with these words is that exception handlers cannot
 5847: differentiate between different @code{abort"}s; they just look like
 5848: @code{-2 throw} to them (the error message cannot be accessed by
 5849: standard programs).  Similar @code{abort} looks like @code{-1 throw} to
 5850: exception handlers.
 5851: 
 5852: doc-abort"
 5853: doc-abort
 5854: 
 5855: 
 5856: 
 5857: @c -------------------------------------------------------------
 5858: @node Defining Words, Interpretation and Compilation Semantics, Control Structures, Words
 5859: @section Defining Words
 5860: @cindex defining words
 5861: 
 5862: Defining words are used to extend Forth by creating new entries in the dictionary.
 5863: 
 5864: @menu
 5865: * CREATE::                      
 5866: * Variables::                   Variables and user variables
 5867: * Constants::                   
 5868: * Values::                      Initialised variables
 5869: * Colon Definitions::           
 5870: * Anonymous Definitions::       Definitions without names
 5871: * Supplying names::             Passing definition names as strings
 5872: * User-defined Defining Words::  
 5873: * Deferred Words::              Allow forward references
 5874: * Aliases::                     
 5875: @end menu
 5876: 
 5877: @node CREATE, Variables, Defining Words, Defining Words
 5878: @subsection @code{CREATE}
 5879: @cindex simple defining words
 5880: @cindex defining words, simple
 5881: 
 5882: Defining words are used to create new entries in the dictionary. The
 5883: simplest defining word is @code{CREATE}. @code{CREATE} is used like
 5884: this:
 5885: 
 5886: @example
 5887: CREATE new-word1
 5888: @end example
 5889: 
 5890: @code{CREATE} is a parsing word, i.e., it takes an argument from the
 5891: input stream (@code{new-word1} in our example).  It generates a
 5892: dictionary entry for @code{new-word1}. When @code{new-word1} is
 5893: executed, all that it does is leave an address on the stack. The address
 5894: represents the value of the data space pointer (@code{HERE}) at the time
 5895: that @code{new-word1} was defined. Therefore, @code{CREATE} is a way of
 5896: associating a name with the address of a region of memory.
 5897: 
 5898: doc-create
 5899: 
 5900: Note that in ANS Forth guarantees only for @code{create} that its body
 5901: is in dictionary data space (i.e., where @code{here}, @code{allot}
 5902: etc. work, @pxref{Dictionary allocation}).  Also, in ANS Forth only
 5903: @code{create}d words can be modified with @code{does>}
 5904: (@pxref{User-defined Defining Words}).  And in ANS Forth @code{>body}
 5905: can only be applied to @code{create}d words.
 5906: 
 5907: By extending this example to reserve some memory in data space, we end
 5908: up with something like a @i{variable}. Here are two different ways to do
 5909: it:
 5910: 
 5911: @example
 5912: CREATE new-word2 1 cells allot  \ reserve 1 cell - initial value undefined
 5913: CREATE new-word3 4 ,            \ reserve 1 cell and initialise it (to 4)
 5914: @end example
 5915: 
 5916: The variable can be examined and modified using @code{@@} (``fetch'') and
 5917: @code{!} (``store'') like this:
 5918: 
 5919: @example
 5920: new-word2 @@ .      \ get address, fetch from it and display
 5921: 1234 new-word2 !   \ new value, get address, store to it
 5922: @end example
 5923: 
 5924: @cindex arrays
 5925: A similar mechanism can be used to create arrays. For example, an
 5926: 80-character text input buffer:
 5927: 
 5928: @example
 5929: CREATE text-buf 80 chars allot
 5930: 
 5931: text-buf 0 chars + c@@ \ the 1st character (offset 0)
 5932: text-buf 3 chars + c@@ \ the 4th character (offset 3)
 5933: @end example
 5934: 
 5935: You can build arbitrarily complex data structures by allocating
 5936: appropriate areas of memory. For further discussions of this, and to
 5937: learn about some Gforth tools that make it easier,
 5938: @xref{Structures}.
 5939: 
 5940: 
 5941: @node Variables, Constants, CREATE, Defining Words
 5942: @subsection Variables
 5943: @cindex variables
 5944: 
 5945: The previous section showed how a sequence of commands could be used to
 5946: generate a variable.  As a final refinement, the whole code sequence can
 5947: be wrapped up in a defining word (pre-empting the subject of the next
 5948: section), making it easier to create new variables:
 5949: 
 5950: @example
 5951: : myvariableX ( "name" -- a-addr ) CREATE 1 cells allot ;
 5952: : myvariable0 ( "name" -- a-addr ) CREATE 0 , ;
 5953: 
 5954: myvariableX foo \ variable foo starts off with an unknown value
 5955: myvariable0 joe \ whilst joe is initialised to 0
 5956: 
 5957: 45 3 * foo !   \ set foo to 135
 5958: 1234 joe !     \ set joe to 1234
 5959: 3 joe +!       \ increment joe by 3.. to 1237
 5960: @end example
 5961: 
 5962: Not surprisingly, there is no need to define @code{myvariable}, since
 5963: Forth already has a definition @code{Variable}. ANS Forth does not
 5964: guarantee that a @code{Variable} is initialised when it is created
 5965: (i.e., it may behave like @code{myvariableX}). In contrast, Gforth's
 5966: @code{Variable} initialises the variable to 0 (i.e., it behaves exactly
 5967: like @code{myvariable0}). Forth also provides @code{2Variable} and
 5968: @code{fvariable} for double and floating-point variables, respectively
 5969: -- they are initialised to 0. and 0e in Gforth. If you use a @code{Variable} to
 5970: store a boolean, you can use @code{on} and @code{off} to toggle its
 5971: state.
 5972: 
 5973: doc-variable
 5974: doc-2variable
 5975: doc-fvariable
 5976: 
 5977: @cindex user variables
 5978: @cindex user space
 5979: The defining word @code{User} behaves in the same way as @code{Variable}.
 5980: The difference is that it reserves space in @i{user (data) space} rather
 5981: than normal data space. In a Forth system that has a multi-tasker, each
 5982: task has its own set of user variables.
 5983: 
 5984: doc-user
 5985: @c doc-udp
 5986: @c doc-uallot
 5987: 
 5988: @comment TODO is that stuff about user variables strictly correct? Is it
 5989: @comment just terminal tasks that have user variables?
 5990: @comment should document tasker.fs (with some examples) elsewhere
 5991: @comment in this manual, then expand on user space and user variables.
 5992: 
 5993: @node Constants, Values, Variables, Defining Words
 5994: @subsection Constants
 5995: @cindex constants
 5996: 
 5997: @code{Constant} allows you to declare a fixed value and refer to it by
 5998: name. For example:
 5999: 
 6000: @example
 6001: 12 Constant INCHES-PER-FOOT
 6002: 3E+08 fconstant SPEED-O-LIGHT
 6003: @end example
 6004: 
 6005: A @code{Variable} can be both read and written, so its run-time
 6006: behaviour is to supply an address through which its current value can be
 6007: manipulated. In contrast, the value of a @code{Constant} cannot be
 6008: changed once it has been declared@footnote{Well, often it can be -- but
 6009: not in a Standard, portable way. It's safer to use a @code{Value} (read
 6010: on).} so it's not necessary to supply the address -- it is more
 6011: efficient to return the value of the constant directly. That's exactly
 6012: what happens; the run-time effect of a constant is to put its value on
 6013: the top of the stack (You can find one
 6014: way of implementing @code{Constant} in @ref{User-defined Defining Words}).
 6015: 
 6016: Forth also provides @code{2Constant} and @code{fconstant} for defining
 6017: double and floating-point constants, respectively.
 6018: 
 6019: doc-constant
 6020: doc-2constant
 6021: doc-fconstant
 6022: 
 6023: @c that's too deep, and it's not necessarily true for all ANS Forths. - anton
 6024: @c nac-> How could that not be true in an ANS Forth? You can't define a
 6025: @c constant, use it and then delete the definition of the constant..
 6026: 
 6027: @c anton->An ANS Forth system can compile a constant to a literal; On
 6028: @c decompilation you would see only the number, just as if it had been used
 6029: @c in the first place.  The word will stay, of course, but it will only be
 6030: @c used by the text interpreter (no run-time duties, except when it is 
 6031: @c POSTPONEd or somesuch).
 6032: 
 6033: @c nac:
 6034: @c I agree that it's rather deep, but IMO it is an important difference
 6035: @c relative to other programming languages.. often it's annoying: it
 6036: @c certainly changes my programming style relative to C.
 6037: 
 6038: @c anton: In what way?
 6039: 
 6040: Constants in Forth behave differently from their equivalents in other
 6041: programming languages. In other languages, a constant (such as an EQU in
 6042: assembler or a #define in C) only exists at compile-time; in the
 6043: executable program the constant has been translated into an absolute
 6044: number and, unless you are using a symbolic debugger, it's impossible to
 6045: know what abstract thing that number represents. In Forth a constant has
 6046: an entry in the header space and remains there after the code that uses
 6047: it has been defined. In fact, it must remain in the dictionary since it
 6048: has run-time duties to perform. For example:
 6049: 
 6050: @example
 6051: 12 Constant INCHES-PER-FOOT
 6052: : FEET-TO-INCHES ( n1 -- n2 ) INCHES-PER-FOOT * ;
 6053: @end example
 6054: 
 6055: @cindex in-lining of constants
 6056: When @code{FEET-TO-INCHES} is executed, it will in turn execute the xt
 6057: associated with the constant @code{INCHES-PER-FOOT}. If you use
 6058: @code{see} to decompile the definition of @code{FEET-TO-INCHES}, you can
 6059: see that it makes a call to @code{INCHES-PER-FOOT}. Some Forth compilers
 6060: attempt to optimise constants by in-lining them where they are used. You
 6061: can force Gforth to in-line a constant like this:
 6062: 
 6063: @example
 6064: : FEET-TO-INCHES ( n1 -- n2 ) [ INCHES-PER-FOOT ] LITERAL * ;
 6065: @end example
 6066: 
 6067: If you use @code{see} to decompile @i{this} version of
 6068: @code{FEET-TO-INCHES}, you can see that @code{INCHES-PER-FOOT} is no
 6069: longer present. To understand how this works, read
 6070: @ref{Interpret/Compile states}, and @ref{Literals}.
 6071: 
 6072: In-lining constants in this way might improve execution time
 6073: fractionally, and can ensure that a constant is now only referenced at
 6074: compile-time. However, the definition of the constant still remains in
 6075: the dictionary. Some Forth compilers provide a mechanism for controlling
 6076: a second dictionary for holding transient words such that this second
 6077: dictionary can be deleted later in order to recover memory
 6078: space. However, there is no standard way of doing this.
 6079: 
 6080: 
 6081: @node Values, Colon Definitions, Constants, Defining Words
 6082: @subsection Values
 6083: @cindex values
 6084: 
 6085: A @code{Value} behaves like a @code{Constant}, but it can be changed.
 6086: @code{TO} is a parsing word that changes a @code{Values}.  In Gforth
 6087: (not in ANS Forth) you can access (and change) a @code{value} also with
 6088: @code{>body}.
 6089: 
 6090: Here are some
 6091: examples:
 6092: 
 6093: @example
 6094: 12 Value APPLES     \ Define APPLES with an initial value of 12
 6095: 34 TO APPLES        \ Change the value of APPLES. TO is a parsing word
 6096: 1 ' APPLES >body +! \ Increment APPLES.  Non-standard usage.
 6097: APPLES              \ puts 35 on the top of the stack.
 6098: @end example
 6099: 
 6100: doc-value
 6101: doc-to
 6102: 
 6103: 
 6104: 
 6105: @node Colon Definitions, Anonymous Definitions, Values, Defining Words
 6106: @subsection Colon Definitions
 6107: @cindex colon definitions
 6108: 
 6109: @example
 6110: : name ( ... -- ... )
 6111:     word1 word2 word3 ;
 6112: @end example
 6113: 
 6114: @noindent
 6115: Creates a word called @code{name} that, upon execution, executes
 6116: @code{word1 word2 word3}. @code{name} is a @dfn{(colon) definition}.
 6117: 
 6118: The explanation above is somewhat superficial. For simple examples of
 6119: colon definitions see @ref{Your first definition}.  For an in-depth
 6120: discussion of some of the issues involved, @xref{Interpretation and
 6121: Compilation Semantics}.
 6122: 
 6123: doc-:
 6124: doc-;
 6125: 
 6126: 
 6127: @node Anonymous Definitions, Supplying names, Colon Definitions, Defining Words
 6128: @subsection Anonymous Definitions
 6129: @cindex colon definitions
 6130: @cindex defining words without name
 6131: 
 6132: Sometimes you want to define an @dfn{anonymous word}; a word without a
 6133: name. You can do this with:
 6134: 
 6135: doc-:noname
 6136: 
 6137: This leaves the execution token for the word on the stack after the
 6138: closing @code{;}. Here's an example in which a deferred word is
 6139: initialised with an @code{xt} from an anonymous colon definition:
 6140: 
 6141: @example
 6142: Defer deferred
 6143: :noname ( ... -- ... )
 6144:   ... ;
 6145: IS deferred
 6146: @end example
 6147: 
 6148: @noindent
 6149: Gforth provides an alternative way of doing this, using two separate
 6150: words:
 6151: 
 6152: doc-noname
 6153: @cindex execution token of last defined word
 6154: doc-latestxt
 6155: 
 6156: @noindent
 6157: The previous example can be rewritten using @code{noname} and
 6158: @code{latestxt}:
 6159: 
 6160: @example
 6161: Defer deferred
 6162: noname : ( ... -- ... )
 6163:   ... ;
 6164: latestxt IS deferred
 6165: @end example
 6166: 
 6167: @noindent
 6168: @code{noname} works with any defining word, not just @code{:}.
 6169: 
 6170: @code{latestxt} also works when the last word was not defined as
 6171: @code{noname}.  It does not work for combined words, though.  It also has
 6172: the useful property that is is valid as soon as the header for a
 6173: definition has been built. Thus:
 6174: 
 6175: @example
 6176: latestxt . : foo [ latestxt . ] ; ' foo .
 6177: @end example
 6178: 
 6179: @noindent
 6180: prints 3 numbers; the last two are the same.
 6181: 
 6182: @node Supplying names, User-defined Defining Words, Anonymous Definitions, Defining Words
 6183: @subsection Supplying the name of a defined word
 6184: @cindex names for defined words
 6185: @cindex defining words, name given in a string
 6186: 
 6187: By default, a defining word takes the name for the defined word from the
 6188: input stream. Sometimes you want to supply the name from a string. You
 6189: can do this with:
 6190: 
 6191: doc-nextname
 6192: 
 6193: For example:
 6194: 
 6195: @example
 6196: s" foo" nextname create
 6197: @end example
 6198: 
 6199: @noindent
 6200: is equivalent to:
 6201: 
 6202: @example
 6203: create foo
 6204: @end example
 6205: 
 6206: @noindent
 6207: @code{nextname} works with any defining word.
 6208: 
 6209: 
 6210: @node User-defined Defining Words, Deferred Words, Supplying names, Defining Words
 6211: @subsection User-defined Defining Words
 6212: @cindex user-defined defining words
 6213: @cindex defining words, user-defined
 6214: 
 6215: You can create a new defining word by wrapping defining-time code around
 6216: an existing defining word and putting the sequence in a colon
 6217: definition. 
 6218: 
 6219: @c anton: This example is very complex and leads in a quite different
 6220: @c direction from the CREATE-DOES> stuff that follows.  It should probably
 6221: @c be done elsewhere, or as a subsubsection of this subsection (or as a
 6222: @c subsection of Defining Words)
 6223: 
 6224: For example, suppose that you have a word @code{stats} that
 6225: gathers statistics about colon definitions given the @i{xt} of the
 6226: definition, and you want every colon definition in your application to
 6227: make a call to @code{stats}. You can define and use a new version of
 6228: @code{:} like this:
 6229: 
 6230: @example
 6231: : stats ( xt -- ) DUP ." (Gathering statistics for " . ." )"
 6232:   ... ;  \ other code
 6233: 
 6234: : my: : latestxt postpone literal ['] stats compile, ;
 6235: 
 6236: my: foo + - ;
 6237: @end example
 6238: 
 6239: When @code{foo} is defined using @code{my:} these steps occur:
 6240: 
 6241: @itemize @bullet
 6242: @item
 6243: @code{my:} is executed.
 6244: @item
 6245: The @code{:} within the definition (the one between @code{my:} and
 6246: @code{latestxt}) is executed, and does just what it always does; it parses
 6247: the input stream for a name, builds a dictionary header for the name
 6248: @code{foo} and switches @code{state} from interpret to compile.
 6249: @item
 6250: The word @code{latestxt} is executed. It puts the @i{xt} for the word that is
 6251: being defined -- @code{foo} -- onto the stack.
 6252: @item
 6253: The code that was produced by @code{postpone literal} is executed; this
 6254: causes the value on the stack to be compiled as a literal in the code
 6255: area of @code{foo}.
 6256: @item
 6257: The code @code{['] stats} compiles a literal into the definition of
 6258: @code{my:}. When @code{compile,} is executed, that literal -- the
 6259: execution token for @code{stats} -- is layed down in the code area of
 6260: @code{foo} , following the literal@footnote{Strictly speaking, the
 6261: mechanism that @code{compile,} uses to convert an @i{xt} into something
 6262: in the code area is implementation-dependent. A threaded implementation
 6263: might spit out the execution token directly whilst another
 6264: implementation might spit out a native code sequence.}.
 6265: @item
 6266: At this point, the execution of @code{my:} is complete, and control
 6267: returns to the text interpreter. The text interpreter is in compile
 6268: state, so subsequent text @code{+ -} is compiled into the definition of
 6269: @code{foo} and the @code{;} terminates the definition as always.
 6270: @end itemize
 6271: 
 6272: You can use @code{see} to decompile a word that was defined using
 6273: @code{my:} and see how it is different from a normal @code{:}
 6274: definition. For example:
 6275: 
 6276: @example
 6277: : bar + - ;  \ like foo but using : rather than my:
 6278: see bar
 6279: : bar
 6280:   + - ;
 6281: see foo
 6282: : foo
 6283:   107645672 stats + - ;
 6284: 
 6285: \ use ' foo . to show that 107645672 is the xt for foo
 6286: @end example
 6287: 
 6288: You can use techniques like this to make new defining words in terms of
 6289: @i{any} existing defining word.
 6290: 
 6291: 
 6292: @cindex defining defining words
 6293: @cindex @code{CREATE} ... @code{DOES>}
 6294: If you want the words defined with your defining words to behave
 6295: differently from words defined with standard defining words, you can
 6296: write your defining word like this:
 6297: 
 6298: @example
 6299: : def-word ( "name" -- )
 6300:     CREATE @i{code1}
 6301: DOES> ( ... -- ... )
 6302:     @i{code2} ;
 6303: 
 6304: def-word name
 6305: @end example
 6306: 
 6307: @cindex child words
 6308: This fragment defines a @dfn{defining word} @code{def-word} and then
 6309: executes it.  When @code{def-word} executes, it @code{CREATE}s a new
 6310: word, @code{name}, and executes the code @i{code1}. The code @i{code2}
 6311: is not executed at this time. The word @code{name} is sometimes called a
 6312: @dfn{child} of @code{def-word}.
 6313: 
 6314: When you execute @code{name}, the address of the body of @code{name} is
 6315: put on the data stack and @i{code2} is executed (the address of the body
 6316: of @code{name} is the address @code{HERE} returns immediately after the
 6317: @code{CREATE}, i.e., the address a @code{create}d word returns by
 6318: default).
 6319: 
 6320: @c anton:
 6321: @c www.dictionary.com says:
 6322: @c at·a·vism: 1.The reappearance of a characteristic in an organism after
 6323: @c several generations of absence, usually caused by the chance
 6324: @c recombination of genes.  2.An individual or a part that exhibits
 6325: @c atavism. Also called throwback.  3.The return of a trait or recurrence
 6326: @c of previous behavior after a period of absence.
 6327: @c
 6328: @c Doesn't seem to fit.
 6329: 
 6330: @c @cindex atavism in child words
 6331: You can use @code{def-word} to define a set of child words that behave
 6332: similarly; they all have a common run-time behaviour determined by
 6333: @i{code2}. Typically, the @i{code1} sequence builds a data area in the
 6334: body of the child word. The structure of the data is common to all
 6335: children of @code{def-word}, but the data values are specific -- and
 6336: private -- to each child word. When a child word is executed, the
 6337: address of its private data area is passed as a parameter on TOS to be
 6338: used and manipulated@footnote{It is legitimate both to read and write to
 6339: this data area.} by @i{code2}.
 6340: 
 6341: The two fragments of code that make up the defining words act (are
 6342: executed) at two completely separate times:
 6343: 
 6344: @itemize @bullet
 6345: @item
 6346: At @i{define time}, the defining word executes @i{code1} to generate a
 6347: child word
 6348: @item
 6349: At @i{child execution time}, when a child word is invoked, @i{code2}
 6350: is executed, using parameters (data) that are private and specific to
 6351: the child word.
 6352: @end itemize
 6353: 
 6354: Another way of understanding the behaviour of @code{def-word} and
 6355: @code{name} is to say that, if you make the following definitions:
 6356: @example
 6357: : def-word1 ( "name" -- )
 6358:     CREATE @i{code1} ;
 6359: 
 6360: : action1 ( ... -- ... )
 6361:     @i{code2} ;
 6362: 
 6363: def-word1 name1
 6364: @end example
 6365: 
 6366: @noindent
 6367: Then using @code{name1 action1} is equivalent to using @code{name}.
 6368: 
 6369: The classic example is that you can define @code{CONSTANT} in this way:
 6370: 
 6371: @example
 6372: : CONSTANT ( w "name" -- )
 6373:     CREATE ,
 6374: DOES> ( -- w )
 6375:     @@ ;
 6376: @end example
 6377: 
 6378: @comment There is a beautiful description of how this works and what
 6379: @comment it does in the Forthwrite 100th edition.. as well as an elegant
 6380: @comment commentary on the Counting Fruits problem.
 6381: 
 6382: When you create a constant with @code{5 CONSTANT five}, a set of
 6383: define-time actions take place; first a new word @code{five} is created,
 6384: then the value 5 is laid down in the body of @code{five} with
 6385: @code{,}. When @code{five} is executed, the address of the body is put on
 6386: the stack, and @code{@@} retrieves the value 5. The word @code{five} has
 6387: no code of its own; it simply contains a data field and a pointer to the
 6388: code that follows @code{DOES>} in its defining word. That makes words
 6389: created in this way very compact.
 6390: 
 6391: The final example in this section is intended to remind you that space
 6392: reserved in @code{CREATE}d words is @i{data} space and therefore can be
 6393: both read and written by a Standard program@footnote{Exercise: use this
 6394: example as a starting point for your own implementation of @code{Value}
 6395: and @code{TO} -- if you get stuck, investigate the behaviour of @code{'} and
 6396: @code{[']}.}:
 6397: 
 6398: @example
 6399: : foo ( "name" -- )
 6400:     CREATE -1 ,
 6401: DOES> ( -- )
 6402:     @@ . ;
 6403: 
 6404: foo first-word
 6405: foo second-word
 6406: 
 6407: 123 ' first-word >BODY !
 6408: @end example
 6409: 
 6410: If @code{first-word} had been a @code{CREATE}d word, we could simply
 6411: have executed it to get the address of its data field. However, since it
 6412: was defined to have @code{DOES>} actions, its execution semantics are to
 6413: perform those @code{DOES>} actions. To get the address of its data field
 6414: it's necessary to use @code{'} to get its xt, then @code{>BODY} to
 6415: translate the xt into the address of the data field.  When you execute
 6416: @code{first-word}, it will display @code{123}. When you execute
 6417: @code{second-word} it will display @code{-1}.
 6418: 
 6419: @cindex stack effect of @code{DOES>}-parts
 6420: @cindex @code{DOES>}-parts, stack effect
 6421: In the examples above the stack comment after the @code{DOES>} specifies
 6422: the stack effect of the defined words, not the stack effect of the
 6423: following code (the following code expects the address of the body on
 6424: the top of stack, which is not reflected in the stack comment). This is
 6425: the convention that I use and recommend (it clashes a bit with using
 6426: locals declarations for stack effect specification, though).
 6427: 
 6428: @menu
 6429: * CREATE..DOES> applications::  
 6430: * CREATE..DOES> details::       
 6431: * Advanced does> usage example::  
 6432: * Const-does>::                 
 6433: @end menu
 6434: 
 6435: @node CREATE..DOES> applications, CREATE..DOES> details, User-defined Defining Words, User-defined Defining Words
 6436: @subsubsection Applications of @code{CREATE..DOES>}
 6437: @cindex @code{CREATE} ... @code{DOES>}, applications
 6438: 
 6439: You may wonder how to use this feature. Here are some usage patterns:
 6440: 
 6441: @cindex factoring similar colon definitions
 6442: When you see a sequence of code occurring several times, and you can
 6443: identify a meaning, you will factor it out as a colon definition. When
 6444: you see similar colon definitions, you can factor them using
 6445: @code{CREATE..DOES>}. E.g., an assembler usually defines several words
 6446: that look very similar:
 6447: @example
 6448: : ori, ( reg-target reg-source n -- )
 6449:     0 asm-reg-reg-imm ;
 6450: : andi, ( reg-target reg-source n -- )
 6451:     1 asm-reg-reg-imm ;
 6452: @end example
 6453: 
 6454: @noindent
 6455: This could be factored with:
 6456: @example
 6457: : reg-reg-imm ( op-code -- )
 6458:     CREATE ,
 6459: DOES> ( reg-target reg-source n -- )
 6460:     @@ asm-reg-reg-imm ;
 6461: 
 6462: 0 reg-reg-imm ori,
 6463: 1 reg-reg-imm andi,
 6464: @end example
 6465: 
 6466: @cindex currying
 6467: Another view of @code{CREATE..DOES>} is to consider it as a crude way to
 6468: supply a part of the parameters for a word (known as @dfn{currying} in
 6469: the functional language community). E.g., @code{+} needs two
 6470: parameters. Creating versions of @code{+} with one parameter fixed can
 6471: be done like this:
 6472: 
 6473: @example
 6474: : curry+ ( n1 "name" -- )
 6475:     CREATE ,
 6476: DOES> ( n2 -- n1+n2 )
 6477:     @@ + ;
 6478: 
 6479:  3 curry+ 3+
 6480: -2 curry+ 2-
 6481: @end example
 6482: 
 6483: 
 6484: @node CREATE..DOES> details, Advanced does> usage example, CREATE..DOES> applications, User-defined Defining Words
 6485: @subsubsection The gory details of @code{CREATE..DOES>}
 6486: @cindex @code{CREATE} ... @code{DOES>}, details
 6487: 
 6488: doc-does>
 6489: 
 6490: @cindex @code{DOES>} in a separate definition
 6491: This means that you need not use @code{CREATE} and @code{DOES>} in the
 6492: same definition; you can put the @code{DOES>}-part in a separate
 6493: definition. This allows us to, e.g., select among different @code{DOES>}-parts:
 6494: @example
 6495: : does1 
 6496: DOES> ( ... -- ... )
 6497:     ... ;
 6498: 
 6499: : does2
 6500: DOES> ( ... -- ... )
 6501:     ... ;
 6502: 
 6503: : def-word ( ... -- ... )
 6504:     create ...
 6505:     IF
 6506:        does1
 6507:     ELSE
 6508:        does2
 6509:     ENDIF ;
 6510: @end example
 6511: 
 6512: In this example, the selection of whether to use @code{does1} or
 6513: @code{does2} is made at definition-time; at the time that the child word is
 6514: @code{CREATE}d.
 6515: 
 6516: @cindex @code{DOES>} in interpretation state
 6517: In a standard program you can apply a @code{DOES>}-part only if the last
 6518: word was defined with @code{CREATE}. In Gforth, the @code{DOES>}-part
 6519: will override the behaviour of the last word defined in any case. In a
 6520: standard program, you can use @code{DOES>} only in a colon
 6521: definition. In Gforth, you can also use it in interpretation state, in a
 6522: kind of one-shot mode; for example:
 6523: @example
 6524: CREATE name ( ... -- ... )
 6525:   @i{initialization}
 6526: DOES>
 6527:   @i{code} ;
 6528: @end example
 6529: 
 6530: @noindent
 6531: is equivalent to the standard:
 6532: @example
 6533: :noname
 6534: DOES>
 6535:     @i{code} ;
 6536: CREATE name EXECUTE ( ... -- ... )
 6537:     @i{initialization}
 6538: @end example
 6539: 
 6540: doc->body
 6541: 
 6542: @node Advanced does> usage example, Const-does>, CREATE..DOES> details, User-defined Defining Words
 6543: @subsubsection Advanced does> usage example
 6544: 
 6545: The MIPS disassembler (@file{arch/mips/disasm.fs}) contains many words
 6546: for disassembling instructions, that follow a very repetetive scheme:
 6547: 
 6548: @example
 6549: :noname @var{disasm-operands} s" @var{inst-name}" type ;
 6550: @var{entry-num} cells @var{table} + !
 6551: @end example
 6552: 
 6553: Of course, this inspires the idea to factor out the commonalities to
 6554: allow a definition like
 6555: 
 6556: @example
 6557: @var{disasm-operands} @var{entry-num} @var{table} define-inst @var{inst-name}
 6558: @end example
 6559: 
 6560: The parameters @var{disasm-operands} and @var{table} are usually
 6561: correlated.  Moreover, before I wrote the disassembler, there already
 6562: existed code that defines instructions like this:
 6563: 
 6564: @example
 6565: @var{entry-num} @var{inst-format} @var{inst-name}
 6566: @end example
 6567: 
 6568: This code comes from the assembler and resides in
 6569: @file{arch/mips/insts.fs}.
 6570: 
 6571: So I had to define the @var{inst-format} words that performed the scheme
 6572: above when executed.  At first I chose to use run-time code-generation:
 6573: 
 6574: @example
 6575: : @var{inst-format} ( entry-num "name" -- ; compiled code: addr w -- )
 6576:   :noname Postpone @var{disasm-operands}
 6577:   name Postpone sliteral Postpone type Postpone ;
 6578:   swap cells @var{table} + ! ;
 6579: @end example
 6580: 
 6581: Note that this supplies the other two parameters of the scheme above.
 6582: 
 6583: An alternative would have been to write this using
 6584: @code{create}/@code{does>}:
 6585: 
 6586: @example
 6587: : @var{inst-format} ( entry-num "name" -- )
 6588:   here name string, ( entry-num c-addr ) \ parse and save "name"
 6589:   noname create , ( entry-num )
 6590:   latestxt swap cells @var{table} + !
 6591: does> ( addr w -- )
 6592:   \ disassemble instruction w at addr
 6593:   @@ >r 
 6594:   @var{disasm-operands}
 6595:   r> count type ;
 6596: @end example
 6597: 
 6598: Somehow the first solution is simpler, mainly because it's simpler to
 6599: shift a string from definition-time to use-time with @code{sliteral}
 6600: than with @code{string,} and friends.
 6601: 
 6602: I wrote a lot of words following this scheme and soon thought about
 6603: factoring out the commonalities among them.  Note that this uses a
 6604: two-level defining word, i.e., a word that defines ordinary defining
 6605: words.
 6606: 
 6607: This time a solution involving @code{postpone} and friends seemed more
 6608: difficult (try it as an exercise), so I decided to use a
 6609: @code{create}/@code{does>} word; since I was already at it, I also used
 6610: @code{create}/@code{does>} for the lower level (try using
 6611: @code{postpone} etc. as an exercise), resulting in the following
 6612: definition:
 6613: 
 6614: @example
 6615: : define-format ( disasm-xt table-xt -- )
 6616:     \ define an instruction format that uses disasm-xt for
 6617:     \ disassembling and enters the defined instructions into table
 6618:     \ table-xt
 6619:     create 2,
 6620: does> ( u "inst" -- )
 6621:     \ defines an anonymous word for disassembling instruction inst,
 6622:     \ and enters it as u-th entry into table-xt
 6623:     2@@ swap here name string, ( u table-xt disasm-xt c-addr ) \ remember string
 6624:     noname create 2,      \ define anonymous word
 6625:     execute latestxt swap ! \ enter xt of defined word into table-xt
 6626: does> ( addr w -- )
 6627:     \ disassemble instruction w at addr
 6628:     2@@ >r ( addr w disasm-xt R: c-addr )
 6629:     execute ( R: c-addr ) \ disassemble operands
 6630:     r> count type ; \ print name 
 6631: @end example
 6632: 
 6633: Note that the tables here (in contrast to above) do the @code{cells +}
 6634: by themselves (that's why you have to pass an xt).  This word is used in
 6635: the following way:
 6636: 
 6637: @example
 6638: ' @var{disasm-operands} ' @var{table} define-format @var{inst-format}
 6639: @end example
 6640: 
 6641: As shown above, the defined instruction format is then used like this:
 6642: 
 6643: @example
 6644: @var{entry-num} @var{inst-format} @var{inst-name}
 6645: @end example
 6646: 
 6647: In terms of currying, this kind of two-level defining word provides the
 6648: parameters in three stages: first @var{disasm-operands} and @var{table},
 6649: then @var{entry-num} and @var{inst-name}, finally @code{addr w}, i.e.,
 6650: the instruction to be disassembled.  
 6651: 
 6652: Of course this did not quite fit all the instruction format names used
 6653: in @file{insts.fs}, so I had to define a few wrappers that conditioned
 6654: the parameters into the right form.
 6655: 
 6656: If you have trouble following this section, don't worry.  First, this is
 6657: involved and takes time (and probably some playing around) to
 6658: understand; second, this is the first two-level
 6659: @code{create}/@code{does>} word I have written in seventeen years of
 6660: Forth; and if I did not have @file{insts.fs} to start with, I may well
 6661: have elected to use just a one-level defining word (with some repeating
 6662: of parameters when using the defining word). So it is not necessary to
 6663: understand this, but it may improve your understanding of Forth.
 6664: 
 6665: 
 6666: @node Const-does>,  , Advanced does> usage example, User-defined Defining Words
 6667: @subsubsection @code{Const-does>}
 6668: 
 6669: A frequent use of @code{create}...@code{does>} is for transferring some
 6670: values from definition-time to run-time.  Gforth supports this use with
 6671: 
 6672: doc-const-does>
 6673: 
 6674: A typical use of this word is:
 6675: 
 6676: @example
 6677: : curry+ ( n1 "name" -- )
 6678: 1 0 CONST-DOES> ( n2 -- n1+n2 )
 6679:     + ;
 6680: 
 6681: 3 curry+ 3+
 6682: @end example
 6683: 
 6684: Here the @code{1 0} means that 1 cell and 0 floats are transferred from
 6685: definition to run-time.
 6686: 
 6687: The advantages of using @code{const-does>} are:
 6688: 
 6689: @itemize
 6690: 
 6691: @item
 6692: You don't have to deal with storing and retrieving the values, i.e.,
 6693: your program becomes more writable and readable.
 6694: 
 6695: @item
 6696: When using @code{does>}, you have to introduce a @code{@@} that cannot
 6697: be optimized away (because you could change the data using
 6698: @code{>body}...@code{!}); @code{const-does>} avoids this problem.
 6699: 
 6700: @end itemize
 6701: 
 6702: An ANS Forth implementation of @code{const-does>} is available in
 6703: @file{compat/const-does.fs}.
 6704: 
 6705: 
 6706: @node Deferred Words, Aliases, User-defined Defining Words, Defining Words
 6707: @subsection Deferred Words
 6708: @cindex deferred words
 6709: 
 6710: The defining word @code{Defer} allows you to define a word by name
 6711: without defining its behaviour; the definition of its behaviour is
 6712: deferred. Here are two situation where this can be useful:
 6713: 
 6714: @itemize @bullet
 6715: @item
 6716: Where you want to allow the behaviour of a word to be altered later, and
 6717: for all precompiled references to the word to change when its behaviour
 6718: is changed.
 6719: @item
 6720: For mutual recursion; @xref{Calls and returns}.
 6721: @end itemize
 6722: 
 6723: In the following example, @code{foo} always invokes the version of
 6724: @code{greet} that prints ``@code{Good morning}'' whilst @code{bar}
 6725: always invokes the version that prints ``@code{Hello}''. There is no way
 6726: of getting @code{foo} to use the later version without re-ordering the
 6727: source code and recompiling it.
 6728: 
 6729: @example
 6730: : greet ." Good morning" ;
 6731: : foo ... greet ... ;
 6732: : greet ." Hello" ;
 6733: : bar ... greet ... ;
 6734: @end example
 6735: 
 6736: This problem can be solved by defining @code{greet} as a @code{Defer}red
 6737: word. The behaviour of a @code{Defer}red word can be defined and
 6738: redefined at any time by using @code{IS} to associate the xt of a
 6739: previously-defined word with it. The previous example becomes:
 6740: 
 6741: @example
 6742: Defer greet ( -- )
 6743: : foo ... greet ... ;
 6744: : bar ... greet ... ;
 6745: : greet1 ( -- ) ." Good morning" ;
 6746: : greet2 ( -- ) ." Hello" ;
 6747: ' greet2 IS greet  \ make greet behave like greet2
 6748: @end example
 6749: 
 6750: @progstyle
 6751: You should write a stack comment for every deferred word, and put only
 6752: XTs into deferred words that conform to this stack effect.  Otherwise
 6753: it's too difficult to use the deferred word.
 6754: 
 6755: A deferred word can be used to improve the statistics-gathering example
 6756: from @ref{User-defined Defining Words}; rather than edit the
 6757: application's source code to change every @code{:} to a @code{my:}, do
 6758: this:
 6759: 
 6760: @example
 6761: : real: : ;     \ retain access to the original
 6762: defer :         \ redefine as a deferred word
 6763: ' my: IS :      \ use special version of :
 6764: \
 6765: \ load application here
 6766: \
 6767: ' real: IS :    \ go back to the original
 6768: @end example
 6769: 
 6770: 
 6771: One thing to note is that @code{IS} has special compilation semantics,
 6772: such that it parses the name at compile time (like @code{TO}):
 6773: 
 6774: @example
 6775: : set-greet ( xt -- )
 6776:   IS greet ;
 6777: 
 6778: ' greet1 set-greet
 6779: @end example
 6780: 
 6781: In situations where @code{IS} does not fit, use @code{defer!} instead.
 6782: 
 6783: A deferred word can only inherit execution semantics from the xt
 6784: (because that is all that an xt can represent -- for more discussion of
 6785: this @pxref{Tokens for Words}); by default it will have default
 6786: interpretation and compilation semantics deriving from this execution
 6787: semantics.  However, you can change the interpretation and compilation
 6788: semantics of the deferred word in the usual ways:
 6789: 
 6790: @example
 6791: : bar .... ; immediate
 6792: Defer fred immediate
 6793: Defer jim
 6794: 
 6795: ' bar IS jim  \ jim has default semantics
 6796: ' bar IS fred \ fred is immediate
 6797: @end example
 6798: 
 6799: doc-defer
 6800: doc-defer!
 6801: doc-is
 6802: doc-defer@
 6803: doc-action-of
 6804: @comment TODO document these: what's defers [is]
 6805: doc-defers
 6806: 
 6807: @c Use @code{words-deferred} to see a list of deferred words.
 6808: 
 6809: Definitions of these words (except @code{defers}) in ANS Forth are
 6810: provided in @file{compat/defer.fs}.
 6811: 
 6812: 
 6813: @node Aliases,  , Deferred Words, Defining Words
 6814: @subsection Aliases
 6815: @cindex aliases
 6816: 
 6817: The defining word @code{Alias} allows you to define a word by name that
 6818: has the same behaviour as some other word. Here are two situation where
 6819: this can be useful:
 6820: 
 6821: @itemize @bullet
 6822: @item
 6823: When you want access to a word's definition from a different word list
 6824: (for an example of this, see the definition of the @code{Root} word list
 6825: in the Gforth source).
 6826: @item
 6827: When you want to create a synonym; a definition that can be known by
 6828: either of two names (for example, @code{THEN} and @code{ENDIF} are
 6829: aliases).
 6830: @end itemize
 6831: 
 6832: Like deferred words, an alias has default compilation and interpretation
 6833: semantics at the beginning (not the modifications of the other word),
 6834: but you can change them in the usual ways (@code{immediate},
 6835: @code{compile-only}). For example:
 6836: 
 6837: @example
 6838: : foo ... ; immediate
 6839: 
 6840: ' foo Alias bar \ bar is not an immediate word
 6841: ' foo Alias fooby immediate \ fooby is an immediate word
 6842: @end example
 6843: 
 6844: Words that are aliases have the same xt, different headers in the
 6845: dictionary, and consequently different name tokens (@pxref{Tokens for
 6846: Words}) and possibly different immediate flags.  An alias can only have
 6847: default or immediate compilation semantics; you can define aliases for
 6848: combined words with @code{interpret/compile:} -- see @ref{Combined words}.
 6849: 
 6850: doc-alias
 6851: 
 6852: 
 6853: @node Interpretation and Compilation Semantics, Tokens for Words, Defining Words, Words
 6854: @section Interpretation and Compilation Semantics
 6855: @cindex semantics, interpretation and compilation
 6856: 
 6857: @c !! state and ' are used without explanation
 6858: @c example for immediate/compile-only? or is the tutorial enough
 6859: 
 6860: @cindex interpretation semantics
 6861: The @dfn{interpretation semantics} of a (named) word are what the text
 6862: interpreter does when it encounters the word in interpret state. It also
 6863: appears in some other contexts, e.g., the execution token returned by
 6864: @code{' @i{word}} identifies the interpretation semantics of @i{word}
 6865: (in other words, @code{' @i{word} execute} is equivalent to
 6866: interpret-state text interpretation of @code{@i{word}}).
 6867: 
 6868: @cindex compilation semantics
 6869: The @dfn{compilation semantics} of a (named) word are what the text
 6870: interpreter does when it encounters the word in compile state. It also
 6871: appears in other contexts, e.g, @code{POSTPONE @i{word}}
 6872: compiles@footnote{In standard terminology, ``appends to the current
 6873: definition''.} the compilation semantics of @i{word}.
 6874: 
 6875: @cindex execution semantics
 6876: The standard also talks about @dfn{execution semantics}. They are used
 6877: only for defining the interpretation and compilation semantics of many
 6878: words. By default, the interpretation semantics of a word are to
 6879: @code{execute} its execution semantics, and the compilation semantics of
 6880: a word are to @code{compile,} its execution semantics.@footnote{In
 6881: standard terminology: The default interpretation semantics are its
 6882: execution semantics; the default compilation semantics are to append its
 6883: execution semantics to the execution semantics of the current
 6884: definition.}
 6885: 
 6886: Unnamed words (@pxref{Anonymous Definitions}) cannot be encountered by
 6887: the text interpreter, ticked, or @code{postpone}d, so they have no
 6888: interpretation or compilation semantics.  Their behaviour is represented
 6889: by their XT (@pxref{Tokens for Words}), and we call it execution
 6890: semantics, too.
 6891: 
 6892: @comment TODO expand, make it co-operate with new sections on text interpreter.
 6893: 
 6894: @cindex immediate words
 6895: @cindex compile-only words
 6896: You can change the semantics of the most-recently defined word:
 6897: 
 6898: 
 6899: doc-immediate
 6900: doc-compile-only
 6901: doc-restrict
 6902: 
 6903: By convention, words with non-default compilation semantics (e.g.,
 6904: immediate words) often have names surrounded with brackets (e.g.,
 6905: @code{[']}, @pxref{Execution token}).
 6906: 
 6907: Note that ticking (@code{'}) a compile-only word gives an error
 6908: (``Interpreting a compile-only word'').
 6909: 
 6910: @menu
 6911: * Combined words::              
 6912: @end menu
 6913: 
 6914: 
 6915: @node Combined words,  , Interpretation and Compilation Semantics, Interpretation and Compilation Semantics
 6916: @subsection Combined Words
 6917: @cindex combined words
 6918: 
 6919: Gforth allows you to define @dfn{combined words} -- words that have an
 6920: arbitrary combination of interpretation and compilation semantics.
 6921: 
 6922: doc-interpret/compile:
 6923: 
 6924: This feature was introduced for implementing @code{TO} and @code{S"}. I
 6925: recommend that you do not define such words, as cute as they may be:
 6926: they make it hard to get at both parts of the word in some contexts.
 6927: E.g., assume you want to get an execution token for the compilation
 6928: part. Instead, define two words, one that embodies the interpretation
 6929: part, and one that embodies the compilation part.  Once you have done
 6930: that, you can define a combined word with @code{interpret/compile:} for
 6931: the convenience of your users.
 6932: 
 6933: You might try to use this feature to provide an optimizing
 6934: implementation of the default compilation semantics of a word. For
 6935: example, by defining:
 6936: @example
 6937: :noname
 6938:    foo bar ;
 6939: :noname
 6940:    POSTPONE foo POSTPONE bar ;
 6941: interpret/compile: opti-foobar
 6942: @end example
 6943: 
 6944: @noindent
 6945: as an optimizing version of:
 6946: 
 6947: @example
 6948: : foobar
 6949:     foo bar ;
 6950: @end example
 6951: 
 6952: Unfortunately, this does not work correctly with @code{[compile]},
 6953: because @code{[compile]} assumes that the compilation semantics of all
 6954: @code{interpret/compile:} words are non-default. I.e., @code{[compile]
 6955: opti-foobar} would compile compilation semantics, whereas
 6956: @code{[compile] foobar} would compile interpretation semantics.
 6957: 
 6958: @cindex state-smart words (are a bad idea)
 6959: @anchor{state-smartness}
 6960: Some people try to use @dfn{state-smart} words to emulate the feature provided
 6961: by @code{interpret/compile:} (words are state-smart if they check
 6962: @code{STATE} during execution). E.g., they would try to code
 6963: @code{foobar} like this:
 6964: 
 6965: @example
 6966: : foobar
 6967:   STATE @@
 6968:   IF ( compilation state )
 6969:     POSTPONE foo POSTPONE bar
 6970:   ELSE
 6971:     foo bar
 6972:   ENDIF ; immediate
 6973: @end example
 6974: 
 6975: Although this works if @code{foobar} is only processed by the text
 6976: interpreter, it does not work in other contexts (like @code{'} or
 6977: @code{POSTPONE}). E.g., @code{' foobar} will produce an execution token
 6978: for a state-smart word, not for the interpretation semantics of the
 6979: original @code{foobar}; when you execute this execution token (directly
 6980: with @code{EXECUTE} or indirectly through @code{COMPILE,}) in compile
 6981: state, the result will not be what you expected (i.e., it will not
 6982: perform @code{foo bar}). State-smart words are a bad idea. Simply don't
 6983: write them@footnote{For a more detailed discussion of this topic, see
 6984: M. Anton Ertl,
 6985: @cite{@uref{http://www.complang.tuwien.ac.at/papers/ertl98.ps.gz,@code{State}-smartness---Why
 6986: it is Evil and How to Exorcise it}}, EuroForth '98.}!
 6987: 
 6988: @cindex defining words with arbitrary semantics combinations
 6989: It is also possible to write defining words that define words with
 6990: arbitrary combinations of interpretation and compilation semantics. In
 6991: general, they look like this:
 6992: 
 6993: @example
 6994: : def-word
 6995:     create-interpret/compile
 6996:     @i{code1}
 6997: interpretation>
 6998:     @i{code2}
 6999: <interpretation
 7000: compilation>
 7001:     @i{code3}
 7002: <compilation ;
 7003: @end example
 7004: 
 7005: For a @i{word} defined with @code{def-word}, the interpretation
 7006: semantics are to push the address of the body of @i{word} and perform
 7007: @i{code2}, and the compilation semantics are to push the address of
 7008: the body of @i{word} and perform @i{code3}. E.g., @code{constant}
 7009: can also be defined like this (except that the defined constants don't
 7010: behave correctly when @code{[compile]}d):
 7011: 
 7012: @example
 7013: : constant ( n "name" -- )
 7014:     create-interpret/compile
 7015:     ,
 7016: interpretation> ( -- n )
 7017:     @@
 7018: <interpretation
 7019: compilation> ( compilation. -- ; run-time. -- n )
 7020:     @@ postpone literal
 7021: <compilation ;
 7022: @end example
 7023: 
 7024: 
 7025: doc-create-interpret/compile
 7026: doc-interpretation>
 7027: doc-<interpretation
 7028: doc-compilation>
 7029: doc-<compilation
 7030: 
 7031: 
 7032: Words defined with @code{interpret/compile:} and
 7033: @code{create-interpret/compile} have an extended header structure that
 7034: differs from other words; however, unless you try to access them with
 7035: plain address arithmetic, you should not notice this. Words for
 7036: accessing the header structure usually know how to deal with this; e.g.,
 7037: @code{'} @i{word} @code{>body} also gives you the body of a word created
 7038: with @code{create-interpret/compile}.
 7039: 
 7040: 
 7041: @c -------------------------------------------------------------
 7042: @node Tokens for Words, Compiling words, Interpretation and Compilation Semantics, Words
 7043: @section Tokens for Words
 7044: @cindex tokens for words
 7045: 
 7046: This section describes the creation and use of tokens that represent
 7047: words.
 7048: 
 7049: @menu
 7050: * Execution token::             represents execution/interpretation semantics
 7051: * Compilation token::           represents compilation semantics
 7052: * Name token::                  represents named words
 7053: @end menu
 7054: 
 7055: @node Execution token, Compilation token, Tokens for Words, Tokens for Words
 7056: @subsection Execution token
 7057: 
 7058: @cindex xt
 7059: @cindex execution token
 7060: An @dfn{execution token} (@i{XT}) represents some behaviour of a word.
 7061: You can use @code{execute} to invoke this behaviour.
 7062: 
 7063: @cindex tick (')
 7064: You can use @code{'} to get an execution token that represents the
 7065: interpretation semantics of a named word:
 7066: 
 7067: @example
 7068: 5 ' .   ( n xt ) 
 7069: execute ( )      \ execute the xt (i.e., ".")
 7070: @end example
 7071: 
 7072: doc-'
 7073: 
 7074: @code{'} parses at run-time; there is also a word @code{[']} that parses
 7075: when it is compiled, and compiles the resulting XT:
 7076: 
 7077: @example
 7078: : foo ['] . execute ;
 7079: 5 foo
 7080: : bar ' execute ; \ by contrast,
 7081: 5 bar .           \ ' parses "." when bar executes
 7082: @end example
 7083: 
 7084: doc-[']
 7085: 
 7086: If you want the execution token of @i{word}, write @code{['] @i{word}}
 7087: in compiled code and @code{' @i{word}} in interpreted code.  Gforth's
 7088: @code{'} and @code{[']} behave somewhat unusually by complaining about
 7089: compile-only words (because these words have no interpretation
 7090: semantics).  You might get what you want by using @code{COMP' @i{word}
 7091: DROP} or @code{[COMP'] @i{word} DROP} (for details @pxref{Compilation
 7092: token}).
 7093: 
 7094: Another way to get an XT is @code{:noname} or @code{latestxt}
 7095: (@pxref{Anonymous Definitions}).  For anonymous words this gives an xt
 7096: for the only behaviour the word has (the execution semantics).  For
 7097: named words, @code{latestxt} produces an XT for the same behaviour it
 7098: would produce if the word was defined anonymously.
 7099: 
 7100: @example
 7101: :noname ." hello" ;
 7102: execute
 7103: @end example
 7104: 
 7105: An XT occupies one cell and can be manipulated like any other cell.
 7106: 
 7107: @cindex code field address
 7108: @cindex CFA
 7109: In ANS Forth the XT is just an abstract data type (i.e., defined by the
 7110: operations that produce or consume it).  For old hands: In Gforth, the
 7111: XT is implemented as a code field address (CFA).
 7112: 
 7113: doc-execute
 7114: doc-perform
 7115: 
 7116: @node Compilation token, Name token, Execution token, Tokens for Words
 7117: @subsection Compilation token
 7118: 
 7119: @cindex compilation token
 7120: @cindex CT (compilation token)
 7121: Gforth represents the compilation semantics of a named word by a
 7122: @dfn{compilation token} consisting of two cells: @i{w xt}. The top cell
 7123: @i{xt} is an execution token. The compilation semantics represented by
 7124: the compilation token can be performed with @code{execute}, which
 7125: consumes the whole compilation token, with an additional stack effect
 7126: determined by the represented compilation semantics.
 7127: 
 7128: At present, the @i{w} part of a compilation token is an execution token,
 7129: and the @i{xt} part represents either @code{execute} or
 7130: @code{compile,}@footnote{Depending upon the compilation semantics of the
 7131: word. If the word has default compilation semantics, the @i{xt} will
 7132: represent @code{compile,}. Otherwise (e.g., for immediate words), the
 7133: @i{xt} will represent @code{execute}.}. However, don't rely on that
 7134: knowledge, unless necessary; future versions of Gforth may introduce
 7135: unusual compilation tokens (e.g., a compilation token that represents
 7136: the compilation semantics of a literal).
 7137: 
 7138: You can perform the compilation semantics represented by the compilation
 7139: token with @code{execute}.  You can compile the compilation semantics
 7140: with @code{postpone,}. I.e., @code{COMP' @i{word} postpone,} is
 7141: equivalent to @code{postpone @i{word}}.
 7142: 
 7143: doc-[comp']
 7144: doc-comp'
 7145: doc-postpone,
 7146: 
 7147: @node Name token,  , Compilation token, Tokens for Words
 7148: @subsection Name token
 7149: 
 7150: @cindex name token
 7151: Gforth represents named words by the @dfn{name token}, (@i{nt}).  Name
 7152: token is an abstract data type that occurs as argument or result of the
 7153: words below.
 7154: 
 7155: @c !! put this elswhere?
 7156: @cindex name field address
 7157: @cindex NFA
 7158: The closest thing to the nt in older Forth systems is the name field
 7159: address (NFA), but there are significant differences: in older Forth
 7160: systems each word had a unique NFA, LFA, CFA and PFA (in this order, or
 7161: LFA, NFA, CFA, PFA) and there were words for getting from one to the
 7162: next.  In contrast, in Gforth 0@dots{}n nts correspond to one xt; there
 7163: is a link field in the structure identified by the name token, but
 7164: searching usually uses a hash table external to these structures; the
 7165: name in Gforth has a cell-wide count-and-flags field, and the nt is not
 7166: implemented as the address of that count field.
 7167: 
 7168: doc-find-name
 7169: doc-latest
 7170: doc->name
 7171: doc-name>int
 7172: doc-name?int
 7173: doc-name>comp
 7174: doc-name>string
 7175: doc-id.
 7176: doc-.name
 7177: doc-.id
 7178: 
 7179: @c ----------------------------------------------------------
 7180: @node Compiling words, The Text Interpreter, Tokens for Words, Words
 7181: @section Compiling words
 7182: @cindex compiling words
 7183: @cindex macros
 7184: 
 7185: In contrast to most other languages, Forth has no strict boundary
 7186: between compilation and run-time.  E.g., you can run arbitrary code
 7187: between defining words (or for computing data used by defining words
 7188: like @code{constant}). Moreover, @code{Immediate} (@pxref{Interpretation
 7189: and Compilation Semantics} and @code{[}...@code{]} (see below) allow
 7190: running arbitrary code while compiling a colon definition (exception:
 7191: you must not allot dictionary space).
 7192: 
 7193: @menu
 7194: * Literals::                    Compiling data values
 7195: * Macros::                      Compiling words
 7196: @end menu
 7197: 
 7198: @node Literals, Macros, Compiling words, Compiling words
 7199: @subsection Literals
 7200: @cindex Literals
 7201: 
 7202: The simplest and most frequent example is to compute a literal during
 7203: compilation.  E.g., the following definition prints an array of strings,
 7204: one string per line:
 7205: 
 7206: @example
 7207: : .strings ( addr u -- ) \ gforth
 7208:     2* cells bounds U+DO
 7209: 	cr i 2@@ type
 7210:     2 cells +LOOP ;  
 7211: @end example
 7212: 
 7213: With a simple-minded compiler like Gforth's, this computes @code{2
 7214: cells} on every loop iteration.  You can compute this value once and for
 7215: all at compile time and compile it into the definition like this:
 7216: 
 7217: @example
 7218: : .strings ( addr u -- ) \ gforth
 7219:     2* cells bounds U+DO
 7220: 	cr i 2@@ type
 7221:     [ 2 cells ] literal +LOOP ;  
 7222: @end example
 7223: 
 7224: @code{[} switches the text interpreter to interpret state (you will get
 7225: an @code{ok} prompt if you type this example interactively and insert a
 7226: newline between @code{[} and @code{]}), so it performs the
 7227: interpretation semantics of @code{2 cells}; this computes a number.
 7228: @code{]} switches the text interpreter back into compile state.  It then
 7229: performs @code{Literal}'s compilation semantics, which are to compile
 7230: this number into the current word.  You can decompile the word with
 7231: @code{see .strings} to see the effect on the compiled code.
 7232: 
 7233: You can also optimize the @code{2* cells} into @code{[ 2 cells ] literal
 7234: *} in this way.
 7235: 
 7236: doc-[
 7237: doc-]
 7238: doc-literal
 7239: doc-]L
 7240: 
 7241: There are also words for compiling other data types than single cells as
 7242: literals:
 7243: 
 7244: doc-2literal
 7245: doc-fliteral
 7246: doc-sliteral
 7247: 
 7248: @cindex colon-sys, passing data across @code{:}
 7249: @cindex @code{:}, passing data across
 7250: You might be tempted to pass data from outside a colon definition to the
 7251: inside on the data stack.  This does not work, because @code{:} puhes a
 7252: colon-sys, making stuff below unaccessible.  E.g., this does not work:
 7253: 
 7254: @example
 7255: 5 : foo literal ; \ error: "unstructured"
 7256: @end example
 7257: 
 7258: Instead, you have to pass the value in some other way, e.g., through a
 7259: variable:
 7260: 
 7261: @example
 7262: variable temp
 7263: 5 temp !
 7264: : foo [ temp @@ ] literal ;
 7265: @end example
 7266: 
 7267: 
 7268: @node Macros,  , Literals, Compiling words
 7269: @subsection Macros
 7270: @cindex Macros
 7271: @cindex compiling compilation semantics
 7272: 
 7273: @code{Literal} and friends compile data values into the current
 7274: definition.  You can also write words that compile other words into the
 7275: current definition.  E.g.,
 7276: 
 7277: @example
 7278: : compile-+ ( -- ) \ compiled code: ( n1 n2 -- n )
 7279:   POSTPONE + ;
 7280: 
 7281: : foo ( n1 n2 -- n )
 7282:   [ compile-+ ] ;
 7283: 1 2 foo .
 7284: @end example
 7285: 
 7286: This is equivalent to @code{: foo + ;} (@code{see foo} to check this).
 7287: What happens in this example?  @code{Postpone} compiles the compilation
 7288: semantics of @code{+} into @code{compile-+}; later the text interpreter
 7289: executes @code{compile-+} and thus the compilation semantics of +, which
 7290: compile (the execution semantics of) @code{+} into
 7291: @code{foo}.@footnote{A recent RFI answer requires that compiling words
 7292: should only be executed in compile state, so this example is not
 7293: guaranteed to work on all standard systems, but on any decent system it
 7294: will work.}
 7295: 
 7296: doc-postpone
 7297: doc-[compile]
 7298: 
 7299: Compiling words like @code{compile-+} are usually immediate (or similar)
 7300: so you do not have to switch to interpret state to execute them;
 7301: mopifying the last example accordingly produces:
 7302: 
 7303: @example
 7304: : [compile-+] ( compilation: --; interpretation: -- )
 7305:   \ compiled code: ( n1 n2 -- n )
 7306:   POSTPONE + ; immediate
 7307: 
 7308: : foo ( n1 n2 -- n )
 7309:   [compile-+] ;
 7310: 1 2 foo .
 7311: @end example
 7312: 
 7313: Immediate compiling words are similar to macros in other languages (in
 7314: particular, Lisp).  The important differences to macros in, e.g., C are:
 7315: 
 7316: @itemize @bullet
 7317: 
 7318: @item
 7319: You use the same language for defining and processing macros, not a
 7320: separate preprocessing language and processor.
 7321: 
 7322: @item
 7323: Consequently, the full power of Forth is available in macro definitions.
 7324: E.g., you can perform arbitrarily complex computations, or generate
 7325: different code conditionally or in a loop (e.g., @pxref{Advanced macros
 7326: Tutorial}).  This power is very useful when writing a parser generators
 7327: or other code-generating software.
 7328: 
 7329: @item
 7330: Macros defined using @code{postpone} etc. deal with the language at a
 7331: higher level than strings; name binding happens at macro definition
 7332: time, so you can avoid the pitfalls of name collisions that can happen
 7333: in C macros.  Of course, Forth is a liberal language and also allows to
 7334: shoot yourself in the foot with text-interpreted macros like
 7335: 
 7336: @example
 7337: : [compile-+] s" +" evaluate ; immediate
 7338: @end example
 7339: 
 7340: Apart from binding the name at macro use time, using @code{evaluate}
 7341: also makes your definition @code{state}-smart (@pxref{state-smartness}).
 7342: @end itemize
 7343: 
 7344: You may want the macro to compile a number into a word.  The word to do
 7345: it is @code{literal}, but you have to @code{postpone} it, so its
 7346: compilation semantics take effect when the macro is executed, not when
 7347: it is compiled:
 7348: 
 7349: @example
 7350: : [compile-5] ( -- ) \ compiled code: ( -- n )
 7351:   5 POSTPONE literal ; immediate
 7352: 
 7353: : foo [compile-5] ;
 7354: foo .
 7355: @end example
 7356: 
 7357: You may want to pass parameters to a macro, that the macro should
 7358: compile into the current definition.  If the parameter is a number, then
 7359: you can use @code{postpone literal} (similar for other values).
 7360: 
 7361: If you want to pass a word that is to be compiled, the usual way is to
 7362: pass an execution token and @code{compile,} it:
 7363: 
 7364: @example
 7365: : twice1 ( xt -- ) \ compiled code: ... -- ...
 7366:   dup compile, compile, ;
 7367: 
 7368: : 2+ ( n1 -- n2 )
 7369:   [ ' 1+ twice1 ] ;
 7370: @end example
 7371: 
 7372: doc-compile,
 7373: 
 7374: An alternative available in Gforth, that allows you to pass compile-only
 7375: words as parameters is to use the compilation token (@pxref{Compilation
 7376: token}).  The same example in this technique:
 7377: 
 7378: @example
 7379: : twice ( ... ct -- ... ) \ compiled code: ... -- ...
 7380:   2dup 2>r execute 2r> execute ;
 7381: 
 7382: : 2+ ( n1 -- n2 )
 7383:   [ comp' 1+ twice ] ;
 7384: @end example
 7385: 
 7386: In the example above @code{2>r} and @code{2r>} ensure that @code{twice}
 7387: works even if the executed compilation semantics has an effect on the
 7388: data stack.
 7389: 
 7390: You can also define complete definitions with these words; this provides
 7391: an alternative to using @code{does>} (@pxref{User-defined Defining
 7392: Words}).  E.g., instead of
 7393: 
 7394: @example
 7395: : curry+ ( n1 "name" -- )
 7396:     CREATE ,
 7397: DOES> ( n2 -- n1+n2 )
 7398:     @@ + ;
 7399: @end example
 7400: 
 7401: you could define
 7402: 
 7403: @example
 7404: : curry+ ( n1 "name" -- )
 7405:   \ name execution: ( n2 -- n1+n2 )
 7406:   >r : r> POSTPONE literal POSTPONE + POSTPONE ; ;
 7407: 
 7408: -3 curry+ 3-
 7409: see 3-
 7410: @end example
 7411: 
 7412: The sequence @code{>r : r>} is necessary, because @code{:} puts a
 7413: colon-sys on the data stack that makes everything below it unaccessible.
 7414: 
 7415: This way of writing defining words is sometimes more, sometimes less
 7416: convenient than using @code{does>} (@pxref{Advanced does> usage
 7417: example}).  One advantage of this method is that it can be optimized
 7418: better, because the compiler knows that the value compiled with
 7419: @code{literal} is fixed, whereas the data associated with a
 7420: @code{create}d word can be changed.
 7421: 
 7422: @c ----------------------------------------------------------
 7423: @node The Text Interpreter, The Input Stream, Compiling words, Words
 7424: @section  The Text Interpreter
 7425: @cindex interpreter - outer
 7426: @cindex text interpreter
 7427: @cindex outer interpreter
 7428: 
 7429: @c Should we really describe all these ugly details?  IMO the text
 7430: @c interpreter should be much cleaner, but that may not be possible within
 7431: @c ANS Forth. - anton
 7432: @c nac-> I wanted to explain how it works to show how you can exploit
 7433: @c it in your own programs. When I was writing a cross-compiler, figuring out
 7434: @c some of these gory details was very helpful to me. None of the textbooks
 7435: @c I've seen cover it, and the most modern Forth textbook -- Forth Inc's,
 7436: @c seems to positively avoid going into too much detail for some of
 7437: @c the internals.
 7438: 
 7439: @c anton: ok.  I wonder, though, if this is the right place; for some stuff
 7440: @c it is; for the ugly details, I would prefer another place.  I wonder
 7441: @c whether we should have a chapter before "Words" that describes some
 7442: @c basic concepts referred to in words, and a chapter after "Words" that
 7443: @c describes implementation details.
 7444: 
 7445: The text interpreter@footnote{This is an expanded version of the
 7446: material in @ref{Introducing the Text Interpreter}.} is an endless loop
 7447: that processes input from the current input device. It is also called
 7448: the outer interpreter, in contrast to the inner interpreter
 7449: (@pxref{Engine}) which executes the compiled Forth code on interpretive
 7450: implementations.
 7451: 
 7452: @cindex interpret state
 7453: @cindex compile state
 7454: The text interpreter operates in one of two states: @dfn{interpret
 7455: state} and @dfn{compile state}. The current state is defined by the
 7456: aptly-named variable @code{state}.
 7457: 
 7458: This section starts by describing how the text interpreter behaves when
 7459: it is in interpret state, processing input from the user input device --
 7460: the keyboard. This is the mode that a Forth system is in after it starts
 7461: up.
 7462: 
 7463: @cindex input buffer
 7464: @cindex terminal input buffer
 7465: The text interpreter works from an area of memory called the @dfn{input
 7466: buffer}@footnote{When the text interpreter is processing input from the
 7467: keyboard, this area of memory is called the @dfn{terminal input buffer}
 7468: (TIB) and is addressed by the (obsolescent) words @code{TIB} and
 7469: @code{#TIB}.}, which stores your keyboard input when you press the
 7470: @key{RET} key. Starting at the beginning of the input buffer, it skips
 7471: leading spaces (called @dfn{delimiters}) then parses a string (a
 7472: sequence of non-space characters) until it reaches either a space
 7473: character or the end of the buffer. Having parsed a string, it makes two
 7474: attempts to process it:
 7475: 
 7476: @cindex dictionary
 7477: @itemize @bullet
 7478: @item
 7479: It looks for the string in a @dfn{dictionary} of definitions. If the
 7480: string is found, the string names a @dfn{definition} (also known as a
 7481: @dfn{word}) and the dictionary search returns information that allows
 7482: the text interpreter to perform the word's @dfn{interpretation
 7483: semantics}. In most cases, this simply means that the word will be
 7484: executed.
 7485: @item
 7486: If the string is not found in the dictionary, the text interpreter
 7487: attempts to treat it as a number, using the rules described in
 7488: @ref{Number Conversion}. If the string represents a legal number in the
 7489: current radix, the number is pushed onto a parameter stack (the data
 7490: stack for integers, the floating-point stack for floating-point
 7491: numbers).
 7492: @end itemize
 7493: 
 7494: If both attempts fail, or if the word is found in the dictionary but has
 7495: no interpretation semantics@footnote{This happens if the word was
 7496: defined as @code{COMPILE-ONLY}.} the text interpreter discards the
 7497: remainder of the input buffer, issues an error message and waits for
 7498: more input. If one of the attempts succeeds, the text interpreter
 7499: repeats the parsing process until the whole of the input buffer has been
 7500: processed, at which point it prints the status message ``@code{ ok}''
 7501: and waits for more input.
 7502: 
 7503: @c anton: this should be in the input stream subsection (or below it)
 7504: 
 7505: @cindex parse area
 7506: The text interpreter keeps track of its position in the input buffer by
 7507: updating a variable called @code{>IN} (pronounced ``to-in''). The value
 7508: of @code{>IN} starts out as 0, indicating an offset of 0 from the start
 7509: of the input buffer. The region from offset @code{>IN @@} to the end of
 7510: the input buffer is called the @dfn{parse area}@footnote{In other words,
 7511: the text interpreter processes the contents of the input buffer by
 7512: parsing strings from the parse area until the parse area is empty.}.
 7513: This example shows how @code{>IN} changes as the text interpreter parses
 7514: the input buffer:
 7515: 
 7516: @example
 7517: : remaining >IN @@ SOURCE 2 PICK - -ROT + SWAP
 7518:   CR ." ->" TYPE ." <-" ; IMMEDIATE 
 7519: 
 7520: 1 2 3 remaining + remaining . 
 7521: 
 7522: : foo 1 2 3 remaining SWAP remaining ;
 7523: @end example
 7524: 
 7525: @noindent
 7526: The result is:
 7527: 
 7528: @example
 7529: ->+ remaining .<-
 7530: ->.<-5  ok
 7531: 
 7532: ->SWAP remaining ;-<
 7533: ->;<-  ok
 7534: @end example
 7535: 
 7536: @cindex parsing words
 7537: The value of @code{>IN} can also be modified by a word in the input
 7538: buffer that is executed by the text interpreter.  This means that a word
 7539: can ``trick'' the text interpreter into either skipping a section of the
 7540: input buffer@footnote{This is how parsing words work.} or into parsing a
 7541: section twice. For example:
 7542: 
 7543: @example
 7544: : lat ." <<foo>>" ;
 7545: : flat ." <<bar>>" >IN DUP @@ 3 - SWAP ! ;
 7546: @end example
 7547: 
 7548: @noindent
 7549: When @code{flat} is executed, this output is produced@footnote{Exercise
 7550: for the reader: what would happen if the @code{3} were replaced with
 7551: @code{4}?}:
 7552: 
 7553: @example
 7554: <<bar>><<foo>>
 7555: @end example
 7556: 
 7557: This technique can be used to work around some of the interoperability
 7558: problems of parsing words.  Of course, it's better to avoid parsing
 7559: words where possible.
 7560: 
 7561: @noindent
 7562: Two important notes about the behaviour of the text interpreter:
 7563: 
 7564: @itemize @bullet
 7565: @item
 7566: It processes each input string to completion before parsing additional
 7567: characters from the input buffer.
 7568: @item
 7569: It treats the input buffer as a read-only region (and so must your code).
 7570: @end itemize
 7571: 
 7572: @noindent
 7573: When the text interpreter is in compile state, its behaviour changes in
 7574: these ways:
 7575: 
 7576: @itemize @bullet
 7577: @item
 7578: If a parsed string is found in the dictionary, the text interpreter will
 7579: perform the word's @dfn{compilation semantics}. In most cases, this
 7580: simply means that the execution semantics of the word will be appended
 7581: to the current definition.
 7582: @item
 7583: When a number is encountered, it is compiled into the current definition
 7584: (as a literal) rather than being pushed onto a parameter stack.
 7585: @item
 7586: If an error occurs, @code{state} is modified to put the text interpreter
 7587: back into interpret state.
 7588: @item
 7589: Each time a line is entered from the keyboard, Gforth prints
 7590: ``@code{ compiled}'' rather than `` @code{ok}''.
 7591: @end itemize
 7592: 
 7593: @cindex text interpreter - input sources
 7594: When the text interpreter is using an input device other than the
 7595: keyboard, its behaviour changes in these ways:
 7596: 
 7597: @itemize @bullet
 7598: @item
 7599: When the parse area is empty, the text interpreter attempts to refill
 7600: the input buffer from the input source. When the input source is
 7601: exhausted, the input source is set back to the previous input source.
 7602: @item
 7603: It doesn't print out ``@code{ ok}'' or ``@code{ compiled}'' messages each
 7604: time the parse area is emptied.
 7605: @item
 7606: If an error occurs, the input source is set back to the user input
 7607: device.
 7608: @end itemize
 7609: 
 7610: You can read about this in more detail in @ref{Input Sources}.
 7611: 
 7612: doc->in
 7613: doc-source
 7614: 
 7615: doc-tib
 7616: doc-#tib
 7617: 
 7618: 
 7619: @menu
 7620: * Input Sources::               
 7621: * Number Conversion::           
 7622: * Interpret/Compile states::    
 7623: * Interpreter Directives::      
 7624: @end menu
 7625: 
 7626: @node Input Sources, Number Conversion, The Text Interpreter, The Text Interpreter
 7627: @subsection Input Sources
 7628: @cindex input sources
 7629: @cindex text interpreter - input sources
 7630: 
 7631: By default, the text interpreter processes input from the user input
 7632: device (the keyboard) when Forth starts up. The text interpreter can
 7633: process input from any of these sources:
 7634: 
 7635: @itemize @bullet
 7636: @item
 7637: The user input device -- the keyboard.
 7638: @item
 7639: A file, using the words described in @ref{Forth source files}.
 7640: @item
 7641: A block, using the words described in @ref{Blocks}.
 7642: @item
 7643: A text string, using @code{evaluate}.
 7644: @end itemize
 7645: 
 7646: A program can identify the current input device from the values of
 7647: @code{source-id} and @code{blk}.
 7648: 
 7649: 
 7650: doc-source-id
 7651: doc-blk
 7652: 
 7653: doc-save-input
 7654: doc-restore-input
 7655: 
 7656: doc-evaluate
 7657: doc-query
 7658: 
 7659: 
 7660: 
 7661: @node Number Conversion, Interpret/Compile states, Input Sources, The Text Interpreter
 7662: @subsection Number Conversion
 7663: @cindex number conversion
 7664: @cindex double-cell numbers, input format
 7665: @cindex input format for double-cell numbers
 7666: @cindex single-cell numbers, input format
 7667: @cindex input format for single-cell numbers
 7668: @cindex floating-point numbers, input format
 7669: @cindex input format for floating-point numbers
 7670: 
 7671: This section describes the rules that the text interpreter uses when it
 7672: tries to convert a string into a number.
 7673: 
 7674: Let <digit> represent any character that is a legal digit in the current
 7675: number base@footnote{For example, 0-9 when the number base is decimal or
 7676: 0-9, A-F when the number base is hexadecimal.}.
 7677: 
 7678: Let <decimal digit> represent any character in the range 0-9.
 7679: 
 7680: Let @{@i{a b}@} represent the @i{optional} presence of any of the characters
 7681: in the braces (@i{a} or @i{b} or neither).
 7682: 
 7683: Let * represent any number of instances of the previous character
 7684: (including none).
 7685: 
 7686: Let any other character represent itself.
 7687: 
 7688: @noindent
 7689: Now, the conversion rules are:
 7690: 
 7691: @itemize @bullet
 7692: @item
 7693: A string of the form <digit><digit>* is treated as a single-precision
 7694: (cell-sized) positive integer. Examples are 0 123 6784532 32343212343456 42
 7695: @item
 7696: A string of the form -<digit><digit>* is treated as a single-precision
 7697: (cell-sized) negative integer, and is represented using 2's-complement
 7698: arithmetic. Examples are -45 -5681 -0
 7699: @item
 7700: A string of the form <digit><digit>*.<digit>* is treated as a double-precision
 7701: (double-cell-sized) positive integer. Examples are 3465. 3.465 34.65
 7702: (all three of these represent the same number).
 7703: @item
 7704: A string of the form -<digit><digit>*.<digit>* is treated as a
 7705: double-precision (double-cell-sized) negative integer, and is
 7706: represented using 2's-complement arithmetic. Examples are -3465. -3.465
 7707: -34.65 (all three of these represent the same number).
 7708: @item
 7709: A string of the form @{+ -@}<decimal digit>@{.@}<decimal digit>*@{e
 7710: E@}@{+ -@}<decimal digit><decimal digit>* is treated as a floating-point
 7711: number. Examples are 1e 1e0 1.e 1.e0 +1e+0 (which all represent the same
 7712: number) +12.E-4
 7713: @end itemize
 7714: 
 7715: By default, the number base used for integer number conversion is
 7716: given by the contents of the variable @code{base}.  Note that a lot of
 7717: confusion can result from unexpected values of @code{base}.  If you
 7718: change @code{base} anywhere, make sure to save the old value and
 7719: restore it afterwards; better yet, use @code{base-execute}, which does
 7720: this for you.  In general I recommend keeping @code{base} decimal, and
 7721: using the prefixes described below for the popular non-decimal bases.
 7722: 
 7723: doc-dpl
 7724: doc-base-execute
 7725: doc-base
 7726: doc-hex
 7727: doc-decimal
 7728: 
 7729: @cindex '-prefix for character strings
 7730: @cindex &-prefix for decimal numbers
 7731: @cindex #-prefix for decimal numbers
 7732: @cindex %-prefix for binary numbers
 7733: @cindex $-prefix for hexadecimal numbers
 7734: @cindex 0x-prefix for hexadecimal numbers
 7735: Gforth allows you to override the value of @code{base} by using a
 7736: prefix@footnote{Some Forth implementations provide a similar scheme by
 7737: implementing @code{$} etc. as parsing words that process the subsequent
 7738: number in the input stream and push it onto the stack. For example, see
 7739: @cite{Number Conversion and Literals}, by Wil Baden; Forth Dimensions
 7740: 20(3) pages 26--27. In such implementations, unlike in Gforth, a space
 7741: is required between the prefix and the number.} before the first digit
 7742: of an (integer) number. The following prefixes are supported:
 7743: 
 7744: @itemize @bullet
 7745: @item
 7746: @code{&} -- decimal
 7747: @item
 7748: @code{#} -- decimal
 7749: @item
 7750: @code{%} -- binary
 7751: @item
 7752: @code{$} -- hexadecimal
 7753: @item
 7754: @code{0x} -- hexadecimal, if base<33.
 7755: @item
 7756: @code{'} -- numeric value (e.g., ASCII code) of next character; an
 7757: optional @code{'} may be present after the character.
 7758: @end itemize
 7759: 
 7760: Here are some examples, with the equivalent decimal number shown after
 7761: in braces:
 7762: 
 7763: -$41 (-65), %1001101 (205), %1001.0001 (145 - a double-precision number),
 7764: 'A (65),
 7765: -'a' (-97),
 7766: &905 (905), $abc (2478), $ABC (2478).
 7767: 
 7768: @cindex number conversion - traps for the unwary
 7769: @noindent
 7770: Number conversion has a number of traps for the unwary:
 7771: 
 7772: @itemize @bullet
 7773: @item
 7774: You cannot determine the current number base using the code sequence
 7775: @code{base @@ .} -- the number base is always 10 in the current number
 7776: base. Instead, use something like @code{base @@ dec.}
 7777: @item
 7778: If the number base is set to a value greater than 14 (for example,
 7779: hexadecimal), the number 123E4 is ambiguous; the conversion rules allow
 7780: it to be intepreted as either a single-precision integer or a
 7781: floating-point number (Gforth treats it as an integer). The ambiguity
 7782: can be resolved by explicitly stating the sign of the mantissa and/or
 7783: exponent: 123E+4 or +123E4 -- if the number base is decimal, no
 7784: ambiguity arises; either representation will be treated as a
 7785: floating-point number.
 7786: @item
 7787: There is a word @code{bin} but it does @i{not} set the number base!
 7788: It is used to specify file types.
 7789: @item
 7790: ANS Forth requires the @code{.} of a double-precision number to be the
 7791: final character in the string.  Gforth allows the @code{.} to be
 7792: anywhere after the first digit.
 7793: @item
 7794: The number conversion process does not check for overflow.
 7795: @item
 7796: In an ANS Forth program @code{base} is required to be decimal when
 7797: converting floating-point numbers.  In Gforth, number conversion to
 7798: floating-point numbers always uses base &10, irrespective of the value
 7799: of @code{base}.
 7800: @end itemize
 7801: 
 7802: You can read numbers into your programs with the words described in
 7803: @ref{Line input and conversion}.
 7804: 
 7805: @node Interpret/Compile states, Interpreter Directives, Number Conversion, The Text Interpreter
 7806: @subsection Interpret/Compile states
 7807: @cindex Interpret/Compile states
 7808: 
 7809: A standard program is not permitted to change @code{state}
 7810: explicitly. However, it can change @code{state} implicitly, using the
 7811: words @code{[} and @code{]}. When @code{[} is executed it switches
 7812: @code{state} to interpret state, and therefore the text interpreter
 7813: starts interpreting. When @code{]} is executed it switches @code{state}
 7814: to compile state and therefore the text interpreter starts
 7815: compiling. The most common usage for these words is for switching into
 7816: interpret state and back from within a colon definition; this technique
 7817: can be used to compile a literal (for an example, @pxref{Literals}) or
 7818: for conditional compilation (for an example, @pxref{Interpreter
 7819: Directives}).
 7820: 
 7821: 
 7822: @c This is a bad example: It's non-standard, and it's not necessary.
 7823: @c However, I can't think of a good example for switching into compile
 7824: @c state when there is no current word (@code{state}-smart words are not a
 7825: @c good reason).  So maybe we should use an example for switching into
 7826: @c interpret @code{state} in a colon def. - anton
 7827: @c nac-> I agree. I started out by putting in the example, then realised
 7828: @c that it was non-ANS, so wrote more words around it. I hope this
 7829: @c re-written version is acceptable to you. I do want to keep the example
 7830: @c as it is helpful for showing what is and what is not portable, particularly
 7831: @c where it outlaws a style in common use.
 7832: 
 7833: @c anton: it's more important to show what's portable.  After we have done
 7834: @c that, we can also show what's not.  In any case, I have written a
 7835: @c section Compiling Words which also deals with [ ].
 7836: 
 7837: @c  !! The following example does not work in Gforth 0.5.9 or later.
 7838: 
 7839: @c  @code{[} and @code{]} also give you the ability to switch into compile
 7840: @c  state and back, but we cannot think of any useful Standard application
 7841: @c  for this ability. Pre-ANS Forth textbooks have examples like this:
 7842: 
 7843: @c  @example
 7844: @c  : AA ." this is A" ;
 7845: @c  : BB ." this is B" ;
 7846: @c  : CC ." this is C" ;
 7847: 
 7848: @c  create table ] aa bb cc [
 7849: 
 7850: @c  : go ( n -- ) \ n is offset into table.. 0 for 1st entry
 7851: @c    cells table + @@ execute ;
 7852: @c  @end example
 7853: 
 7854: @c  This example builds a jump table; @code{0 go} will display ``@code{this
 7855: @c  is A}''. Using @code{[} and @code{]} in this example is equivalent to
 7856: @c  defining @code{table} like this:
 7857: 
 7858: @c  @example
 7859: @c  create table ' aa COMPILE, ' bb COMPILE, ' cc COMPILE,
 7860: @c  @end example
 7861: 
 7862: @c  The problem with this code is that the definition of @code{table} is not
 7863: @c  portable -- it @i{compile}s execution tokens into code space. Whilst it
 7864: @c  @i{may} work on systems where code space and data space co-incide, the
 7865: @c  Standard only allows data space to be assigned for a @code{CREATE}d
 7866: @c  word. In addition, the Standard only allows @code{@@} to access data
 7867: @c  space, whilst this example is using it to access code space. The only
 7868: @c  portable, Standard way to build this table is to build it in data space,
 7869: @c  like this:
 7870: 
 7871: @c  @example
 7872: @c  create table ' aa , ' bb , ' cc ,
 7873: @c  @end example
 7874: 
 7875: @c  doc-state
 7876: 
 7877: 
 7878: @node Interpreter Directives,  , Interpret/Compile states, The Text Interpreter
 7879: @subsection Interpreter Directives
 7880: @cindex interpreter directives
 7881: @cindex conditional compilation
 7882: 
 7883: These words are usually used in interpret state; typically to control
 7884: which parts of a source file are processed by the text
 7885: interpreter. There are only a few ANS Forth Standard words, but Gforth
 7886: supplements these with a rich set of immediate control structure words
 7887: to compensate for the fact that the non-immediate versions can only be
 7888: used in compile state (@pxref{Control Structures}). Typical usages:
 7889: 
 7890: @example
 7891: FALSE Constant HAVE-ASSEMBLER
 7892: .
 7893: .
 7894: HAVE-ASSEMBLER [IF]
 7895: : ASSEMBLER-FEATURE
 7896:   ...
 7897: ;
 7898: [ENDIF]
 7899: .
 7900: .
 7901: : SEE
 7902:   ... \ general-purpose SEE code
 7903:   [ HAVE-ASSEMBLER [IF] ]
 7904:   ... \ assembler-specific SEE code
 7905:   [ [ENDIF] ]
 7906: ;
 7907: @end example
 7908: 
 7909: 
 7910: doc-[IF]
 7911: doc-[ELSE]
 7912: doc-[THEN]
 7913: doc-[ENDIF]
 7914: 
 7915: doc-[IFDEF]
 7916: doc-[IFUNDEF]
 7917: 
 7918: doc-[?DO]
 7919: doc-[DO]
 7920: doc-[FOR]
 7921: doc-[LOOP]
 7922: doc-[+LOOP]
 7923: doc-[NEXT]
 7924: 
 7925: doc-[BEGIN]
 7926: doc-[UNTIL]
 7927: doc-[AGAIN]
 7928: doc-[WHILE]
 7929: doc-[REPEAT]
 7930: 
 7931: 
 7932: @c -------------------------------------------------------------
 7933: @node The Input Stream, Word Lists, The Text Interpreter, Words
 7934: @section The Input Stream
 7935: @cindex input stream
 7936: 
 7937: @c !! integrate this better with the "Text Interpreter" section
 7938: The text interpreter reads from the input stream, which can come from
 7939: several sources (@pxref{Input Sources}).  Some words, in particular
 7940: defining words, but also words like @code{'}, read parameters from the
 7941: input stream instead of from the stack.
 7942: 
 7943: Such words are called parsing words, because they parse the input
 7944: stream.  Parsing words are hard to use in other words, because it is
 7945: hard to pass program-generated parameters through the input stream.
 7946: They also usually have an unintuitive combination of interpretation and
 7947: compilation semantics when implemented naively, leading to various
 7948: approaches that try to produce a more intuitive behaviour
 7949: (@pxref{Combined words}).
 7950: 
 7951: It should be obvious by now that parsing words are a bad idea.  If you
 7952: want to implement a parsing word for convenience, also provide a factor
 7953: of the word that does not parse, but takes the parameters on the stack.
 7954: To implement the parsing word on top if it, you can use the following
 7955: words:
 7956: 
 7957: @c anton: these belong in the input stream section
 7958: doc-parse
 7959: doc-parse-name
 7960: doc-parse-word
 7961: doc-name
 7962: doc-word
 7963: doc-\"-parse
 7964: doc-refill
 7965: 
 7966: Conversely, if you have the bad luck (or lack of foresight) to have to
 7967: deal with parsing words without having such factors, how do you pass a
 7968: string that is not in the input stream to it?
 7969: 
 7970: doc-execute-parsing
 7971: 
 7972: A definition of this word in ANS Forth is provided in
 7973: @file{compat/execute-parsing.fs}.
 7974: 
 7975: If you want to run a parsing word on a file, the following word should
 7976: help:
 7977: 
 7978: doc-execute-parsing-file
 7979: 
 7980: @c -------------------------------------------------------------
 7981: @node Word Lists, Environmental Queries, The Input Stream, Words
 7982: @section Word Lists
 7983: @cindex word lists
 7984: @cindex header space
 7985: 
 7986: A wordlist is a list of named words; you can add new words and look up
 7987: words by name (and you can remove words in a restricted way with
 7988: markers).  Every named (and @code{reveal}ed) word is in one wordlist.
 7989: 
 7990: @cindex search order stack
 7991: The text interpreter searches the wordlists present in the search order
 7992: (a stack of wordlists), from the top to the bottom.  Within each
 7993: wordlist, the search starts conceptually at the newest word; i.e., if
 7994: two words in a wordlist have the same name, the newer word is found.
 7995: 
 7996: @cindex compilation word list
 7997: New words are added to the @dfn{compilation wordlist} (aka current
 7998: wordlist).
 7999: 
 8000: @cindex wid
 8001: A word list is identified by a cell-sized word list identifier (@i{wid})
 8002: in much the same way as a file is identified by a file handle. The
 8003: numerical value of the wid has no (portable) meaning, and might change
 8004: from session to session.
 8005: 
 8006: The ANS Forth ``Search order'' word set is intended to provide a set of
 8007: low-level tools that allow various different schemes to be
 8008: implemented. Gforth also provides @code{vocabulary}, a traditional Forth
 8009: word.  @file{compat/vocabulary.fs} provides an implementation in ANS
 8010: Forth.
 8011: 
 8012: @comment TODO: locals section refers to here, saying that every word list (aka
 8013: @comment vocabulary) has its own methods for searching etc. Need to document that.
 8014: @c anton: but better in a separate subsection on wordlist internals
 8015: 
 8016: @comment TODO: document markers, reveal, tables, mappedwordlist
 8017: 
 8018: @comment the gforthman- prefix is used to pick out the true definition of a
 8019: @comment word from the source files, rather than some alias.
 8020: 
 8021: doc-forth-wordlist
 8022: doc-definitions
 8023: doc-get-current
 8024: doc-set-current
 8025: doc-get-order
 8026: doc---gforthman-set-order
 8027: doc-wordlist
 8028: doc-table
 8029: doc->order
 8030: doc-previous
 8031: doc-also
 8032: doc---gforthman-forth
 8033: doc-only
 8034: doc---gforthman-order
 8035: 
 8036: doc-find
 8037: doc-search-wordlist
 8038: 
 8039: doc-words
 8040: doc-vlist
 8041: @c doc-words-deferred
 8042: 
 8043: @c doc-mappedwordlist @c map-structure undefined, implemantation-specific
 8044: doc-root
 8045: doc-vocabulary
 8046: doc-seal
 8047: doc-vocs
 8048: doc-current
 8049: doc-context
 8050: 
 8051: 
 8052: @menu
 8053: * Vocabularies::                
 8054: * Why use word lists?::         
 8055: * Word list example::           
 8056: @end menu
 8057: 
 8058: @node Vocabularies, Why use word lists?, Word Lists, Word Lists
 8059: @subsection Vocabularies
 8060: @cindex Vocabularies, detailed explanation
 8061: 
 8062: Here is an example of creating and using a new wordlist using ANS
 8063: Forth words:
 8064: 
 8065: @example
 8066: wordlist constant my-new-words-wordlist
 8067: : my-new-words get-order nip my-new-words-wordlist swap set-order ;
 8068: 
 8069: \ add it to the search order
 8070: also my-new-words
 8071: 
 8072: \ alternatively, add it to the search order and make it
 8073: \ the compilation word list
 8074: also my-new-words definitions
 8075: \ type "order" to see the problem
 8076: @end example
 8077: 
 8078: The problem with this example is that @code{order} has no way to
 8079: associate the name @code{my-new-words} with the wid of the word list (in
 8080: Gforth, @code{order} and @code{vocs} will display @code{???}  for a wid
 8081: that has no associated name). There is no Standard way of associating a
 8082: name with a wid.
 8083: 
 8084: In Gforth, this example can be re-coded using @code{vocabulary}, which
 8085: associates a name with a wid:
 8086: 
 8087: @example
 8088: vocabulary my-new-words
 8089: 
 8090: \ add it to the search order
 8091: also my-new-words
 8092: 
 8093: \ alternatively, add it to the search order and make it
 8094: \ the compilation word list
 8095: my-new-words definitions
 8096: \ type "order" to see that the problem is solved
 8097: @end example
 8098: 
 8099: 
 8100: @node Why use word lists?, Word list example, Vocabularies, Word Lists
 8101: @subsection Why use word lists?
 8102: @cindex word lists - why use them?
 8103: 
 8104: Here are some reasons why people use wordlists:
 8105: 
 8106: @itemize @bullet
 8107: 
 8108: @c anton: Gforth's hashing implementation makes the search speed
 8109: @c independent from the number of words.  But it is linear with the number
 8110: @c of wordlists that have to be searched, so in effect using more wordlists
 8111: @c actually slows down compilation.
 8112: 
 8113: @c @item
 8114: @c To improve compilation speed by reducing the number of header space
 8115: @c entries that must be searched. This is achieved by creating a new
 8116: @c word list that contains all of the definitions that are used in the
 8117: @c definition of a Forth system but which would not usually be used by
 8118: @c programs running on that system. That word list would be on the search
 8119: @c list when the Forth system was compiled but would be removed from the
 8120: @c search list for normal operation. This can be a useful technique for
 8121: @c low-performance systems (for example, 8-bit processors in embedded
 8122: @c systems) but is unlikely to be necessary in high-performance desktop
 8123: @c systems.
 8124: 
 8125: @item
 8126: To prevent a set of words from being used outside the context in which
 8127: they are valid. Two classic examples of this are an integrated editor
 8128: (all of the edit commands are defined in a separate word list; the
 8129: search order is set to the editor word list when the editor is invoked;
 8130: the old search order is restored when the editor is terminated) and an
 8131: integrated assembler (the op-codes for the machine are defined in a
 8132: separate word list which is used when a @code{CODE} word is defined).
 8133: 
 8134: @item
 8135: To organize the words of an application or library into a user-visible
 8136: set (in @code{forth-wordlist} or some other common wordlist) and a set
 8137: of helper words used just for the implementation (hidden in a separate
 8138: wordlist).  This keeps @code{words}' output smaller, separates
 8139: implementation and interface, and reduces the chance of name conflicts
 8140: within the common wordlist.
 8141: 
 8142: @item
 8143: To prevent a name-space clash between multiple definitions with the same
 8144: name. For example, when building a cross-compiler you might have a word
 8145: @code{IF} that generates conditional code for your target system. By
 8146: placing this definition in a different word list you can control whether
 8147: the host system's @code{IF} or the target system's @code{IF} get used in
 8148: any particular context by controlling the order of the word lists on the
 8149: search order stack.
 8150: 
 8151: @end itemize
 8152: 
 8153: The downsides of using wordlists are:
 8154: 
 8155: @itemize
 8156: 
 8157: @item
 8158: Debugging becomes more cumbersome.
 8159: 
 8160: @item
 8161: Name conflicts worked around with wordlists are still there, and you
 8162: have to arrange the search order carefully to get the desired results;
 8163: if you forget to do that, you get hard-to-find errors (as in any case
 8164: where you read the code differently from the compiler; @code{see} can
 8165: help seeing which of several possible words the name resolves to in such
 8166: cases).  @code{See} displays just the name of the words, not what
 8167: wordlist they belong to, so it might be misleading.  Using unique names
 8168: is a better approach to avoid name conflicts.
 8169: 
 8170: @item
 8171: You have to explicitly undo any changes to the search order.  In many
 8172: cases it would be more convenient if this happened implicitly.  Gforth
 8173: currently does not provide such a feature, but it may do so in the
 8174: future.
 8175: @end itemize
 8176: 
 8177: 
 8178: @node Word list example,  , Why use word lists?, Word Lists
 8179: @subsection Word list example
 8180: @cindex word lists - example
 8181: 
 8182: The following example is from the
 8183: @uref{http://www.complang.tuwien.ac.at/forth/garbage-collection.zip,
 8184: garbage collector} and uses wordlists to separate public words from
 8185: helper words:
 8186: 
 8187: @example
 8188: get-current ( wid )
 8189: vocabulary garbage-collector also garbage-collector definitions
 8190: ... \ define helper words
 8191: ( wid ) set-current \ restore original (i.e., public) compilation wordlist
 8192: ... \ define the public (i.e., API) words
 8193:     \ they can refer to the helper words
 8194: previous \ restore original search order (helper words become invisible)
 8195: @end example
 8196: 
 8197: @c -------------------------------------------------------------
 8198: @node Environmental Queries, Files, Word Lists, Words
 8199: @section Environmental Queries
 8200: @cindex environmental queries
 8201: 
 8202: ANS Forth introduced the idea of ``environmental queries'' as a way
 8203: for a program running on a system to determine certain characteristics of the system.
 8204: The Standard specifies a number of strings that might be recognised by a system.
 8205: 
 8206: The Standard requires that the header space used for environmental queries
 8207: be distinct from the header space used for definitions.
 8208: 
 8209: Typically, environmental queries are supported by creating a set of
 8210: definitions in a word list that is @i{only} used during environmental
 8211: queries; that is what Gforth does. There is no Standard way of adding
 8212: definitions to the set of recognised environmental queries, but any
 8213: implementation that supports the loading of optional word sets must have
 8214: some mechanism for doing this (after loading the word set, the
 8215: associated environmental query string must return @code{true}). In
 8216: Gforth, the word list used to honour environmental queries can be
 8217: manipulated just like any other word list.
 8218: 
 8219: 
 8220: doc-environment?
 8221: doc-environment-wordlist
 8222: 
 8223: doc-gforth
 8224: doc-os-class
 8225: 
 8226: 
 8227: Note that, whilst the documentation for (e.g.) @code{gforth} shows it
 8228: returning two items on the stack, querying it using @code{environment?}
 8229: will return an additional item; the @code{true} flag that shows that the
 8230: string was recognised.
 8231: 
 8232: @comment TODO Document the standard strings or note where they are documented herein
 8233: 
 8234: Here are some examples of using environmental queries:
 8235: 
 8236: @example
 8237: s" address-unit-bits" environment? 0=
 8238: [IF]
 8239:      cr .( environmental attribute address-units-bits unknown... ) cr
 8240: [ELSE]
 8241:      drop \ ensure balanced stack effect
 8242: [THEN]
 8243: 
 8244: \ this might occur in the prelude of a standard program that uses THROW
 8245: s" exception" environment? [IF]
 8246:    0= [IF]
 8247:       : throw abort" exception thrown" ;
 8248:    [THEN]
 8249: [ELSE] \ we don't know, so make sure
 8250:    : throw abort" exception thrown" ;
 8251: [THEN]
 8252: 
 8253: s" gforth" environment? [IF] .( Gforth version ) TYPE
 8254:                         [ELSE] .( Not Gforth..) [THEN]
 8255: 
 8256: \ a program using v*
 8257: s" gforth" environment? [IF]
 8258:   s" 0.5.0" compare 0< [IF] \ v* is a primitive since 0.5.0
 8259:    : v* ( f_addr1 nstride1 f_addr2 nstride2 ucount -- r )
 8260:      >r swap 2swap swap 0e r> 0 ?DO
 8261:        dup f@ over + 2swap dup f@ f* f+ over + 2swap
 8262:      LOOP
 8263:      2drop 2drop ; 
 8264:   [THEN]
 8265: [ELSE] \ 
 8266:   : v* ( f_addr1 nstride1 f_addr2 nstride2 ucount -- r )
 8267:   ...
 8268: [THEN]
 8269: @end example
 8270: 
 8271: Here is an example of adding a definition to the environment word list:
 8272: 
 8273: @example
 8274: get-current environment-wordlist set-current
 8275: true constant block
 8276: true constant block-ext
 8277: set-current
 8278: @end example
 8279: 
 8280: You can see what definitions are in the environment word list like this:
 8281: 
 8282: @example
 8283: environment-wordlist >order words previous
 8284: @end example
 8285: 
 8286: 
 8287: @c -------------------------------------------------------------
 8288: @node Files, Blocks, Environmental Queries, Words
 8289: @section Files
 8290: @cindex files
 8291: @cindex I/O - file-handling
 8292: 
 8293: Gforth provides facilities for accessing files that are stored in the
 8294: host operating system's file-system. Files that are processed by Gforth
 8295: can be divided into two categories:
 8296: 
 8297: @itemize @bullet
 8298: @item
 8299: Files that are processed by the Text Interpreter (@dfn{Forth source files}).
 8300: @item
 8301: Files that are processed by some other program (@dfn{general files}).
 8302: @end itemize
 8303: 
 8304: @menu
 8305: * Forth source files::          
 8306: * General files::               
 8307: * Redirection::                 
 8308: * Search Paths::                
 8309: @end menu
 8310: 
 8311: @c -------------------------------------------------------------
 8312: @node Forth source files, General files, Files, Files
 8313: @subsection Forth source files
 8314: @cindex including files
 8315: @cindex Forth source files
 8316: 
 8317: The simplest way to interpret the contents of a file is to use one of
 8318: these two formats:
 8319: 
 8320: @example
 8321: include mysource.fs
 8322: s" mysource.fs" included
 8323: @end example
 8324: 
 8325: You usually want to include a file only if it is not included already
 8326: (by, say, another source file). In that case, you can use one of these
 8327: three formats:
 8328: 
 8329: @example
 8330: require mysource.fs
 8331: needs mysource.fs
 8332: s" mysource.fs" required
 8333: @end example
 8334: 
 8335: @cindex stack effect of included files
 8336: @cindex including files, stack effect
 8337: It is good practice to write your source files such that interpreting them
 8338: does not change the stack. Source files designed in this way can be used with
 8339: @code{required} and friends without complications. For example:
 8340: 
 8341: @example
 8342: 1024 require foo.fs drop
 8343: @end example
 8344: 
 8345: Here you want to pass the argument 1024 (e.g., a buffer size) to
 8346: @file{foo.fs}.  Interpreting @file{foo.fs} has the stack effect ( n -- n
 8347: ), which allows its use with @code{require}.  Of course with such
 8348: parameters to required files, you have to ensure that the first
 8349: @code{require} fits for all uses (i.e., @code{require} it early in the
 8350: master load file).
 8351: 
 8352: doc-include-file
 8353: doc-included
 8354: doc-included?
 8355: doc-include
 8356: doc-required
 8357: doc-require
 8358: doc-needs
 8359: @c doc-init-included-files @c internal
 8360: doc-sourcefilename
 8361: doc-sourceline#
 8362: 
 8363: A definition in ANS Forth for @code{required} is provided in
 8364: @file{compat/required.fs}.
 8365: 
 8366: @c -------------------------------------------------------------
 8367: @node General files, Redirection, Forth source files, Files
 8368: @subsection General files
 8369: @cindex general files
 8370: @cindex file-handling
 8371: 
 8372: Files are opened/created by name and type. The following file access
 8373: methods (FAMs) are recognised:
 8374: 
 8375: @cindex fam (file access method)
 8376: doc-r/o
 8377: doc-r/w
 8378: doc-w/o
 8379: doc-bin
 8380: 
 8381: 
 8382: When a file is opened/created, it returns a file identifier,
 8383: @i{wfileid} that is used for all other file commands. All file
 8384: commands also return a status value, @i{wior}, that is 0 for a
 8385: successful operation and an implementation-defined non-zero value in the
 8386: case of an error.
 8387: 
 8388: 
 8389: doc-open-file
 8390: doc-create-file
 8391: 
 8392: doc-close-file
 8393: doc-delete-file
 8394: doc-rename-file
 8395: doc-read-file
 8396: doc-read-line
 8397: doc-key-file
 8398: doc-key?-file
 8399: doc-write-file
 8400: doc-write-line
 8401: doc-emit-file
 8402: doc-flush-file
 8403: 
 8404: doc-file-status
 8405: doc-file-position
 8406: doc-reposition-file
 8407: doc-file-size
 8408: doc-resize-file
 8409: 
 8410: doc-slurp-file
 8411: doc-slurp-fid
 8412: doc-stdin
 8413: doc-stdout
 8414: doc-stderr
 8415: 
 8416: @c ---------------------------------------------------------
 8417: @node Redirection, Search Paths, General files, Files
 8418: @subsection Redirection
 8419: @cindex Redirection
 8420: @cindex Input Redirection
 8421: @cindex Output Redirection
 8422: 
 8423: You can redirect the output of @code{type} and @code{emit} and all the
 8424: words that use them (all output words that don't have an explicit
 8425: target file) to an arbitrary file with the @code{outfile-execute},
 8426: used like this:
 8427: 
 8428: @example
 8429: : some-warning ( n -- )
 8430:     cr ." warning# " . ;
 8431: 
 8432: : print-some-warning ( n -- )
 8433:     ['] some-warning stderr outfile-execute ;
 8434: @end example
 8435: 
 8436: After @code{some-warning} is executed, the original output direction
 8437: is restored; this construct is safe against exceptions.  Similarly,
 8438: there is @code{infile-execute} for redirecting the input of @code{key}
 8439: and its users (any input word that does not take a file explicitly).
 8440: 
 8441: doc-outfile-execute
 8442: doc-infile-execute
 8443: 
 8444: If you do not want to redirect the input or output to a file, you can
 8445: also make use of the fact that @code{key}, @code{emit} and @code{type}
 8446: are deferred words (@pxref{Deferred Words}).  However, in that case
 8447: you have to worry about the restoration and the protection against
 8448: exceptions yourself; also, note that for redirecting the output in
 8449: this way, you have to redirect both @code{emit} and @code{type}.
 8450: 
 8451: @c ---------------------------------------------------------
 8452: @node Search Paths,  , Redirection, Files
 8453: @subsection Search Paths
 8454: @cindex path for @code{included}
 8455: @cindex file search path
 8456: @cindex @code{include} search path
 8457: @cindex search path for files
 8458: 
 8459: If you specify an absolute filename (i.e., a filename starting with
 8460: @file{/} or @file{~}, or with @file{:} in the second position (as in
 8461: @samp{C:...})) for @code{included} and friends, that file is included
 8462: just as you would expect.
 8463: 
 8464: If the filename starts with @file{./}, this refers to the directory that
 8465: the present file was @code{included} from.  This allows files to include
 8466: other files relative to their own position (irrespective of the current
 8467: working directory or the absolute position).  This feature is essential
 8468: for libraries consisting of several files, where a file may include
 8469: other files from the library.  It corresponds to @code{#include "..."}
 8470: in C. If the current input source is not a file, @file{.} refers to the
 8471: directory of the innermost file being included, or, if there is no file
 8472: being included, to the current working directory.
 8473: 
 8474: For relative filenames (not starting with @file{./}), Gforth uses a
 8475: search path similar to Forth's search order (@pxref{Word Lists}). It
 8476: tries to find the given filename in the directories present in the path,
 8477: and includes the first one it finds. There are separate search paths for
 8478: Forth source files and general files.  If the search path contains the
 8479: directory @file{.}, this refers to the directory of the current file, or
 8480: the working directory, as if the file had been specified with @file{./}.
 8481: 
 8482: Use @file{~+} to refer to the current working directory (as in the
 8483: @code{bash}).
 8484: 
 8485: @c anton: fold the following subsubsections into this subsection?
 8486: 
 8487: @menu
 8488: * Source Search Paths::         
 8489: * General Search Paths::        
 8490: @end menu
 8491: 
 8492: @c ---------------------------------------------------------
 8493: @node Source Search Paths, General Search Paths, Search Paths, Search Paths
 8494: @subsubsection Source Search Paths
 8495: @cindex search path control, source files
 8496: 
 8497: The search path is initialized when you start Gforth (@pxref{Invoking
 8498: Gforth}). You can display it and change it using @code{fpath} in
 8499: combination with the general path handling words.
 8500: 
 8501: doc-fpath
 8502: @c the functionality of the following words is easily available through
 8503: @c   fpath and the general path words.  The may go away.
 8504: @c doc-.fpath
 8505: @c doc-fpath+
 8506: @c doc-fpath=
 8507: @c doc-open-fpath-file
 8508: 
 8509: @noindent
 8510: Here is an example of using @code{fpath} and @code{require}:
 8511: 
 8512: @example
 8513: fpath path= /usr/lib/forth/|./
 8514: require timer.fs
 8515: @end example
 8516: 
 8517: 
 8518: @c ---------------------------------------------------------
 8519: @node General Search Paths,  , Source Search Paths, Search Paths
 8520: @subsubsection General Search Paths
 8521: @cindex search path control, source files
 8522: 
 8523: Your application may need to search files in several directories, like
 8524: @code{included} does. To facilitate this, Gforth allows you to define
 8525: and use your own search paths, by providing generic equivalents of the
 8526: Forth search path words:
 8527: 
 8528: doc-open-path-file
 8529: doc-path-allot
 8530: doc-clear-path
 8531: doc-also-path
 8532: doc-.path
 8533: doc-path+
 8534: doc-path=
 8535: 
 8536: @c anton: better define a word for it, say "path-allot ( ucount -- path-addr )
 8537: 
 8538: Here's an example of creating an empty search path:
 8539: @c
 8540: @example
 8541: create mypath 500 path-allot \ maximum length 500 chars (is checked)
 8542: @end example
 8543: 
 8544: @c -------------------------------------------------------------
 8545: @node Blocks, Other I/O, Files, Words
 8546: @section Blocks
 8547: @cindex I/O - blocks
 8548: @cindex blocks
 8549: 
 8550: When you run Gforth on a modern desk-top computer, it runs under the
 8551: control of an operating system which provides certain services.  One of
 8552: these services is @var{file services}, which allows Forth source code
 8553: and data to be stored in files and read into Gforth (@pxref{Files}).
 8554: 
 8555: Traditionally, Forth has been an important programming language on
 8556: systems where it has interfaced directly to the underlying hardware with
 8557: no intervening operating system. Forth provides a mechanism, called
 8558: @dfn{blocks}, for accessing mass storage on such systems.
 8559: 
 8560: A block is a 1024-byte data area, which can be used to hold data or
 8561: Forth source code. No structure is imposed on the contents of the
 8562: block. A block is identified by its number; blocks are numbered
 8563: contiguously from 1 to an implementation-defined maximum.
 8564: 
 8565: A typical system that used blocks but no operating system might use a
 8566: single floppy-disk drive for mass storage, with the disks formatted to
 8567: provide 256-byte sectors. Blocks would be implemented by assigning the
 8568: first four sectors of the disk to block 1, the second four sectors to
 8569: block 2 and so on, up to the limit of the capacity of the disk. The disk
 8570: would not contain any file system information, just the set of blocks.
 8571: 
 8572: @cindex blocks file
 8573: On systems that do provide file services, blocks are typically
 8574: implemented by storing a sequence of blocks within a single @dfn{blocks
 8575: file}.  The size of the blocks file will be an exact multiple of 1024
 8576: bytes, corresponding to the number of blocks it contains. This is the
 8577: mechanism that Gforth uses.
 8578: 
 8579: @cindex @file{blocks.fb}
 8580: Only one blocks file can be open at a time. If you use block words without
 8581: having specified a blocks file, Gforth defaults to the blocks file
 8582: @file{blocks.fb}. Gforth uses the Forth search path when attempting to
 8583: locate a blocks file (@pxref{Source Search Paths}).
 8584: 
 8585: @cindex block buffers
 8586: When you read and write blocks under program control, Gforth uses a
 8587: number of @dfn{block buffers} as intermediate storage. These buffers are
 8588: not used when you use @code{load} to interpret the contents of a block.
 8589: 
 8590: The behaviour of the block buffers is analagous to that of a cache.
 8591: Each block buffer has three states:
 8592: 
 8593: @itemize @bullet
 8594: @item
 8595: Unassigned
 8596: @item
 8597: Assigned-clean
 8598: @item
 8599: Assigned-dirty
 8600: @end itemize
 8601: 
 8602: Initially, all block buffers are @i{unassigned}. In order to access a
 8603: block, the block (specified by its block number) must be assigned to a
 8604: block buffer.
 8605: 
 8606: The assignment of a block to a block buffer is performed by @code{block}
 8607: or @code{buffer}. Use @code{block} when you wish to modify the existing
 8608: contents of a block. Use @code{buffer} when you don't care about the
 8609: existing contents of the block@footnote{The ANS Forth definition of
 8610: @code{buffer} is intended not to cause disk I/O; if the data associated
 8611: with the particular block is already stored in a block buffer due to an
 8612: earlier @code{block} command, @code{buffer} will return that block
 8613: buffer and the existing contents of the block will be
 8614: available. Otherwise, @code{buffer} will simply assign a new, empty
 8615: block buffer for the block.}.
 8616: 
 8617: Once a block has been assigned to a block buffer using @code{block} or
 8618: @code{buffer}, that block buffer becomes the @i{current block
 8619: buffer}. Data may only be manipulated (read or written) within the
 8620: current block buffer.
 8621: 
 8622: When the contents of the current block buffer has been modified it is
 8623: necessary, @emph{before calling @code{block} or @code{buffer} again}, to
 8624: either abandon the changes (by doing nothing) or mark the block as
 8625: changed (assigned-dirty), using @code{update}. Using @code{update} does
 8626: not change the blocks file; it simply changes a block buffer's state to
 8627: @i{assigned-dirty}.  The block will be written implicitly when it's
 8628: buffer is needed for another block, or explicitly by @code{flush} or
 8629: @code{save-buffers}.
 8630: 
 8631: word @code{Flush} writes all @i{assigned-dirty} blocks back to the
 8632: blocks file on disk. Leaving Gforth with @code{bye} also performs a
 8633: @code{flush}.
 8634: 
 8635: In Gforth, @code{block} and @code{buffer} use a @i{direct-mapped}
 8636: algorithm to assign a block buffer to a block. That means that any
 8637: particular block can only be assigned to one specific block buffer,
 8638: called (for the particular operation) the @i{victim buffer}. If the
 8639: victim buffer is @i{unassigned} or @i{assigned-clean} it is allocated to
 8640: the new block immediately. If it is @i{assigned-dirty} its current
 8641: contents are written back to the blocks file on disk before it is
 8642: allocated to the new block.
 8643: 
 8644: Although no structure is imposed on the contents of a block, it is
 8645: traditional to display the contents as 16 lines each of 64 characters.  A
 8646: block provides a single, continuous stream of input (for example, it
 8647: acts as a single parse area) -- there are no end-of-line characters
 8648: within a block, and no end-of-file character at the end of a
 8649: block. There are two consequences of this:
 8650: 
 8651: @itemize @bullet
 8652: @item
 8653: The last character of one line wraps straight into the first character
 8654: of the following line
 8655: @item
 8656: The word @code{\} -- comment to end of line -- requires special
 8657: treatment; in the context of a block it causes all characters until the
 8658: end of the current 64-character ``line'' to be ignored.
 8659: @end itemize
 8660: 
 8661: In Gforth, when you use @code{block} with a non-existent block number,
 8662: the current blocks file will be extended to the appropriate size and the
 8663: block buffer will be initialised with spaces.
 8664: 
 8665: Gforth includes a simple block editor (type @code{use blocked.fb 0 list}
 8666: for details) but doesn't encourage the use of blocks; the mechanism is
 8667: only provided for backward compatibility -- ANS Forth requires blocks to
 8668: be available when files are.
 8669: 
 8670: Common techniques that are used when working with blocks include:
 8671: 
 8672: @itemize @bullet
 8673: @item
 8674: A screen editor that allows you to edit blocks without leaving the Forth
 8675: environment.
 8676: @item
 8677: Shadow screens; where every code block has an associated block
 8678: containing comments (for example: code in odd block numbers, comments in
 8679: even block numbers). Typically, the block editor provides a convenient
 8680: mechanism to toggle between code and comments.
 8681: @item
 8682: Load blocks; a single block (typically block 1) contains a number of
 8683: @code{thru} commands which @code{load} the whole of the application.
 8684: @end itemize
 8685: 
 8686: See Frank Sergeant's Pygmy Forth to see just how well blocks can be
 8687: integrated into a Forth programming environment.
 8688: 
 8689: @comment TODO what about errors on open-blocks?
 8690: 
 8691: doc-open-blocks
 8692: doc-use
 8693: doc-block-offset
 8694: doc-get-block-fid
 8695: doc-block-position
 8696: 
 8697: doc-list
 8698: doc-scr
 8699: 
 8700: doc-block
 8701: doc-buffer
 8702: 
 8703: doc-empty-buffers
 8704: doc-empty-buffer
 8705: doc-update
 8706: doc-updated?
 8707: doc-save-buffers
 8708: doc-save-buffer
 8709: doc-flush
 8710: 
 8711: doc-load
 8712: doc-thru
 8713: doc-+load
 8714: doc-+thru
 8715: doc---gforthman--->
 8716: doc-block-included
 8717: 
 8718: 
 8719: @c -------------------------------------------------------------
 8720: @node Other I/O, OS command line arguments, Blocks, Words
 8721: @section Other I/O
 8722: @cindex I/O - keyboard and display
 8723: 
 8724: @menu
 8725: * Simple numeric output::       Predefined formats
 8726: * Formatted numeric output::    Formatted (pictured) output
 8727: * String Formats::              How Forth stores strings in memory
 8728: * Displaying characters and strings::  Other stuff
 8729: * Terminal output::             Cursor positioning etc.
 8730: * Single-key input::            
 8731: * Line input and conversion::   
 8732: * Pipes::                       How to create your own pipes
 8733: * Xchars and Unicode::          Non-ASCII characters
 8734: @end menu
 8735: 
 8736: @node Simple numeric output, Formatted numeric output, Other I/O, Other I/O
 8737: @subsection Simple numeric output
 8738: @cindex numeric output - simple/free-format
 8739: 
 8740: The simplest output functions are those that display numbers from the
 8741: data or floating-point stacks. Floating-point output is always displayed
 8742: using base 10. Numbers displayed from the data stack use the value stored
 8743: in @code{base}.
 8744: 
 8745: 
 8746: doc-.
 8747: doc-dec.
 8748: doc-hex.
 8749: doc-u.
 8750: doc-.r
 8751: doc-u.r
 8752: doc-d.
 8753: doc-ud.
 8754: doc-d.r
 8755: doc-ud.r
 8756: doc-f.
 8757: doc-fe.
 8758: doc-fs.
 8759: doc-f.rdp
 8760: 
 8761: Examples of printing the number 1234.5678E23 in the different floating-point output
 8762: formats are shown below:
 8763: 
 8764: @example
 8765: f. 123456779999999000000000000.
 8766: fe. 123.456779999999E24
 8767: fs. 1.23456779999999E26
 8768: @end example
 8769: 
 8770: 
 8771: @node Formatted numeric output, String Formats, Simple numeric output, Other I/O
 8772: @subsection Formatted numeric output
 8773: @cindex formatted numeric output
 8774: @cindex pictured numeric output
 8775: @cindex numeric output - formatted
 8776: 
 8777: Forth traditionally uses a technique called @dfn{pictured numeric
 8778: output} for formatted printing of integers.  In this technique, digits
 8779: are extracted from the number (using the current output radix defined by
 8780: @code{base}), converted to ASCII codes and appended to a string that is
 8781: built in a scratch-pad area of memory (@pxref{core-idef,
 8782: Implementation-defined options, Implementation-defined
 8783: options}). Arbitrary characters can be appended to the string during the
 8784: extraction process. The completed string is specified by an address
 8785: and length and can be manipulated (@code{TYPE}ed, copied, modified)
 8786: under program control.
 8787: 
 8788: All of the integer output words described in the previous section
 8789: (@pxref{Simple numeric output}) are implemented in Gforth using pictured
 8790: numeric output.
 8791: 
 8792: Three important things to remember about pictured numeric output:
 8793: 
 8794: @itemize @bullet
 8795: @item
 8796: It always operates on double-precision numbers; to display a
 8797: single-precision number, convert it first (for ways of doing this
 8798: @pxref{Double precision}).
 8799: @item
 8800: It always treats the double-precision number as though it were
 8801: unsigned. The examples below show ways of printing signed numbers.
 8802: @item
 8803: The string is built up from right to left; least significant digit first.
 8804: @end itemize
 8805: 
 8806: 
 8807: doc-<#
 8808: doc-<<#
 8809: doc-#
 8810: doc-#s
 8811: doc-hold
 8812: doc-sign
 8813: doc-#>
 8814: doc-#>>
 8815: 
 8816: doc-represent
 8817: doc-f>str-rdp
 8818: doc-f>buf-rdp
 8819: 
 8820: 
 8821: @noindent
 8822: Here are some examples of using pictured numeric output:
 8823: 
 8824: @example
 8825: : my-u. ( u -- )
 8826:   \ Simplest use of pns.. behaves like Standard u. 
 8827:   0              \ convert to unsigned double
 8828:   <<#            \ start conversion
 8829:   #s             \ convert all digits
 8830:   #>             \ complete conversion
 8831:   TYPE SPACE     \ display, with trailing space
 8832:   #>> ;          \ release hold area
 8833: 
 8834: : cents-only ( u -- )
 8835:   0              \ convert to unsigned double
 8836:   <<#            \ start conversion
 8837:   # #            \ convert two least-significant digits
 8838:   #>             \ complete conversion, discard other digits
 8839:   TYPE SPACE     \ display, with trailing space
 8840:   #>> ;          \ release hold area
 8841: 
 8842: : dollars-and-cents ( u -- )
 8843:   0              \ convert to unsigned double
 8844:   <<#            \ start conversion
 8845:   # #            \ convert two least-significant digits
 8846:   [char] . hold  \ insert decimal point
 8847:   #s             \ convert remaining digits
 8848:   [char] $ hold  \ append currency symbol
 8849:   #>             \ complete conversion
 8850:   TYPE SPACE     \ display, with trailing space
 8851:   #>> ;          \ release hold area
 8852: 
 8853: : my-. ( n -- )
 8854:   \ handling negatives.. behaves like Standard .
 8855:   s>d            \ convert to signed double
 8856:   swap over dabs \ leave sign byte followed by unsigned double
 8857:   <<#            \ start conversion
 8858:   #s             \ convert all digits
 8859:   rot sign       \ get at sign byte, append "-" if needed
 8860:   #>             \ complete conversion
 8861:   TYPE SPACE     \ display, with trailing space
 8862:   #>> ;          \ release hold area
 8863: 
 8864: : account. ( n -- )
 8865:   \ accountants don't like minus signs, they use parentheses
 8866:   \ for negative numbers
 8867:   s>d            \ convert to signed double
 8868:   swap over dabs \ leave sign byte followed by unsigned double
 8869:   <<#            \ start conversion
 8870:   2 pick         \ get copy of sign byte
 8871:   0< IF [char] ) hold THEN \ right-most character of output
 8872:   #s             \ convert all digits
 8873:   rot            \ get at sign byte
 8874:   0< IF [char] ( hold THEN
 8875:   #>             \ complete conversion
 8876:   TYPE SPACE     \ display, with trailing space
 8877:   #>> ;          \ release hold area
 8878: 
 8879: @end example
 8880: 
 8881: Here are some examples of using these words:
 8882: 
 8883: @example
 8884: 1 my-u. 1
 8885: hex -1 my-u. decimal FFFFFFFF
 8886: 1 cents-only 01
 8887: 1234 cents-only 34
 8888: 2 dollars-and-cents $0.02
 8889: 1234 dollars-and-cents $12.34
 8890: 123 my-. 123
 8891: -123 my. -123
 8892: 123 account. 123
 8893: -456 account. (456)
 8894: @end example
 8895: 
 8896: 
 8897: @node String Formats, Displaying characters and strings, Formatted numeric output, Other I/O
 8898: @subsection String Formats
 8899: @cindex strings - see character strings
 8900: @cindex character strings - formats
 8901: @cindex I/O - see character strings
 8902: @cindex counted strings
 8903: 
 8904: @c anton: this does not really belong here; maybe the memory section,
 8905: @c  or the principles chapter
 8906: 
 8907: Forth commonly uses two different methods for representing character
 8908: strings:
 8909: 
 8910: @itemize @bullet
 8911: @item
 8912: @cindex address of counted string
 8913: @cindex counted string
 8914: As a @dfn{counted string}, represented by a @i{c-addr}. The char
 8915: addressed by @i{c-addr} contains a character-count, @i{n}, of the
 8916: string and the string occupies the subsequent @i{n} char addresses in
 8917: memory.
 8918: @item
 8919: As cell pair on the stack; @i{c-addr u}, where @i{u} is the length
 8920: of the string in characters, and @i{c-addr} is the address of the
 8921: first byte of the string.
 8922: @end itemize
 8923: 
 8924: ANS Forth encourages the use of the second format when representing
 8925: strings.
 8926: 
 8927: 
 8928: doc-count
 8929: 
 8930: 
 8931: For words that move, copy and search for strings see @ref{Memory
 8932: Blocks}. For words that display characters and strings see
 8933: @ref{Displaying characters and strings}.
 8934: 
 8935: @node Displaying characters and strings, Terminal output, String Formats, Other I/O
 8936: @subsection Displaying characters and strings
 8937: @cindex characters - compiling and displaying
 8938: @cindex character strings - compiling and displaying
 8939: 
 8940: This section starts with a glossary of Forth words and ends with a set
 8941: of examples.
 8942: 
 8943: doc-bl
 8944: doc-space
 8945: doc-spaces
 8946: doc-emit
 8947: doc-toupper
 8948: doc-."
 8949: doc-.(
 8950: doc-.\"
 8951: doc-type
 8952: doc-typewhite
 8953: doc-cr
 8954: @cindex cursor control
 8955: doc-s"
 8956: doc-s\"
 8957: doc-c"
 8958: doc-char
 8959: doc-[char]
 8960: 
 8961: 
 8962: @noindent
 8963: As an example, consider the following text, stored in a file @file{test.fs}:
 8964: 
 8965: @example
 8966: .( text-1)
 8967: : my-word
 8968:   ." text-2" cr
 8969:   .( text-3)
 8970: ;
 8971: 
 8972: ." text-4"
 8973: 
 8974: : my-char
 8975:   [char] ALPHABET emit
 8976:   char emit
 8977: ;
 8978: @end example
 8979: 
 8980: When you load this code into Gforth, the following output is generated:
 8981: 
 8982: @example
 8983: @kbd{include test.fs @key{RET}} text-1text-3text-4 ok
 8984: @end example
 8985: 
 8986: @itemize @bullet
 8987: @item
 8988: Messages @code{text-1} and @code{text-3} are displayed because @code{.(} 
 8989: is an immediate word; it behaves in the same way whether it is used inside
 8990: or outside a colon definition.
 8991: @item
 8992: Message @code{text-4} is displayed because of Gforth's added interpretation
 8993: semantics for @code{."}.
 8994: @item
 8995: Message @code{text-2} is @i{not} displayed, because the text interpreter
 8996: performs the compilation semantics for @code{."} within the definition of
 8997: @code{my-word}.
 8998: @end itemize
 8999: 
 9000: Here are some examples of executing @code{my-word} and @code{my-char}:
 9001: 
 9002: @example
 9003: @kbd{my-word @key{RET}} text-2
 9004:  ok
 9005: @kbd{my-char fred @key{RET}} Af ok
 9006: @kbd{my-char jim @key{RET}} Aj ok
 9007: @end example
 9008: 
 9009: @itemize @bullet
 9010: @item
 9011: Message @code{text-2} is displayed because of the run-time behaviour of
 9012: @code{."}.
 9013: @item
 9014: @code{[char]} compiles the ``A'' from ``ALPHABET'' and puts its display code
 9015: on the stack at run-time. @code{emit} always displays the character
 9016: when @code{my-char} is executed.
 9017: @item
 9018: @code{char} parses a string at run-time and the second @code{emit} displays
 9019: the first character of the string.
 9020: @item
 9021: If you type @code{see my-char} you can see that @code{[char]} discarded
 9022: the text ``LPHABET'' and only compiled the display code for ``A'' into the
 9023: definition of @code{my-char}.
 9024: @end itemize
 9025: 
 9026: 
 9027: @node Terminal output, Single-key input, Displaying characters and strings, Other I/O
 9028: @subsection Terminal output
 9029: @cindex output to terminal
 9030: @cindex terminal output
 9031: 
 9032: If you are outputting to a terminal, you may want to control the
 9033: positioning of the cursor:
 9034: @cindex cursor positioning
 9035: 
 9036: doc-at-xy
 9037: 
 9038: In order to know where to position the cursor, it is often helpful to
 9039: know the size of the screen:
 9040: @cindex terminal size 
 9041: 
 9042: doc-form
 9043: 
 9044: And sometimes you want to use:
 9045: @cindex clear screen
 9046: 
 9047: doc-page
 9048: 
 9049: Note that on non-terminals you should use @code{12 emit}, not
 9050: @code{page}, to get a form feed.
 9051: 
 9052: 
 9053: @node Single-key input, Line input and conversion, Terminal output, Other I/O
 9054: @subsection Single-key input
 9055: @cindex single-key input
 9056: @cindex input, single-key
 9057: 
 9058: If you want to get a single printable character, you can use
 9059: @code{key}; to check whether a character is available for @code{key},
 9060: you can use @code{key?}.
 9061: 
 9062: doc-key
 9063: doc-key?
 9064: 
 9065: If you want to process a mix of printable and non-printable
 9066: characters, you can do that with @code{ekey} and friends.  @code{Ekey}
 9067: produces a keyboard event that you have to convert into a character
 9068: with @code{ekey>char} or into a key identifier with @code{ekey>fkey}.
 9069: 
 9070: Typical code for using EKEY looks like this:
 9071: 
 9072: @example
 9073: ekey ekey>char if ( c )
 9074:   ... \ do something with the character
 9075: else ekey>fkey if ( key-id )
 9076:   case
 9077:     k-up                                  of ... endof
 9078:     k-f1                                  of ... endof
 9079:     k-left k-shift-mask or k-ctrl-mask or of ... endof
 9080:     ...
 9081:   endcase
 9082: else ( keyboard-event )
 9083:   drop \ just ignore an unknown keyboard event type
 9084: then then
 9085: @end example
 9086: 
 9087: doc-ekey
 9088: doc-ekey>char
 9089: doc-ekey>fkey
 9090: doc-ekey?
 9091: 
 9092: The key identifiers for cursor keys are:
 9093: 
 9094: doc-k-left
 9095: doc-k-right
 9096: doc-k-up	
 9097: doc-k-down	
 9098: doc-k-home	
 9099: doc-k-end	
 9100: doc-k-prior
 9101: doc-k-next
 9102: doc-k-insert
 9103: doc-k-delete
 9104: 
 9105: The key identifiers for function keys (aka keypad keys) are:
 9106: 
 9107: doc-k-f1
 9108: doc-k-f2
 9109: doc-k-f3
 9110: doc-k-f4
 9111: doc-k-f5
 9112: doc-k-f6
 9113: doc-k-f7
 9114: doc-k-f8
 9115: doc-k-f9
 9116: doc-k-f10
 9117: doc-k-f11
 9118: doc-k-f12
 9119: 
 9120: Note that @code{k-f11} and @code{k-f12} are not as widely available.
 9121: 
 9122: You can combine these key identifiers with masks for various shift keys:
 9123: 
 9124: doc-k-shift-mask
 9125: doc-k-ctrl-mask
 9126: doc-k-alt-mask
 9127: 
 9128: Note that, even if a Forth system has @code{ekey>fkey} and the key
 9129: identifier words, the keys are not necessarily available or it may not
 9130: necessarily be able to report all the keys and all the possible
 9131: combinations with shift masks.  Therefore, write your programs in such
 9132: a way that they are still useful even if the keys and key combinations
 9133: cannot be pressed or are not recognized.
 9134: 
 9135: Examples: Older keyboards often do not have an F11 and F12 key.  If
 9136: you run Gforth in an xterm, the xterm catches a number of combinations
 9137: (e.g., @key{Shift-Up}), and never passes it to Gforth.  Finally,
 9138: Gforth currently does not recognize and report combinations with
 9139: multiple shift keys (so the @key{shift-ctrl-left} case in the example
 9140: above would never be entered).
 9141: 
 9142: Gforth recognizes various keys available on ANSI terminals (in MS-DOS
 9143: you need the ANSI.SYS driver to get that behaviour); it works by
 9144: recognizing the escape sequences that ANSI terminals send when such a
 9145: key is pressed.  If you have a terminal that sends other escape
 9146: sequences, you will not get useful results on Gforth.  Other Forth
 9147: systems may work in a different way.
 9148: 
 9149: 
 9150: @node  Line input and conversion, Pipes, Single-key input, Other I/O
 9151: @subsection Line input and conversion
 9152: @cindex line input from terminal
 9153: @cindex input, linewise from terminal
 9154: @cindex convertin strings to numbers
 9155: @cindex I/O - see input
 9156: 
 9157: For ways of storing character strings in memory see @ref{String Formats}.
 9158: 
 9159: @comment TODO examples for >number >float accept key key? pad parse word refill
 9160: @comment then index them
 9161: 
 9162: Words for inputting one line from the keyboard:
 9163: 
 9164: doc-accept
 9165: doc-edit-line
 9166: 
 9167: Conversion words:
 9168: 
 9169: doc-s>number?
 9170: doc-s>unumber?
 9171: doc->number
 9172: doc->float
 9173: 
 9174: 
 9175: @comment obsolescent words..
 9176: Obsolescent input and conversion words:
 9177: 
 9178: doc-convert
 9179: doc-expect
 9180: doc-span
 9181: 
 9182: 
 9183: @node Pipes, Xchars and Unicode, Line input and conversion, Other I/O
 9184: @subsection Pipes
 9185: @cindex pipes, creating your own
 9186: 
 9187: In addition to using Gforth in pipes created by other processes
 9188: (@pxref{Gforth in pipes}), you can create your own pipe with
 9189: @code{open-pipe}, and read from or write to it.
 9190: 
 9191: doc-open-pipe
 9192: doc-close-pipe
 9193: 
 9194: If you write to a pipe, Gforth can throw a @code{broken-pipe-error}; if
 9195: you don't catch this exception, Gforth will catch it and exit, usually
 9196: silently (@pxref{Gforth in pipes}).  Since you probably do not want
 9197: this, you should wrap a @code{catch} or @code{try} block around the code
 9198: from @code{open-pipe} to @code{close-pipe}, so you can deal with the
 9199: problem yourself, and then return to regular processing.
 9200: 
 9201: doc-broken-pipe-error
 9202: 
 9203: @node Xchars and Unicode,  , Pipes, Other I/O
 9204: @subsection Xchars and Unicode
 9205: 
 9206: This chapter needs completion
 9207: 
 9208: @node OS command line arguments, Locals, Other I/O, Words
 9209: @section OS command line arguments
 9210: @cindex OS command line arguments
 9211: @cindex command line arguments, OS
 9212: @cindex arguments, OS command line
 9213: 
 9214: The usual way to pass arguments to Gforth programs on the command line
 9215: is via the @option{-e} option, e.g.
 9216: 
 9217: @example
 9218: gforth -e "123 456" foo.fs -e bye
 9219: @end example
 9220: 
 9221: However, you may want to interpret the command-line arguments directly.
 9222: In that case, you can access the (image-specific) command-line arguments
 9223: through @code{next-arg}:
 9224: 
 9225: doc-next-arg
 9226: 
 9227: Here's an example program @file{echo.fs} for @code{next-arg}:
 9228: 
 9229: @example
 9230: : echo ( -- )
 9231:     begin
 9232: 	next-arg 2dup 0 0 d<> while
 9233: 	    type space
 9234:     repeat
 9235:     2drop ;
 9236: 
 9237: echo cr bye
 9238: @end example
 9239: 
 9240: This can be invoked with
 9241: 
 9242: @example
 9243: gforth echo.fs hello world
 9244: @end example
 9245: 
 9246: and it will print
 9247: 
 9248: @example
 9249: hello world
 9250: @end example
 9251: 
 9252: The next lower level of dealing with the OS command line are the
 9253: following words:
 9254: 
 9255: doc-arg
 9256: doc-shift-args
 9257: 
 9258: Finally, at the lowest level Gforth provides the following words:
 9259: 
 9260: doc-argc
 9261: doc-argv
 9262: 
 9263: @c -------------------------------------------------------------
 9264: @node Locals, Structures, OS command line arguments, Words
 9265: @section Locals
 9266: @cindex locals
 9267: 
 9268: Local variables can make Forth programming more enjoyable and Forth
 9269: programs easier to read. Unfortunately, the locals of ANS Forth are
 9270: laden with restrictions. Therefore, we provide not only the ANS Forth
 9271: locals wordset, but also our own, more powerful locals wordset (we
 9272: implemented the ANS Forth locals wordset through our locals wordset).
 9273: 
 9274: The ideas in this section have also been published in M. Anton Ertl,
 9275: @cite{@uref{http://www.complang.tuwien.ac.at/papers/ertl94l.ps.gz,
 9276: Automatic Scoping of Local Variables}}, EuroForth '94.
 9277: 
 9278: @menu
 9279: * Gforth locals::               
 9280: * ANS Forth locals::            
 9281: @end menu
 9282: 
 9283: @node Gforth locals, ANS Forth locals, Locals, Locals
 9284: @subsection Gforth locals
 9285: @cindex Gforth locals
 9286: @cindex locals, Gforth style
 9287: 
 9288: Locals can be defined with
 9289: 
 9290: @example
 9291: @{ local1 local2 ... -- comment @}
 9292: @end example
 9293: or
 9294: @example
 9295: @{ local1 local2 ... @}
 9296: @end example
 9297: 
 9298: E.g.,
 9299: @example
 9300: : max @{ n1 n2 -- n3 @}
 9301:  n1 n2 > if
 9302:    n1
 9303:  else
 9304:    n2
 9305:  endif ;
 9306: @end example
 9307: 
 9308: The similarity of locals definitions with stack comments is intended. A
 9309: locals definition often replaces the stack comment of a word. The order
 9310: of the locals corresponds to the order in a stack comment and everything
 9311: after the @code{--} is really a comment.
 9312: 
 9313: This similarity has one disadvantage: It is too easy to confuse locals
 9314: declarations with stack comments, causing bugs and making them hard to
 9315: find. However, this problem can be avoided by appropriate coding
 9316: conventions: Do not use both notations in the same program. If you do,
 9317: they should be distinguished using additional means, e.g. by position.
 9318: 
 9319: @cindex types of locals
 9320: @cindex locals types
 9321: The name of the local may be preceded by a type specifier, e.g.,
 9322: @code{F:} for a floating point value:
 9323: 
 9324: @example
 9325: : CX* @{ F: Ar F: Ai F: Br F: Bi -- Cr Ci @}
 9326: \ complex multiplication
 9327:  Ar Br f* Ai Bi f* f-
 9328:  Ar Bi f* Ai Br f* f+ ;
 9329: @end example
 9330: 
 9331: @cindex flavours of locals
 9332: @cindex locals flavours
 9333: @cindex value-flavoured locals
 9334: @cindex variable-flavoured locals
 9335: Gforth currently supports cells (@code{W:}, @code{W^}), doubles
 9336: (@code{D:}, @code{D^}), floats (@code{F:}, @code{F^}) and characters
 9337: (@code{C:}, @code{C^}) in two flavours: a value-flavoured local (defined
 9338: with @code{W:}, @code{D:} etc.) produces its value and can be changed
 9339: with @code{TO}. A variable-flavoured local (defined with @code{W^} etc.)
 9340: produces its address (which becomes invalid when the variable's scope is
 9341: left). E.g., the standard word @code{emit} can be defined in terms of
 9342: @code{type} like this:
 9343: 
 9344: @example
 9345: : emit @{ C^ char* -- @}
 9346:     char* 1 type ;
 9347: @end example
 9348: 
 9349: @cindex default type of locals
 9350: @cindex locals, default type
 9351: A local without type specifier is a @code{W:} local. Both flavours of
 9352: locals are initialized with values from the data or FP stack.
 9353: 
 9354: Currently there is no way to define locals with user-defined data
 9355: structures, but we are working on it.
 9356: 
 9357: Gforth allows defining locals everywhere in a colon definition. This
 9358: poses the following questions:
 9359: 
 9360: @menu
 9361: * Where are locals visible by name?::  
 9362: * How long do locals live?::    
 9363: * Locals programming style::    
 9364: * Locals implementation::       
 9365: @end menu
 9366: 
 9367: @node Where are locals visible by name?, How long do locals live?, Gforth locals, Gforth locals
 9368: @subsubsection Where are locals visible by name?
 9369: @cindex locals visibility
 9370: @cindex visibility of locals
 9371: @cindex scope of locals
 9372: 
 9373: Basically, the answer is that locals are visible where you would expect
 9374: it in block-structured languages, and sometimes a little longer. If you
 9375: want to restrict the scope of a local, enclose its definition in
 9376: @code{SCOPE}...@code{ENDSCOPE}.
 9377: 
 9378: 
 9379: doc-scope
 9380: doc-endscope
 9381: 
 9382: 
 9383: These words behave like control structure words, so you can use them
 9384: with @code{CS-PICK} and @code{CS-ROLL} to restrict the scope in
 9385: arbitrary ways.
 9386: 
 9387: If you want a more exact answer to the visibility question, here's the
 9388: basic principle: A local is visible in all places that can only be
 9389: reached through the definition of the local@footnote{In compiler
 9390: construction terminology, all places dominated by the definition of the
 9391: local.}. In other words, it is not visible in places that can be reached
 9392: without going through the definition of the local. E.g., locals defined
 9393: in @code{IF}...@code{ENDIF} are visible until the @code{ENDIF}, locals
 9394: defined in @code{BEGIN}...@code{UNTIL} are visible after the
 9395: @code{UNTIL} (until, e.g., a subsequent @code{ENDSCOPE}).
 9396: 
 9397: The reasoning behind this solution is: We want to have the locals
 9398: visible as long as it is meaningful. The user can always make the
 9399: visibility shorter by using explicit scoping. In a place that can
 9400: only be reached through the definition of a local, the meaning of a
 9401: local name is clear. In other places it is not: How is the local
 9402: initialized at the control flow path that does not contain the
 9403: definition? Which local is meant, if the same name is defined twice in
 9404: two independent control flow paths?
 9405: 
 9406: This should be enough detail for nearly all users, so you can skip the
 9407: rest of this section. If you really must know all the gory details and
 9408: options, read on.
 9409: 
 9410: In order to implement this rule, the compiler has to know which places
 9411: are unreachable. It knows this automatically after @code{AHEAD},
 9412: @code{AGAIN}, @code{EXIT} and @code{LEAVE}; in other cases (e.g., after
 9413: most @code{THROW}s), you can use the word @code{UNREACHABLE} to tell the
 9414: compiler that the control flow never reaches that place. If
 9415: @code{UNREACHABLE} is not used where it could, the only consequence is
 9416: that the visibility of some locals is more limited than the rule above
 9417: says. If @code{UNREACHABLE} is used where it should not (i.e., if you
 9418: lie to the compiler), buggy code will be produced.
 9419: 
 9420: 
 9421: doc-unreachable
 9422: 
 9423: 
 9424: Another problem with this rule is that at @code{BEGIN}, the compiler
 9425: does not know which locals will be visible on the incoming
 9426: back-edge. All problems discussed in the following are due to this
 9427: ignorance of the compiler (we discuss the problems using @code{BEGIN}
 9428: loops as examples; the discussion also applies to @code{?DO} and other
 9429: loops). Perhaps the most insidious example is:
 9430: @example
 9431: AHEAD
 9432: BEGIN
 9433:   x
 9434: [ 1 CS-ROLL ] THEN
 9435:   @{ x @}
 9436:   ...
 9437: UNTIL
 9438: @end example
 9439: 
 9440: This should be legal according to the visibility rule. The use of
 9441: @code{x} can only be reached through the definition; but that appears
 9442: textually below the use.
 9443: 
 9444: From this example it is clear that the visibility rules cannot be fully
 9445: implemented without major headaches. Our implementation treats common
 9446: cases as advertised and the exceptions are treated in a safe way: The
 9447: compiler makes a reasonable guess about the locals visible after a
 9448: @code{BEGIN}; if it is too pessimistic, the
 9449: user will get a spurious error about the local not being defined; if the
 9450: compiler is too optimistic, it will notice this later and issue a
 9451: warning. In the case above the compiler would complain about @code{x}
 9452: being undefined at its use. You can see from the obscure examples in
 9453: this section that it takes quite unusual control structures to get the
 9454: compiler into trouble, and even then it will often do fine.
 9455: 
 9456: If the @code{BEGIN} is reachable from above, the most optimistic guess
 9457: is that all locals visible before the @code{BEGIN} will also be
 9458: visible after the @code{BEGIN}. This guess is valid for all loops that
 9459: are entered only through the @code{BEGIN}, in particular, for normal
 9460: @code{BEGIN}...@code{WHILE}...@code{REPEAT} and
 9461: @code{BEGIN}...@code{UNTIL} loops and it is implemented in our
 9462: compiler. When the branch to the @code{BEGIN} is finally generated by
 9463: @code{AGAIN} or @code{UNTIL}, the compiler checks the guess and
 9464: warns the user if it was too optimistic:
 9465: @example
 9466: IF
 9467:   @{ x @}
 9468: BEGIN
 9469:   \ x ? 
 9470: [ 1 cs-roll ] THEN
 9471:   ...
 9472: UNTIL
 9473: @end example
 9474: 
 9475: Here, @code{x} lives only until the @code{BEGIN}, but the compiler
 9476: optimistically assumes that it lives until the @code{THEN}. It notices
 9477: this difference when it compiles the @code{UNTIL} and issues a
 9478: warning. The user can avoid the warning, and make sure that @code{x}
 9479: is not used in the wrong area by using explicit scoping:
 9480: @example
 9481: IF
 9482:   SCOPE
 9483:   @{ x @}
 9484:   ENDSCOPE
 9485: BEGIN
 9486: [ 1 cs-roll ] THEN
 9487:   ...
 9488: UNTIL
 9489: @end example
 9490: 
 9491: Since the guess is optimistic, there will be no spurious error messages
 9492: about undefined locals.
 9493: 
 9494: If the @code{BEGIN} is not reachable from above (e.g., after
 9495: @code{AHEAD} or @code{EXIT}), the compiler cannot even make an
 9496: optimistic guess, as the locals visible after the @code{BEGIN} may be
 9497: defined later. Therefore, the compiler assumes that no locals are
 9498: visible after the @code{BEGIN}. However, the user can use
 9499: @code{ASSUME-LIVE} to make the compiler assume that the same locals are
 9500: visible at the BEGIN as at the point where the top control-flow stack
 9501: item was created.
 9502: 
 9503: 
 9504: doc-assume-live
 9505: 
 9506: 
 9507: @noindent
 9508: E.g.,
 9509: @example
 9510: @{ x @}
 9511: AHEAD
 9512: ASSUME-LIVE
 9513: BEGIN
 9514:   x
 9515: [ 1 CS-ROLL ] THEN
 9516:   ...
 9517: UNTIL
 9518: @end example
 9519: 
 9520: Other cases where the locals are defined before the @code{BEGIN} can be
 9521: handled by inserting an appropriate @code{CS-ROLL} before the
 9522: @code{ASSUME-LIVE} (and changing the control-flow stack manipulation
 9523: behind the @code{ASSUME-LIVE}).
 9524: 
 9525: Cases where locals are defined after the @code{BEGIN} (but should be
 9526: visible immediately after the @code{BEGIN}) can only be handled by
 9527: rearranging the loop. E.g., the ``most insidious'' example above can be
 9528: arranged into:
 9529: @example
 9530: BEGIN
 9531:   @{ x @}
 9532:   ... 0=
 9533: WHILE
 9534:   x
 9535: REPEAT
 9536: @end example
 9537: 
 9538: @node How long do locals live?, Locals programming style, Where are locals visible by name?, Gforth locals
 9539: @subsubsection How long do locals live?
 9540: @cindex locals lifetime
 9541: @cindex lifetime of locals
 9542: 
 9543: The right answer for the lifetime question would be: A local lives at
 9544: least as long as it can be accessed. For a value-flavoured local this
 9545: means: until the end of its visibility. However, a variable-flavoured
 9546: local could be accessed through its address far beyond its visibility
 9547: scope. Ultimately, this would mean that such locals would have to be
 9548: garbage collected. Since this entails un-Forth-like implementation
 9549: complexities, I adopted the same cowardly solution as some other
 9550: languages (e.g., C): The local lives only as long as it is visible;
 9551: afterwards its address is invalid (and programs that access it
 9552: afterwards are erroneous).
 9553: 
 9554: @node Locals programming style, Locals implementation, How long do locals live?, Gforth locals
 9555: @subsubsection Locals programming style
 9556: @cindex locals programming style
 9557: @cindex programming style, locals
 9558: 
 9559: The freedom to define locals anywhere has the potential to change
 9560: programming styles dramatically. In particular, the need to use the
 9561: return stack for intermediate storage vanishes. Moreover, all stack
 9562: manipulations (except @code{PICK}s and @code{ROLL}s with run-time
 9563: determined arguments) can be eliminated: If the stack items are in the
 9564: wrong order, just write a locals definition for all of them; then
 9565: write the items in the order you want.
 9566: 
 9567: This seems a little far-fetched and eliminating stack manipulations is
 9568: unlikely to become a conscious programming objective. Still, the number
 9569: of stack manipulations will be reduced dramatically if local variables
 9570: are used liberally (e.g., compare @code{max} (@pxref{Gforth locals}) with
 9571: a traditional implementation of @code{max}).
 9572: 
 9573: This shows one potential benefit of locals: making Forth programs more
 9574: readable. Of course, this benefit will only be realized if the
 9575: programmers continue to honour the principle of factoring instead of
 9576: using the added latitude to make the words longer.
 9577: 
 9578: @cindex single-assignment style for locals
 9579: Using @code{TO} can and should be avoided.  Without @code{TO},
 9580: every value-flavoured local has only a single assignment and many
 9581: advantages of functional languages apply to Forth. I.e., programs are
 9582: easier to analyse, to optimize and to read: It is clear from the
 9583: definition what the local stands for, it does not turn into something
 9584: different later.
 9585: 
 9586: E.g., a definition using @code{TO} might look like this:
 9587: @example
 9588: : strcmp @{ addr1 u1 addr2 u2 -- n @}
 9589:  u1 u2 min 0
 9590:  ?do
 9591:    addr1 c@@ addr2 c@@ -
 9592:    ?dup-if
 9593:      unloop exit
 9594:    then
 9595:    addr1 char+ TO addr1
 9596:    addr2 char+ TO addr2
 9597:  loop
 9598:  u1 u2 - ;
 9599: @end example
 9600: Here, @code{TO} is used to update @code{addr1} and @code{addr2} at
 9601: every loop iteration. @code{strcmp} is a typical example of the
 9602: readability problems of using @code{TO}. When you start reading
 9603: @code{strcmp}, you think that @code{addr1} refers to the start of the
 9604: string. Only near the end of the loop you realize that it is something
 9605: else.
 9606: 
 9607: This can be avoided by defining two locals at the start of the loop that
 9608: are initialized with the right value for the current iteration.
 9609: @example
 9610: : strcmp @{ addr1 u1 addr2 u2 -- n @}
 9611:  addr1 addr2
 9612:  u1 u2 min 0 
 9613:  ?do @{ s1 s2 @}
 9614:    s1 c@@ s2 c@@ -
 9615:    ?dup-if
 9616:      unloop exit
 9617:    then
 9618:    s1 char+ s2 char+
 9619:  loop
 9620:  2drop
 9621:  u1 u2 - ;
 9622: @end example
 9623: Here it is clear from the start that @code{s1} has a different value
 9624: in every loop iteration.
 9625: 
 9626: @node Locals implementation,  , Locals programming style, Gforth locals
 9627: @subsubsection Locals implementation
 9628: @cindex locals implementation
 9629: @cindex implementation of locals
 9630: 
 9631: @cindex locals stack
 9632: Gforth uses an extra locals stack. The most compelling reason for
 9633: this is that the return stack is not float-aligned; using an extra stack
 9634: also eliminates the problems and restrictions of using the return stack
 9635: as locals stack. Like the other stacks, the locals stack grows toward
 9636: lower addresses. A few primitives allow an efficient implementation:
 9637: 
 9638: 
 9639: doc-@local#
 9640: doc-f@local#
 9641: doc-laddr#
 9642: doc-lp+!#
 9643: doc-lp!
 9644: doc->l
 9645: doc-f>l
 9646: 
 9647: 
 9648: In addition to these primitives, some specializations of these
 9649: primitives for commonly occurring inline arguments are provided for
 9650: efficiency reasons, e.g., @code{@@local0} as specialization of
 9651: @code{@@local#} for the inline argument 0. The following compiling words
 9652: compile the right specialized version, or the general version, as
 9653: appropriate:
 9654: 
 9655: 
 9656: @c doc-compile-@local
 9657: @c doc-compile-f@local
 9658: doc-compile-lp+!
 9659: 
 9660: 
 9661: Combinations of conditional branches and @code{lp+!#} like
 9662: @code{?branch-lp+!#} (the locals pointer is only changed if the branch
 9663: is taken) are provided for efficiency and correctness in loops.
 9664: 
 9665: A special area in the dictionary space is reserved for keeping the
 9666: local variable names. @code{@{} switches the dictionary pointer to this
 9667: area and @code{@}} switches it back and generates the locals
 9668: initializing code. @code{W:} etc.@ are normal defining words. This
 9669: special area is cleared at the start of every colon definition.
 9670: 
 9671: @cindex word list for defining locals
 9672: A special feature of Gforth's dictionary is used to implement the
 9673: definition of locals without type specifiers: every word list (aka
 9674: vocabulary) has its own methods for searching
 9675: etc. (@pxref{Word Lists}). For the present purpose we defined a word list
 9676: with a special search method: When it is searched for a word, it
 9677: actually creates that word using @code{W:}. @code{@{} changes the search
 9678: order to first search the word list containing @code{@}}, @code{W:} etc.,
 9679: and then the word list for defining locals without type specifiers.
 9680: 
 9681: The lifetime rules support a stack discipline within a colon
 9682: definition: The lifetime of a local is either nested with other locals
 9683: lifetimes or it does not overlap them.
 9684: 
 9685: At @code{BEGIN}, @code{IF}, and @code{AHEAD} no code for locals stack
 9686: pointer manipulation is generated. Between control structure words
 9687: locals definitions can push locals onto the locals stack. @code{AGAIN}
 9688: is the simplest of the other three control flow words. It has to
 9689: restore the locals stack depth of the corresponding @code{BEGIN}
 9690: before branching. The code looks like this:
 9691: @format
 9692: @code{lp+!#} current-locals-size @minus{} dest-locals-size
 9693: @code{branch} <begin>
 9694: @end format
 9695: 
 9696: @code{UNTIL} is a little more complicated: If it branches back, it
 9697: must adjust the stack just like @code{AGAIN}. But if it falls through,
 9698: the locals stack must not be changed. The compiler generates the
 9699: following code:
 9700: @format
 9701: @code{?branch-lp+!#} <begin> current-locals-size @minus{} dest-locals-size
 9702: @end format
 9703: The locals stack pointer is only adjusted if the branch is taken.
 9704: 
 9705: @code{THEN} can produce somewhat inefficient code:
 9706: @format
 9707: @code{lp+!#} current-locals-size @minus{} orig-locals-size
 9708: <orig target>:
 9709: @code{lp+!#} orig-locals-size @minus{} new-locals-size
 9710: @end format
 9711: The second @code{lp+!#} adjusts the locals stack pointer from the
 9712: level at the @i{orig} point to the level after the @code{THEN}. The
 9713: first @code{lp+!#} adjusts the locals stack pointer from the current
 9714: level to the level at the orig point, so the complete effect is an
 9715: adjustment from the current level to the right level after the
 9716: @code{THEN}.
 9717: 
 9718: @cindex locals information on the control-flow stack
 9719: @cindex control-flow stack items, locals information
 9720: In a conventional Forth implementation a dest control-flow stack entry
 9721: is just the target address and an orig entry is just the address to be
 9722: patched. Our locals implementation adds a word list to every orig or dest
 9723: item. It is the list of locals visible (or assumed visible) at the point
 9724: described by the entry. Our implementation also adds a tag to identify
 9725: the kind of entry, in particular to differentiate between live and dead
 9726: (reachable and unreachable) orig entries.
 9727: 
 9728: A few unusual operations have to be performed on locals word lists:
 9729: 
 9730: 
 9731: doc-common-list
 9732: doc-sub-list?
 9733: doc-list-size
 9734: 
 9735: 
 9736: Several features of our locals word list implementation make these
 9737: operations easy to implement: The locals word lists are organised as
 9738: linked lists; the tails of these lists are shared, if the lists
 9739: contain some of the same locals; and the address of a name is greater
 9740: than the address of the names behind it in the list.
 9741: 
 9742: Another important implementation detail is the variable
 9743: @code{dead-code}. It is used by @code{BEGIN} and @code{THEN} to
 9744: determine if they can be reached directly or only through the branch
 9745: that they resolve. @code{dead-code} is set by @code{UNREACHABLE},
 9746: @code{AHEAD}, @code{EXIT} etc., and cleared at the start of a colon
 9747: definition, by @code{BEGIN} and usually by @code{THEN}.
 9748: 
 9749: Counted loops are similar to other loops in most respects, but
 9750: @code{LEAVE} requires special attention: It performs basically the same
 9751: service as @code{AHEAD}, but it does not create a control-flow stack
 9752: entry. Therefore the information has to be stored elsewhere;
 9753: traditionally, the information was stored in the target fields of the
 9754: branches created by the @code{LEAVE}s, by organizing these fields into a
 9755: linked list. Unfortunately, this clever trick does not provide enough
 9756: space for storing our extended control flow information. Therefore, we
 9757: introduce another stack, the leave stack. It contains the control-flow
 9758: stack entries for all unresolved @code{LEAVE}s.
 9759: 
 9760: Local names are kept until the end of the colon definition, even if
 9761: they are no longer visible in any control-flow path. In a few cases
 9762: this may lead to increased space needs for the locals name area, but
 9763: usually less than reclaiming this space would cost in code size.
 9764: 
 9765: 
 9766: @node ANS Forth locals,  , Gforth locals, Locals
 9767: @subsection ANS Forth locals
 9768: @cindex locals, ANS Forth style
 9769: 
 9770: The ANS Forth locals wordset does not define a syntax for locals, but
 9771: words that make it possible to define various syntaxes. One of the
 9772: possible syntaxes is a subset of the syntax we used in the Gforth locals
 9773: wordset, i.e.:
 9774: 
 9775: @example
 9776: @{ local1 local2 ... -- comment @}
 9777: @end example
 9778: @noindent
 9779: or
 9780: @example
 9781: @{ local1 local2 ... @}
 9782: @end example
 9783: 
 9784: The order of the locals corresponds to the order in a stack comment. The
 9785: restrictions are:
 9786: 
 9787: @itemize @bullet
 9788: @item
 9789: Locals can only be cell-sized values (no type specifiers are allowed).
 9790: @item
 9791: Locals can be defined only outside control structures.
 9792: @item
 9793: Locals can interfere with explicit usage of the return stack. For the
 9794: exact (and long) rules, see the standard. If you don't use return stack
 9795: accessing words in a definition using locals, you will be all right. The
 9796: purpose of this rule is to make locals implementation on the return
 9797: stack easier.
 9798: @item
 9799: The whole definition must be in one line.
 9800: @end itemize
 9801: 
 9802: Locals defined in ANS Forth behave like @code{VALUE}s
 9803: (@pxref{Values}). I.e., they are initialized from the stack. Using their
 9804: name produces their value. Their value can be changed using @code{TO}.
 9805: 
 9806: Since the syntax above is supported by Gforth directly, you need not do
 9807: anything to use it. If you want to port a program using this syntax to
 9808: another ANS Forth system, use @file{compat/anslocal.fs} to implement the
 9809: syntax on the other system.
 9810: 
 9811: Note that a syntax shown in the standard, section A.13 looks
 9812: similar, but is quite different in having the order of locals
 9813: reversed. Beware!
 9814: 
 9815: The ANS Forth locals wordset itself consists of one word:
 9816: 
 9817: doc-(local)
 9818: 
 9819: The ANS Forth locals extension wordset defines a syntax using
 9820: @code{locals|}, but it is so awful that we strongly recommend not to use
 9821: it. We have implemented this syntax to make porting to Gforth easy, but
 9822: do not document it here. The problem with this syntax is that the locals
 9823: are defined in an order reversed with respect to the standard stack
 9824: comment notation, making programs harder to read, and easier to misread
 9825: and miswrite. The only merit of this syntax is that it is easy to
 9826: implement using the ANS Forth locals wordset.
 9827: 
 9828: 
 9829: @c ----------------------------------------------------------
 9830: @node Structures, Object-oriented Forth, Locals, Words
 9831: @section  Structures
 9832: @cindex structures
 9833: @cindex records
 9834: 
 9835: This section presents the structure package that comes with Gforth. A
 9836: version of the package implemented in ANS Forth is available in
 9837: @file{compat/struct.fs}. This package was inspired by a posting on
 9838: comp.lang.forth in 1989 (unfortunately I don't remember, by whom;
 9839: possibly John Hayes). A version of this section has been published in
 9840: M. Anton Ertl,
 9841: @uref{http://www.complang.tuwien.ac.at/forth/objects/structs.html, Yet
 9842: Another Forth Structures Package}, Forth Dimensions 19(3), pages
 9843: 13--16. Marcel Hendrix provided helpful comments.
 9844: 
 9845: @menu
 9846: * Why explicit structure support?::  
 9847: * Structure Usage::             
 9848: * Structure Naming Convention::  
 9849: * Structure Implementation::    
 9850: * Structure Glossary::          
 9851: * Forth200x Structures::        
 9852: @end menu
 9853: 
 9854: @node Why explicit structure support?, Structure Usage, Structures, Structures
 9855: @subsection Why explicit structure support?
 9856: 
 9857: @cindex address arithmetic for structures
 9858: @cindex structures using address arithmetic
 9859: If we want to use a structure containing several fields, we could simply
 9860: reserve memory for it, and access the fields using address arithmetic
 9861: (@pxref{Address arithmetic}). As an example, consider a structure with
 9862: the following fields
 9863: 
 9864: @table @code
 9865: @item a
 9866: is a float
 9867: @item b
 9868: is a cell
 9869: @item c
 9870: is a float
 9871: @end table
 9872: 
 9873: Given the (float-aligned) base address of the structure we get the
 9874: address of the field
 9875: 
 9876: @table @code
 9877: @item a
 9878: without doing anything further.
 9879: @item b
 9880: with @code{float+}
 9881: @item c
 9882: with @code{float+ cell+ faligned}
 9883: @end table
 9884: 
 9885: It is easy to see that this can become quite tiring. 
 9886: 
 9887: Moreover, it is not very readable, because seeing a
 9888: @code{cell+} tells us neither which kind of structure is
 9889: accessed nor what field is accessed; we have to somehow infer the kind
 9890: of structure, and then look up in the documentation, which field of
 9891: that structure corresponds to that offset.
 9892: 
 9893: Finally, this kind of address arithmetic also causes maintenance
 9894: troubles: If you add or delete a field somewhere in the middle of the
 9895: structure, you have to find and change all computations for the fields
 9896: afterwards.
 9897: 
 9898: So, instead of using @code{cell+} and friends directly, how
 9899: about storing the offsets in constants:
 9900: 
 9901: @example
 9902: 0 constant a-offset
 9903: 0 float+ constant b-offset
 9904: 0 float+ cell+ faligned c-offset
 9905: @end example
 9906: 
 9907: Now we can get the address of field @code{x} with @code{x-offset
 9908: +}. This is much better in all respects. Of course, you still
 9909: have to change all later offset definitions if you add a field. You can
 9910: fix this by declaring the offsets in the following way:
 9911: 
 9912: @example
 9913: 0 constant a-offset
 9914: a-offset float+ constant b-offset
 9915: b-offset cell+ faligned constant c-offset
 9916: @end example
 9917: 
 9918: Since we always use the offsets with @code{+}, we could use a defining
 9919: word @code{cfield} that includes the @code{+} in the action of the
 9920: defined word:
 9921: 
 9922: @example
 9923: : cfield ( n "name" -- )
 9924:     create ,
 9925: does> ( name execution: addr1 -- addr2 )
 9926:     @@ + ;
 9927: 
 9928: 0 cfield a
 9929: 0 a float+ cfield b
 9930: 0 b cell+ faligned cfield c
 9931: @end example
 9932: 
 9933: Instead of @code{x-offset +}, we now simply write @code{x}.
 9934: 
 9935: The structure field words now can be used quite nicely. However,
 9936: their definition is still a bit cumbersome: We have to repeat the
 9937: name, the information about size and alignment is distributed before
 9938: and after the field definitions etc.  The structure package presented
 9939: here addresses these problems.
 9940: 
 9941: @node Structure Usage, Structure Naming Convention, Why explicit structure support?, Structures
 9942: @subsection Structure Usage
 9943: @cindex structure usage
 9944: 
 9945: @cindex @code{field} usage
 9946: @cindex @code{struct} usage
 9947: @cindex @code{end-struct} usage
 9948: You can define a structure for a (data-less) linked list with:
 9949: @example
 9950: struct
 9951:     cell% field list-next
 9952: end-struct list%
 9953: @end example
 9954: 
 9955: With the address of the list node on the stack, you can compute the
 9956: address of the field that contains the address of the next node with
 9957: @code{list-next}. E.g., you can determine the length of a list
 9958: with:
 9959: 
 9960: @example
 9961: : list-length ( list -- n )
 9962: \ "list" is a pointer to the first element of a linked list
 9963: \ "n" is the length of the list
 9964:     0 BEGIN ( list1 n1 )
 9965:         over
 9966:     WHILE ( list1 n1 )
 9967:         1+ swap list-next @@ swap
 9968:     REPEAT
 9969:     nip ;
 9970: @end example
 9971: 
 9972: You can reserve memory for a list node in the dictionary with
 9973: @code{list% %allot}, which leaves the address of the list node on the
 9974: stack. For the equivalent allocation on the heap you can use @code{list%
 9975: %alloc} (or, for an @code{allocate}-like stack effect (i.e., with ior),
 9976: use @code{list% %allocate}). You can get the the size of a list
 9977: node with @code{list% %size} and its alignment with @code{list%
 9978: %alignment}.
 9979: 
 9980: Note that in ANS Forth the body of a @code{create}d word is
 9981: @code{aligned} but not necessarily @code{faligned};
 9982: therefore, if you do a:
 9983: 
 9984: @example
 9985: create @emph{name} foo% %allot drop
 9986: @end example
 9987: 
 9988: @noindent
 9989: then the memory alloted for @code{foo%} is guaranteed to start at the
 9990: body of @code{@emph{name}} only if @code{foo%} contains only character,
 9991: cell and double fields.  Therefore, if your structure contains floats,
 9992: better use
 9993: 
 9994: @example
 9995: foo% %allot constant @emph{name}
 9996: @end example
 9997: 
 9998: @cindex structures containing structures
 9999: You can include a structure @code{foo%} as a field of
10000: another structure, like this:
10001: @example
10002: struct
10003: ...
10004:     foo% field ...
10005: ...
10006: end-struct ...
10007: @end example
10008: 
10009: @cindex structure extension
10010: @cindex extended records
10011: Instead of starting with an empty structure, you can extend an
10012: existing structure. E.g., a plain linked list without data, as defined
10013: above, is hardly useful; You can extend it to a linked list of integers,
10014: like this:@footnote{This feature is also known as @emph{extended
10015: records}. It is the main innovation in the Oberon language; in other
10016: words, adding this feature to Modula-2 led Wirth to create a new
10017: language, write a new compiler etc.  Adding this feature to Forth just
10018: required a few lines of code.}
10019: 
10020: @example
10021: list%
10022:     cell% field intlist-int
10023: end-struct intlist%
10024: @end example
10025: 
10026: @code{intlist%} is a structure with two fields:
10027: @code{list-next} and @code{intlist-int}.
10028: 
10029: @cindex structures containing arrays
10030: You can specify an array type containing @emph{n} elements of
10031: type @code{foo%} like this:
10032: 
10033: @example
10034: foo% @emph{n} *
10035: @end example
10036: 
10037: You can use this array type in any place where you can use a normal
10038: type, e.g., when defining a @code{field}, or with
10039: @code{%allot}.
10040: 
10041: @cindex first field optimization
10042: The first field is at the base address of a structure and the word for
10043: this field (e.g., @code{list-next}) actually does not change the address
10044: on the stack. You may be tempted to leave it away in the interest of
10045: run-time and space efficiency. This is not necessary, because the
10046: structure package optimizes this case: If you compile a first-field
10047: words, no code is generated. So, in the interest of readability and
10048: maintainability you should include the word for the field when accessing
10049: the field.
10050: 
10051: 
10052: @node Structure Naming Convention, Structure Implementation, Structure Usage, Structures
10053: @subsection Structure Naming Convention
10054: @cindex structure naming convention
10055: 
10056: The field names that come to (my) mind are often quite generic, and,
10057: if used, would cause frequent name clashes. E.g., many structures
10058: probably contain a @code{counter} field. The structure names
10059: that come to (my) mind are often also the logical choice for the names
10060: of words that create such a structure.
10061: 
10062: Therefore, I have adopted the following naming conventions: 
10063: 
10064: @itemize @bullet
10065: @cindex field naming convention
10066: @item
10067: The names of fields are of the form
10068: @code{@emph{struct}-@emph{field}}, where
10069: @code{@emph{struct}} is the basic name of the structure, and
10070: @code{@emph{field}} is the basic name of the field. You can
10071: think of field words as converting the (address of the)
10072: structure into the (address of the) field.
10073: 
10074: @cindex structure naming convention
10075: @item
10076: The names of structures are of the form
10077: @code{@emph{struct}%}, where
10078: @code{@emph{struct}} is the basic name of the structure.
10079: @end itemize
10080: 
10081: This naming convention does not work that well for fields of extended
10082: structures; e.g., the integer list structure has a field
10083: @code{intlist-int}, but has @code{list-next}, not
10084: @code{intlist-next}.
10085: 
10086: @node Structure Implementation, Structure Glossary, Structure Naming Convention, Structures
10087: @subsection Structure Implementation
10088: @cindex structure implementation
10089: @cindex implementation of structures
10090: 
10091: The central idea in the implementation is to pass the data about the
10092: structure being built on the stack, not in some global
10093: variable. Everything else falls into place naturally once this design
10094: decision is made.
10095: 
10096: The type description on the stack is of the form @emph{align
10097: size}. Keeping the size on the top-of-stack makes dealing with arrays
10098: very simple.
10099: 
10100: @code{field} is a defining word that uses @code{Create}
10101: and @code{DOES>}. The body of the field contains the offset
10102: of the field, and the normal @code{DOES>} action is simply:
10103: 
10104: @example
10105: @@ +
10106: @end example
10107: 
10108: @noindent
10109: i.e., add the offset to the address, giving the stack effect
10110: @i{addr1 -- addr2} for a field.
10111: 
10112: @cindex first field optimization, implementation
10113: This simple structure is slightly complicated by the optimization
10114: for fields with offset 0, which requires a different
10115: @code{DOES>}-part (because we cannot rely on there being
10116: something on the stack if such a field is invoked during
10117: compilation). Therefore, we put the different @code{DOES>}-parts
10118: in separate words, and decide which one to invoke based on the
10119: offset. For a zero offset, the field is basically a noop; it is
10120: immediate, and therefore no code is generated when it is compiled.
10121: 
10122: @node Structure Glossary, Forth200x Structures, Structure Implementation, Structures
10123: @subsection Structure Glossary
10124: @cindex structure glossary
10125: 
10126: 
10127: doc-%align
10128: doc-%alignment
10129: doc-%alloc
10130: doc-%allocate
10131: doc-%allot
10132: doc-cell%
10133: doc-char%
10134: doc-dfloat%
10135: doc-double%
10136: doc-end-struct
10137: doc-field
10138: doc-float%
10139: doc-naligned
10140: doc-sfloat%
10141: doc-%size
10142: doc-struct
10143: 
10144: 
10145: @node Forth200x Structures,  , Structure Glossary, Structures
10146: @subsection Forth200x Structures
10147: @cindex Structures in Forth200x
10148: 
10149: The Forth 200x standard defines a slightly less convenient form of
10150: structures.  In general (when using @code{field+}, you have to perform
10151: the alignment yourself, but there are a number of convenience words
10152: (e.g., @code{field:} that perform the alignment for you.
10153: 
10154: A typical usage example is:
10155: 
10156: @example
10157: 0
10158:   field:                   s-a
10159:   faligned 2 floats +field s-b
10160: constant s-struct
10161: @end example
10162: 
10163: An alternative way of writing this structure is:
10164: 
10165: @example
10166: begin-structure s-struct
10167:   field:                   s-a
10168:   faligned 2 floats +field s-b
10169: end-structure
10170: @end example
10171: 
10172: doc-begin-structure
10173: doc-end-structure
10174: doc-+field
10175: doc-cfield:
10176: doc-field:
10177: doc-2field:
10178: doc-ffield:
10179: doc-sffield:
10180: doc-dffield:
10181: 
10182: @c -------------------------------------------------------------
10183: @node Object-oriented Forth, Programming Tools, Structures, Words
10184: @section Object-oriented Forth
10185: 
10186: Gforth comes with three packages for object-oriented programming:
10187: @file{objects.fs}, @file{oof.fs}, and @file{mini-oof.fs}; none of them
10188: is preloaded, so you have to @code{include} them before use. The most
10189: important differences between these packages (and others) are discussed
10190: in @ref{Comparison with other object models}. All packages are written
10191: in ANS Forth and can be used with any other ANS Forth.
10192: 
10193: @menu
10194: * Why object-oriented programming?::  
10195: * Object-Oriented Terminology::  
10196: * Objects::                     
10197: * OOF::                         
10198: * Mini-OOF::                    
10199: * Comparison with other object models::  
10200: @end menu
10201: 
10202: @c ----------------------------------------------------------------
10203: @node Why object-oriented programming?, Object-Oriented Terminology, Object-oriented Forth, Object-oriented Forth
10204: @subsection Why object-oriented programming?
10205: @cindex object-oriented programming motivation
10206: @cindex motivation for object-oriented programming
10207: 
10208: Often we have to deal with several data structures (@emph{objects}),
10209: that have to be treated similarly in some respects, but differently in
10210: others. Graphical objects are the textbook example: circles, triangles,
10211: dinosaurs, icons, and others, and we may want to add more during program
10212: development. We want to apply some operations to any graphical object,
10213: e.g., @code{draw} for displaying it on the screen. However, @code{draw}
10214: has to do something different for every kind of object.
10215: @comment TODO add some other operations eg perimeter, area
10216: @comment and tie in to concrete examples later..
10217: 
10218: We could implement @code{draw} as a big @code{CASE}
10219: control structure that executes the appropriate code depending on the
10220: kind of object to be drawn. This would be not be very elegant, and,
10221: moreover, we would have to change @code{draw} every time we add
10222: a new kind of graphical object (say, a spaceship).
10223: 
10224: What we would rather do is: When defining spaceships, we would tell
10225: the system: ``Here's how you @code{draw} a spaceship; you figure
10226: out the rest''.
10227: 
10228: This is the problem that all systems solve that (rightfully) call
10229: themselves object-oriented; the object-oriented packages presented here
10230: solve this problem (and not much else).
10231: @comment TODO ?list properties of oo systems.. oo vs o-based?
10232: 
10233: @c ------------------------------------------------------------------------
10234: @node Object-Oriented Terminology, Objects, Why object-oriented programming?, Object-oriented Forth
10235: @subsection Object-Oriented Terminology
10236: @cindex object-oriented terminology
10237: @cindex terminology for object-oriented programming
10238: 
10239: This section is mainly for reference, so you don't have to understand
10240: all of it right away.  The terminology is mainly Smalltalk-inspired.  In
10241: short:
10242: 
10243: @table @emph
10244: @cindex class
10245: @item class
10246: a data structure definition with some extras.
10247: 
10248: @cindex object
10249: @item object
10250: an instance of the data structure described by the class definition.
10251: 
10252: @cindex instance variables
10253: @item instance variables
10254: fields of the data structure.
10255: 
10256: @cindex selector
10257: @cindex method selector
10258: @cindex virtual function
10259: @item selector
10260: (or @emph{method selector}) a word (e.g.,
10261: @code{draw}) that performs an operation on a variety of data
10262: structures (classes). A selector describes @emph{what} operation to
10263: perform. In C++ terminology: a (pure) virtual function.
10264: 
10265: @cindex method
10266: @item method
10267: the concrete definition that performs the operation
10268: described by the selector for a specific class. A method specifies
10269: @emph{how} the operation is performed for a specific class.
10270: 
10271: @cindex selector invocation
10272: @cindex message send
10273: @cindex invoking a selector
10274: @item selector invocation
10275: a call of a selector. One argument of the call (the TOS (top-of-stack))
10276: is used for determining which method is used. In Smalltalk terminology:
10277: a message (consisting of the selector and the other arguments) is sent
10278: to the object.
10279: 
10280: @cindex receiving object
10281: @item receiving object
10282: the object used for determining the method executed by a selector
10283: invocation. In the @file{objects.fs} model, it is the object that is on
10284: the TOS when the selector is invoked. (@emph{Receiving} comes from
10285: the Smalltalk @emph{message} terminology.)
10286: 
10287: @cindex child class
10288: @cindex parent class
10289: @cindex inheritance
10290: @item child class
10291: a class that has (@emph{inherits}) all properties (instance variables,
10292: selectors, methods) from a @emph{parent class}. In Smalltalk
10293: terminology: The subclass inherits from the superclass. In C++
10294: terminology: The derived class inherits from the base class.
10295: 
10296: @end table
10297: 
10298: @c If you wonder about the message sending terminology, it comes from
10299: @c a time when each object had it's own task and objects communicated via
10300: @c message passing; eventually the Smalltalk developers realized that
10301: @c they can do most things through simple (indirect) calls. They kept the
10302: @c terminology.
10303: 
10304: @c --------------------------------------------------------------
10305: @node Objects, OOF, Object-Oriented Terminology, Object-oriented Forth
10306: @subsection The @file{objects.fs} model
10307: @cindex objects
10308: @cindex object-oriented programming
10309: 
10310: @cindex @file{objects.fs}
10311: @cindex @file{oof.fs}
10312: 
10313: This section describes the @file{objects.fs} package. This material also
10314: has been published in M. Anton Ertl,
10315: @cite{@uref{http://www.complang.tuwien.ac.at/forth/objects/objects.html,
10316: Yet Another Forth Objects Package}}, Forth Dimensions 19(2), pages
10317: 37--43.
10318: @c McKewan's and Zsoter's packages
10319: 
10320: This section assumes that you have read @ref{Structures}.
10321: 
10322: The techniques on which this model is based have been used to implement
10323: the parser generator, Gray, and have also been used in Gforth for
10324: implementing the various flavours of word lists (hashed or not,
10325: case-sensitive or not, special-purpose word lists for locals etc.).
10326: 
10327: 
10328: @menu
10329: * Properties of the Objects model::  
10330: * Basic Objects Usage::         
10331: * The Objects base class::      
10332: * Creating objects::            
10333: * Object-Oriented Programming Style::  
10334: * Class Binding::               
10335: * Method conveniences::         
10336: * Classes and Scoping::         
10337: * Dividing classes::            
10338: * Object Interfaces::           
10339: * Objects Implementation::      
10340: * Objects Glossary::            
10341: @end menu
10342: 
10343: Marcel Hendrix provided helpful comments on this section.
10344: 
10345: @node Properties of the Objects model, Basic Objects Usage, Objects, Objects
10346: @subsubsection Properties of the @file{objects.fs} model
10347: @cindex @file{objects.fs} properties
10348: 
10349: @itemize @bullet
10350: @item
10351: It is straightforward to pass objects on the stack. Passing
10352: selectors on the stack is a little less convenient, but possible.
10353: 
10354: @item
10355: Objects are just data structures in memory, and are referenced by their
10356: address. You can create words for objects with normal defining words
10357: like @code{constant}. Likewise, there is no difference between instance
10358: variables that contain objects and those that contain other data.
10359: 
10360: @item
10361: Late binding is efficient and easy to use.
10362: 
10363: @item
10364: It avoids parsing, and thus avoids problems with state-smartness
10365: and reduced extensibility; for convenience there are a few parsing
10366: words, but they have non-parsing counterparts. There are also a few
10367: defining words that parse. This is hard to avoid, because all standard
10368: defining words parse (except @code{:noname}); however, such
10369: words are not as bad as many other parsing words, because they are not
10370: state-smart.
10371: 
10372: @item
10373: It does not try to incorporate everything. It does a few things and does
10374: them well (IMO). In particular, this model was not designed to support
10375: information hiding (although it has features that may help); you can use
10376: a separate package for achieving this.
10377: 
10378: @item
10379: It is layered; you don't have to learn and use all features to use this
10380: model. Only a few features are necessary (@pxref{Basic Objects Usage},
10381: @pxref{The Objects base class}, @pxref{Creating objects}.), the others
10382: are optional and independent of each other.
10383: 
10384: @item
10385: An implementation in ANS Forth is available.
10386: 
10387: @end itemize
10388: 
10389: 
10390: @node Basic Objects Usage, The Objects base class, Properties of the Objects model, Objects
10391: @subsubsection Basic @file{objects.fs} Usage
10392: @cindex basic objects usage
10393: @cindex objects, basic usage
10394: 
10395: You can define a class for graphical objects like this:
10396: 
10397: @cindex @code{class} usage
10398: @cindex @code{end-class} usage
10399: @cindex @code{selector} usage
10400: @example
10401: object class \ "object" is the parent class
10402:   selector draw ( x y graphical -- )
10403: end-class graphical
10404: @end example
10405: 
10406: This code defines a class @code{graphical} with an
10407: operation @code{draw}.  We can perform the operation
10408: @code{draw} on any @code{graphical} object, e.g.:
10409: 
10410: @example
10411: 100 100 t-rex draw
10412: @end example
10413: 
10414: @noindent
10415: where @code{t-rex} is a word (say, a constant) that produces a
10416: graphical object.
10417: 
10418: @comment TODO add a 2nd operation eg perimeter.. and use for
10419: @comment a concrete example
10420: 
10421: @cindex abstract class
10422: How do we create a graphical object? With the present definitions,
10423: we cannot create a useful graphical object. The class
10424: @code{graphical} describes graphical objects in general, but not
10425: any concrete graphical object type (C++ users would call it an
10426: @emph{abstract class}); e.g., there is no method for the selector
10427: @code{draw} in the class @code{graphical}.
10428: 
10429: For concrete graphical objects, we define child classes of the
10430: class @code{graphical}, e.g.:
10431: 
10432: @cindex @code{overrides} usage
10433: @cindex @code{field} usage in class definition
10434: @example
10435: graphical class \ "graphical" is the parent class
10436:   cell% field circle-radius
10437: 
10438: :noname ( x y circle -- )
10439:   circle-radius @@ draw-circle ;
10440: overrides draw
10441: 
10442: :noname ( n-radius circle -- )
10443:   circle-radius ! ;
10444: overrides construct
10445: 
10446: end-class circle
10447: @end example
10448: 
10449: Here we define a class @code{circle} as a child of @code{graphical},
10450: with field @code{circle-radius} (which behaves just like a field
10451: (@pxref{Structures}); it defines (using @code{overrides}) new methods
10452: for the selectors @code{draw} and @code{construct} (@code{construct} is
10453: defined in @code{object}, the parent class of @code{graphical}).
10454: 
10455: Now we can create a circle on the heap (i.e.,
10456: @code{allocate}d memory) with:
10457: 
10458: @cindex @code{heap-new} usage
10459: @example
10460: 50 circle heap-new constant my-circle
10461: @end example
10462: 
10463: @noindent
10464: @code{heap-new} invokes @code{construct}, thus
10465: initializing the field @code{circle-radius} with 50. We can draw
10466: this new circle at (100,100) with:
10467: 
10468: @example
10469: 100 100 my-circle draw
10470: @end example
10471: 
10472: @cindex selector invocation, restrictions
10473: @cindex class definition, restrictions
10474: Note: You can only invoke a selector if the object on the TOS
10475: (the receiving object) belongs to the class where the selector was
10476: defined or one of its descendents; e.g., you can invoke
10477: @code{draw} only for objects belonging to @code{graphical}
10478: or its descendents (e.g., @code{circle}).  Immediately before
10479: @code{end-class}, the search order has to be the same as
10480: immediately after @code{class}.
10481: 
10482: @node The Objects base class, Creating objects, Basic Objects Usage, Objects
10483: @subsubsection The @file{object.fs} base class
10484: @cindex @code{object} class
10485: 
10486: When you define a class, you have to specify a parent class.  So how do
10487: you start defining classes? There is one class available from the start:
10488: @code{object}. It is ancestor for all classes and so is the
10489: only class that has no parent. It has two selectors: @code{construct}
10490: and @code{print}.
10491: 
10492: @node Creating objects, Object-Oriented Programming Style, The Objects base class, Objects
10493: @subsubsection Creating objects
10494: @cindex creating objects
10495: @cindex object creation
10496: @cindex object allocation options
10497: 
10498: @cindex @code{heap-new} discussion
10499: @cindex @code{dict-new} discussion
10500: @cindex @code{construct} discussion
10501: You can create and initialize an object of a class on the heap with
10502: @code{heap-new} ( ... class -- object ) and in the dictionary
10503: (allocation with @code{allot}) with @code{dict-new} (
10504: ... class -- object ). Both words invoke @code{construct}, which
10505: consumes the stack items indicated by "..." above.
10506: 
10507: @cindex @code{init-object} discussion
10508: @cindex @code{class-inst-size} discussion
10509: If you want to allocate memory for an object yourself, you can get its
10510: alignment and size with @code{class-inst-size 2@@} ( class --
10511: align size ). Once you have memory for an object, you can initialize
10512: it with @code{init-object} ( ... class object -- );
10513: @code{construct} does only a part of the necessary work.
10514: 
10515: @node Object-Oriented Programming Style, Class Binding, Creating objects, Objects
10516: @subsubsection Object-Oriented Programming Style
10517: @cindex object-oriented programming style
10518: @cindex programming style, object-oriented
10519: 
10520: This section is not exhaustive.
10521: 
10522: @cindex stack effects of selectors
10523: @cindex selectors and stack effects
10524: In general, it is a good idea to ensure that all methods for the
10525: same selector have the same stack effect: when you invoke a selector,
10526: you often have no idea which method will be invoked, so, unless all
10527: methods have the same stack effect, you will not know the stack effect
10528: of the selector invocation.
10529: 
10530: One exception to this rule is methods for the selector
10531: @code{construct}. We know which method is invoked, because we
10532: specify the class to be constructed at the same place. Actually, I
10533: defined @code{construct} as a selector only to give the users a
10534: convenient way to specify initialization. The way it is used, a
10535: mechanism different from selector invocation would be more natural
10536: (but probably would take more code and more space to explain).
10537: 
10538: @node Class Binding, Method conveniences, Object-Oriented Programming Style, Objects
10539: @subsubsection Class Binding
10540: @cindex class binding
10541: @cindex early binding
10542: 
10543: @cindex late binding
10544: Normal selector invocations determine the method at run-time depending
10545: on the class of the receiving object. This run-time selection is called
10546: @i{late binding}.
10547: 
10548: Sometimes it's preferable to invoke a different method. For example,
10549: you might want to use the simple method for @code{print}ing
10550: @code{object}s instead of the possibly long-winded @code{print} method
10551: of the receiver class. You can achieve this by replacing the invocation
10552: of @code{print} with:
10553: 
10554: @cindex @code{[bind]} usage
10555: @example
10556: [bind] object print
10557: @end example
10558: 
10559: @noindent
10560: in compiled code or:
10561: 
10562: @cindex @code{bind} usage
10563: @example
10564: bind object print
10565: @end example
10566: 
10567: @cindex class binding, alternative to
10568: @noindent
10569: in interpreted code. Alternatively, you can define the method with a
10570: name (e.g., @code{print-object}), and then invoke it through the
10571: name. Class binding is just a (often more convenient) way to achieve
10572: the same effect; it avoids name clutter and allows you to invoke
10573: methods directly without naming them first.
10574: 
10575: @cindex superclass binding
10576: @cindex parent class binding
10577: A frequent use of class binding is this: When we define a method
10578: for a selector, we often want the method to do what the selector does
10579: in the parent class, and a little more. There is a special word for
10580: this purpose: @code{[parent]}; @code{[parent]
10581: @emph{selector}} is equivalent to @code{[bind] @emph{parent
10582: selector}}, where @code{@emph{parent}} is the parent
10583: class of the current class. E.g., a method definition might look like:
10584: 
10585: @cindex @code{[parent]} usage
10586: @example
10587: :noname
10588:   dup [parent] foo \ do parent's foo on the receiving object
10589:   ... \ do some more
10590: ; overrides foo
10591: @end example
10592: 
10593: @cindex class binding as optimization
10594: In @cite{Object-oriented programming in ANS Forth} (Forth Dimensions,
10595: March 1997), Andrew McKewan presents class binding as an optimization
10596: technique. I recommend not using it for this purpose unless you are in
10597: an emergency. Late binding is pretty fast with this model anyway, so the
10598: benefit of using class binding is small; the cost of using class binding
10599: where it is not appropriate is reduced maintainability.
10600: 
10601: While we are at programming style questions: You should bind
10602: selectors only to ancestor classes of the receiving object. E.g., say,
10603: you know that the receiving object is of class @code{foo} or its
10604: descendents; then you should bind only to @code{foo} and its
10605: ancestors.
10606: 
10607: @node Method conveniences, Classes and Scoping, Class Binding, Objects
10608: @subsubsection Method conveniences
10609: @cindex method conveniences
10610: 
10611: In a method you usually access the receiving object pretty often.  If
10612: you define the method as a plain colon definition (e.g., with
10613: @code{:noname}), you may have to do a lot of stack
10614: gymnastics. To avoid this, you can define the method with @code{m:
10615: ... ;m}. E.g., you could define the method for
10616: @code{draw}ing a @code{circle} with
10617: 
10618: @cindex @code{this} usage
10619: @cindex @code{m:} usage
10620: @cindex @code{;m} usage
10621: @example
10622: m: ( x y circle -- )
10623:   ( x y ) this circle-radius @@ draw-circle ;m
10624: @end example
10625: 
10626: @cindex @code{exit} in @code{m: ... ;m}
10627: @cindex @code{exitm} discussion
10628: @cindex @code{catch} in @code{m: ... ;m}
10629: When this method is executed, the receiver object is removed from the
10630: stack; you can access it with @code{this} (admittedly, in this
10631: example the use of @code{m: ... ;m} offers no advantage). Note
10632: that I specify the stack effect for the whole method (i.e. including
10633: the receiver object), not just for the code between @code{m:}
10634: and @code{;m}. You cannot use @code{exit} in
10635: @code{m:...;m}; instead, use
10636: @code{exitm}.@footnote{Moreover, for any word that calls
10637: @code{catch} and was defined before loading
10638: @code{objects.fs}, you have to redefine it like I redefined
10639: @code{catch}: @code{: catch this >r catch r> to-this ;}}
10640: 
10641: @cindex @code{inst-var} usage
10642: You will frequently use sequences of the form @code{this
10643: @emph{field}} (in the example above: @code{this
10644: circle-radius}). If you use the field only in this way, you can
10645: define it with @code{inst-var} and eliminate the
10646: @code{this} before the field name. E.g., the @code{circle}
10647: class above could also be defined with:
10648: 
10649: @example
10650: graphical class
10651:   cell% inst-var radius
10652: 
10653: m: ( x y circle -- )
10654:   radius @@ draw-circle ;m
10655: overrides draw
10656: 
10657: m: ( n-radius circle -- )
10658:   radius ! ;m
10659: overrides construct
10660: 
10661: end-class circle
10662: @end example
10663: 
10664: @code{radius} can only be used in @code{circle} and its
10665: descendent classes and inside @code{m:...;m}.
10666: 
10667: @cindex @code{inst-value} usage
10668: You can also define fields with @code{inst-value}, which is
10669: to @code{inst-var} what @code{value} is to
10670: @code{variable}.  You can change the value of such a field with
10671: @code{[to-inst]}.  E.g., we could also define the class
10672: @code{circle} like this:
10673: 
10674: @example
10675: graphical class
10676:   inst-value radius
10677: 
10678: m: ( x y circle -- )
10679:   radius draw-circle ;m
10680: overrides draw
10681: 
10682: m: ( n-radius circle -- )
10683:   [to-inst] radius ;m
10684: overrides construct
10685: 
10686: end-class circle
10687: @end example
10688: 
10689: @c !! :m is easy to confuse with m:.  Another name would be better.
10690: 
10691: @c Finally, you can define named methods with @code{:m}.  One use of this
10692: @c feature is the definition of words that occur only in one class and are
10693: @c not intended to be overridden, but which still need method context
10694: @c (e.g., for accessing @code{inst-var}s).  Another use is for methods that
10695: @c would be bound frequently, if defined anonymously.
10696: 
10697: 
10698: @node Classes and Scoping, Dividing classes, Method conveniences, Objects
10699: @subsubsection Classes and Scoping
10700: @cindex classes and scoping
10701: @cindex scoping and classes
10702: 
10703: Inheritance is frequent, unlike structure extension. This exacerbates
10704: the problem with the field name convention (@pxref{Structure Naming
10705: Convention}): One always has to remember in which class the field was
10706: originally defined; changing a part of the class structure would require
10707: changes for renaming in otherwise unaffected code.
10708: 
10709: @cindex @code{inst-var} visibility
10710: @cindex @code{inst-value} visibility
10711: To solve this problem, I added a scoping mechanism (which was not in my
10712: original charter): A field defined with @code{inst-var} (or
10713: @code{inst-value}) is visible only in the class where it is defined and in
10714: the descendent classes of this class.  Using such fields only makes
10715: sense in @code{m:}-defined methods in these classes anyway.
10716: 
10717: This scoping mechanism allows us to use the unadorned field name,
10718: because name clashes with unrelated words become much less likely.
10719: 
10720: @cindex @code{protected} discussion
10721: @cindex @code{private} discussion
10722: Once we have this mechanism, we can also use it for controlling the
10723: visibility of other words: All words defined after
10724: @code{protected} are visible only in the current class and its
10725: descendents. @code{public} restores the compilation
10726: (i.e. @code{current}) word list that was in effect before. If you
10727: have several @code{protected}s without an intervening
10728: @code{public} or @code{set-current}, @code{public}
10729: will restore the compilation word list in effect before the first of
10730: these @code{protected}s.
10731: 
10732: @node Dividing classes, Object Interfaces, Classes and Scoping, Objects
10733: @subsubsection Dividing classes
10734: @cindex Dividing classes
10735: @cindex @code{methods}...@code{end-methods}
10736: 
10737: You may want to do the definition of methods separate from the
10738: definition of the class, its selectors, fields, and instance variables,
10739: i.e., separate the implementation from the definition.  You can do this
10740: in the following way:
10741: 
10742: @example
10743: graphical class
10744:   inst-value radius
10745: end-class circle
10746: 
10747: ... \ do some other stuff
10748: 
10749: circle methods \ now we are ready
10750: 
10751: m: ( x y circle -- )
10752:   radius draw-circle ;m
10753: overrides draw
10754: 
10755: m: ( n-radius circle -- )
10756:   [to-inst] radius ;m
10757: overrides construct
10758: 
10759: end-methods
10760: @end example
10761: 
10762: You can use several @code{methods}...@code{end-methods} sections.  The
10763: only things you can do to the class in these sections are: defining
10764: methods, and overriding the class's selectors.  You must not define new
10765: selectors or fields.
10766: 
10767: Note that you often have to override a selector before using it.  In
10768: particular, you usually have to override @code{construct} with a new
10769: method before you can invoke @code{heap-new} and friends.  E.g., you
10770: must not create a circle before the @code{overrides construct} sequence
10771: in the example above.
10772: 
10773: @node Object Interfaces, Objects Implementation, Dividing classes, Objects
10774: @subsubsection Object Interfaces
10775: @cindex object interfaces
10776: @cindex interfaces for objects
10777: 
10778: In this model you can only call selectors defined in the class of the
10779: receiving objects or in one of its ancestors. If you call a selector
10780: with a receiving object that is not in one of these classes, the
10781: result is undefined; if you are lucky, the program crashes
10782: immediately.
10783: 
10784: @cindex selectors common to hardly-related classes
10785: Now consider the case when you want to have a selector (or several)
10786: available in two classes: You would have to add the selector to a
10787: common ancestor class, in the worst case to @code{object}. You
10788: may not want to do this, e.g., because someone else is responsible for
10789: this ancestor class.
10790: 
10791: The solution for this problem is interfaces. An interface is a
10792: collection of selectors. If a class implements an interface, the
10793: selectors become available to the class and its descendents. A class
10794: can implement an unlimited number of interfaces. For the problem
10795: discussed above, we would define an interface for the selector(s), and
10796: both classes would implement the interface.
10797: 
10798: As an example, consider an interface @code{storage} for
10799: writing objects to disk and getting them back, and a class
10800: @code{foo} that implements it. The code would look like this:
10801: 
10802: @cindex @code{interface} usage
10803: @cindex @code{end-interface} usage
10804: @cindex @code{implementation} usage
10805: @example
10806: interface
10807:   selector write ( file object -- )
10808:   selector read1 ( file object -- )
10809: end-interface storage
10810: 
10811: bar class
10812:   storage implementation
10813: 
10814: ... overrides write
10815: ... overrides read1
10816: ...
10817: end-class foo
10818: @end example
10819: 
10820: @noindent
10821: (I would add a word @code{read} @i{( file -- object )} that uses
10822: @code{read1} internally, but that's beyond the point illustrated
10823: here.)
10824: 
10825: Note that you cannot use @code{protected} in an interface; and
10826: of course you cannot define fields.
10827: 
10828: In the Neon model, all selectors are available for all classes;
10829: therefore it does not need interfaces. The price you pay in this model
10830: is slower late binding, and therefore, added complexity to avoid late
10831: binding.
10832: 
10833: @node Objects Implementation, Objects Glossary, Object Interfaces, Objects
10834: @subsubsection @file{objects.fs} Implementation
10835: @cindex @file{objects.fs} implementation
10836: 
10837: @cindex @code{object-map} discussion
10838: An object is a piece of memory, like one of the data structures
10839: described with @code{struct...end-struct}. It has a field
10840: @code{object-map} that points to the method map for the object's
10841: class.
10842: 
10843: @cindex method map
10844: @cindex virtual function table
10845: The @emph{method map}@footnote{This is Self terminology; in C++
10846: terminology: virtual function table.} is an array that contains the
10847: execution tokens (@i{xt}s) of the methods for the object's class. Each
10848: selector contains an offset into a method map.
10849: 
10850: @cindex @code{selector} implementation, class
10851: @code{selector} is a defining word that uses
10852: @code{CREATE} and @code{DOES>}. The body of the
10853: selector contains the offset; the @code{DOES>} action for a
10854: class selector is, basically:
10855: 
10856: @example
10857: ( object addr ) @@ over object-map @@ + @@ execute
10858: @end example
10859: 
10860: Since @code{object-map} is the first field of the object, it
10861: does not generate any code. As you can see, calling a selector has a
10862: small, constant cost.
10863: 
10864: @cindex @code{current-interface} discussion
10865: @cindex class implementation and representation
10866: A class is basically a @code{struct} combined with a method
10867: map. During the class definition the alignment and size of the class
10868: are passed on the stack, just as with @code{struct}s, so
10869: @code{field} can also be used for defining class
10870: fields. However, passing more items on the stack would be
10871: inconvenient, so @code{class} builds a data structure in memory,
10872: which is accessed through the variable
10873: @code{current-interface}. After its definition is complete, the
10874: class is represented on the stack by a pointer (e.g., as parameter for
10875: a child class definition).
10876: 
10877: A new class starts off with the alignment and size of its parent,
10878: and a copy of the parent's method map. Defining new fields extends the
10879: size and alignment; likewise, defining new selectors extends the
10880: method map. @code{overrides} just stores a new @i{xt} in the method
10881: map at the offset given by the selector.
10882: 
10883: @cindex class binding, implementation
10884: Class binding just gets the @i{xt} at the offset given by the selector
10885: from the class's method map and @code{compile,}s (in the case of
10886: @code{[bind]}) it.
10887: 
10888: @cindex @code{this} implementation
10889: @cindex @code{catch} and @code{this}
10890: @cindex @code{this} and @code{catch}
10891: I implemented @code{this} as a @code{value}. At the
10892: start of an @code{m:...;m} method the old @code{this} is
10893: stored to the return stack and restored at the end; and the object on
10894: the TOS is stored @code{TO this}. This technique has one
10895: disadvantage: If the user does not leave the method via
10896: @code{;m}, but via @code{throw} or @code{exit},
10897: @code{this} is not restored (and @code{exit} may
10898: crash). To deal with the @code{throw} problem, I have redefined
10899: @code{catch} to save and restore @code{this}; the same
10900: should be done with any word that can catch an exception. As for
10901: @code{exit}, I simply forbid it (as a replacement, there is
10902: @code{exitm}).
10903: 
10904: @cindex @code{inst-var} implementation
10905: @code{inst-var} is just the same as @code{field}, with
10906: a different @code{DOES>} action:
10907: @example
10908: @@ this +
10909: @end example
10910: Similar for @code{inst-value}.
10911: 
10912: @cindex class scoping implementation
10913: Each class also has a word list that contains the words defined with
10914: @code{inst-var} and @code{inst-value}, and its protected
10915: words. It also has a pointer to its parent. @code{class} pushes
10916: the word lists of the class and all its ancestors onto the search order stack,
10917: and @code{end-class} drops them.
10918: 
10919: @cindex interface implementation
10920: An interface is like a class without fields, parent and protected
10921: words; i.e., it just has a method map. If a class implements an
10922: interface, its method map contains a pointer to the method map of the
10923: interface. The positive offsets in the map are reserved for class
10924: methods, therefore interface map pointers have negative
10925: offsets. Interfaces have offsets that are unique throughout the
10926: system, unlike class selectors, whose offsets are only unique for the
10927: classes where the selector is available (invokable).
10928: 
10929: This structure means that interface selectors have to perform one
10930: indirection more than class selectors to find their method. Their body
10931: contains the interface map pointer offset in the class method map, and
10932: the method offset in the interface method map. The
10933: @code{does>} action for an interface selector is, basically:
10934: 
10935: @example
10936: ( object selector-body )
10937: 2dup selector-interface @@ ( object selector-body object interface-offset )
10938: swap object-map @@ + @@ ( object selector-body map )
10939: swap selector-offset @@ + @@ execute
10940: @end example
10941: 
10942: where @code{object-map} and @code{selector-offset} are
10943: first fields and generate no code.
10944: 
10945: As a concrete example, consider the following code:
10946: 
10947: @example
10948: interface
10949:   selector if1sel1
10950:   selector if1sel2
10951: end-interface if1
10952: 
10953: object class
10954:   if1 implementation
10955:   selector cl1sel1
10956:   cell% inst-var cl1iv1
10957: 
10958: ' m1 overrides construct
10959: ' m2 overrides if1sel1
10960: ' m3 overrides if1sel2
10961: ' m4 overrides cl1sel2
10962: end-class cl1
10963: 
10964: create obj1 object dict-new drop
10965: create obj2 cl1    dict-new drop
10966: @end example
10967: 
10968: The data structure created by this code (including the data structure
10969: for @code{object}) is shown in the
10970: @uref{objects-implementation.eps,figure}, assuming a cell size of 4.
10971: @comment TODO add this diagram..
10972: 
10973: @node Objects Glossary,  , Objects Implementation, Objects
10974: @subsubsection @file{objects.fs} Glossary
10975: @cindex @file{objects.fs} Glossary
10976: 
10977: 
10978: doc---objects-bind
10979: doc---objects-<bind>
10980: doc---objects-bind'
10981: doc---objects-[bind]
10982: doc---objects-class
10983: doc---objects-class->map
10984: doc---objects-class-inst-size
10985: doc---objects-class-override!
10986: doc---objects-class-previous
10987: doc---objects-class>order
10988: doc---objects-construct
10989: doc---objects-current'
10990: doc---objects-[current]
10991: doc---objects-current-interface
10992: doc---objects-dict-new
10993: doc---objects-end-class
10994: doc---objects-end-class-noname
10995: doc---objects-end-interface
10996: doc---objects-end-interface-noname
10997: doc---objects-end-methods
10998: doc---objects-exitm
10999: doc---objects-heap-new
11000: doc---objects-implementation
11001: doc---objects-init-object
11002: doc---objects-inst-value
11003: doc---objects-inst-var
11004: doc---objects-interface
11005: doc---objects-m:
11006: doc---objects-:m
11007: doc---objects-;m
11008: doc---objects-method
11009: doc---objects-methods
11010: doc---objects-object
11011: doc---objects-overrides
11012: doc---objects-[parent]
11013: doc---objects-print
11014: doc---objects-protected
11015: doc---objects-public
11016: doc---objects-selector
11017: doc---objects-this
11018: doc---objects-<to-inst>
11019: doc---objects-[to-inst]
11020: doc---objects-to-this
11021: doc---objects-xt-new
11022: 
11023: 
11024: @c -------------------------------------------------------------
11025: @node OOF, Mini-OOF, Objects, Object-oriented Forth
11026: @subsection The @file{oof.fs} model
11027: @cindex oof
11028: @cindex object-oriented programming
11029: 
11030: @cindex @file{objects.fs}
11031: @cindex @file{oof.fs}
11032: 
11033: This section describes the @file{oof.fs} package.
11034: 
11035: The package described in this section has been used in bigFORTH since 1991, and
11036: used for two large applications: a chromatographic system used to
11037: create new medicaments, and a graphic user interface library (MINOS).
11038: 
11039: You can find a description (in German) of @file{oof.fs} in @cite{Object
11040: oriented bigFORTH} by Bernd Paysan, published in @cite{Vierte Dimension}
11041: 10(2), 1994.
11042: 
11043: @menu
11044: * Properties of the OOF model::  
11045: * Basic OOF Usage::             
11046: * The OOF base class::          
11047: * Class Declaration::           
11048: * Class Implementation::        
11049: @end menu
11050: 
11051: @node Properties of the OOF model, Basic OOF Usage, OOF, OOF
11052: @subsubsection Properties of the @file{oof.fs} model
11053: @cindex @file{oof.fs} properties
11054: 
11055: @itemize @bullet
11056: @item
11057: This model combines object oriented programming with information
11058: hiding. It helps you writing large application, where scoping is
11059: necessary, because it provides class-oriented scoping.
11060: 
11061: @item
11062: Named objects, object pointers, and object arrays can be created,
11063: selector invocation uses the ``object selector'' syntax. Selector invocation
11064: to objects and/or selectors on the stack is a bit less convenient, but
11065: possible.
11066: 
11067: @item
11068: Selector invocation and instance variable usage of the active object is
11069: straightforward, since both make use of the active object.
11070: 
11071: @item
11072: Late binding is efficient and easy to use.
11073: 
11074: @item
11075: State-smart objects parse selectors. However, extensibility is provided
11076: using a (parsing) selector @code{postpone} and a selector @code{'}.
11077: 
11078: @item
11079: An implementation in ANS Forth is available.
11080: 
11081: @end itemize
11082: 
11083: 
11084: @node Basic OOF Usage, The OOF base class, Properties of the OOF model, OOF
11085: @subsubsection Basic @file{oof.fs} Usage
11086: @cindex @file{oof.fs} usage
11087: 
11088: This section uses the same example as for @code{objects} (@pxref{Basic Objects Usage}).
11089: 
11090: You can define a class for graphical objects like this:
11091: 
11092: @cindex @code{class} usage
11093: @cindex @code{class;} usage
11094: @cindex @code{method} usage
11095: @example
11096: object class graphical \ "object" is the parent class
11097:   method draw ( x y -- )
11098: class;
11099: @end example
11100: 
11101: This code defines a class @code{graphical} with an
11102: operation @code{draw}.  We can perform the operation
11103: @code{draw} on any @code{graphical} object, e.g.:
11104: 
11105: @example
11106: 100 100 t-rex draw
11107: @end example
11108: 
11109: @noindent
11110: where @code{t-rex} is an object or object pointer, created with e.g.
11111: @code{graphical : t-rex}.
11112: 
11113: @cindex abstract class
11114: How do we create a graphical object? With the present definitions,
11115: we cannot create a useful graphical object. The class
11116: @code{graphical} describes graphical objects in general, but not
11117: any concrete graphical object type (C++ users would call it an
11118: @emph{abstract class}); e.g., there is no method for the selector
11119: @code{draw} in the class @code{graphical}.
11120: 
11121: For concrete graphical objects, we define child classes of the
11122: class @code{graphical}, e.g.:
11123: 
11124: @example
11125: graphical class circle \ "graphical" is the parent class
11126:   cell var circle-radius
11127: how:
11128:   : draw ( x y -- )
11129:     circle-radius @@ draw-circle ;
11130: 
11131:   : init ( n-radius -- )
11132:     circle-radius ! ;
11133: class;
11134: @end example
11135: 
11136: Here we define a class @code{circle} as a child of @code{graphical},
11137: with a field @code{circle-radius}; it defines new methods for the
11138: selectors @code{draw} and @code{init} (@code{init} is defined in
11139: @code{object}, the parent class of @code{graphical}).
11140: 
11141: Now we can create a circle in the dictionary with:
11142: 
11143: @example
11144: 50 circle : my-circle
11145: @end example
11146: 
11147: @noindent
11148: @code{:} invokes @code{init}, thus initializing the field
11149: @code{circle-radius} with 50. We can draw this new circle at (100,100)
11150: with:
11151: 
11152: @example
11153: 100 100 my-circle draw
11154: @end example
11155: 
11156: @cindex selector invocation, restrictions
11157: @cindex class definition, restrictions
11158: Note: You can only invoke a selector if the receiving object belongs to
11159: the class where the selector was defined or one of its descendents;
11160: e.g., you can invoke @code{draw} only for objects belonging to
11161: @code{graphical} or its descendents (e.g., @code{circle}). The scoping
11162: mechanism will check if you try to invoke a selector that is not
11163: defined in this class hierarchy, so you'll get an error at compilation
11164: time.
11165: 
11166: 
11167: @node The OOF base class, Class Declaration, Basic OOF Usage, OOF
11168: @subsubsection The @file{oof.fs} base class
11169: @cindex @file{oof.fs} base class
11170: 
11171: When you define a class, you have to specify a parent class.  So how do
11172: you start defining classes? There is one class available from the start:
11173: @code{object}. You have to use it as ancestor for all classes. It is the
11174: only class that has no parent. Classes are also objects, except that
11175: they don't have instance variables; class manipulation such as
11176: inheritance or changing definitions of a class is handled through
11177: selectors of the class @code{object}.
11178: 
11179: @code{object} provides a number of selectors:
11180: 
11181: @itemize @bullet
11182: @item
11183: @code{class} for subclassing, @code{definitions} to add definitions
11184: later on, and @code{class?} to get type informations (is the class a
11185: subclass of the class passed on the stack?).
11186: 
11187: doc---object-class
11188: doc---object-definitions
11189: doc---object-class?
11190: 
11191: 
11192: @item
11193: @code{init} and @code{dispose} as constructor and destructor of the
11194: object. @code{init} is invocated after the object's memory is allocated,
11195: while @code{dispose} also handles deallocation. Thus if you redefine
11196: @code{dispose}, you have to call the parent's dispose with @code{super
11197: dispose}, too.
11198: 
11199: doc---object-init
11200: doc---object-dispose
11201: 
11202: 
11203: @item
11204: @code{new}, @code{new[]}, @code{:}, @code{ptr}, @code{asptr}, and
11205: @code{[]} to create named and unnamed objects and object arrays or
11206: object pointers.
11207: 
11208: doc---object-new
11209: doc---object-new[]
11210: doc---object-:
11211: doc---object-ptr
11212: doc---object-asptr
11213: doc---object-[]
11214: 
11215: 
11216: @item
11217: @code{::} and @code{super} for explicit scoping. You should use explicit
11218: scoping only for super classes or classes with the same set of instance
11219: variables. Explicitly-scoped selectors use early binding.
11220: 
11221: doc---object-::
11222: doc---object-super
11223: 
11224: 
11225: @item
11226: @code{self} to get the address of the object
11227: 
11228: doc---object-self
11229: 
11230: 
11231: @item
11232: @code{bind}, @code{bound}, @code{link}, and @code{is} to assign object
11233: pointers and instance defers.
11234: 
11235: doc---object-bind
11236: doc---object-bound
11237: doc---object-link
11238: doc---object-is
11239: 
11240: 
11241: @item
11242: @code{'} to obtain selector tokens, @code{send} to invocate selectors
11243: form the stack, and @code{postpone} to generate selector invocation code.
11244: 
11245: doc---object-'
11246: doc---object-postpone
11247: 
11248: 
11249: @item
11250: @code{with} and @code{endwith} to select the active object from the
11251: stack, and enable its scope. Using @code{with} and @code{endwith}
11252: also allows you to create code using selector @code{postpone} without being
11253: trapped by the state-smart objects.
11254: 
11255: doc---object-with
11256: doc---object-endwith
11257: 
11258: 
11259: @end itemize
11260: 
11261: @node Class Declaration, Class Implementation, The OOF base class, OOF
11262: @subsubsection Class Declaration
11263: @cindex class declaration
11264: 
11265: @itemize @bullet
11266: @item
11267: Instance variables
11268: 
11269: doc---oof-var
11270: 
11271: 
11272: @item
11273: Object pointers
11274: 
11275: doc---oof-ptr
11276: doc---oof-asptr
11277: 
11278: 
11279: @item
11280: Instance defers
11281: 
11282: doc---oof-defer
11283: 
11284: 
11285: @item
11286: Method selectors
11287: 
11288: doc---oof-early
11289: doc---oof-method
11290: 
11291: 
11292: @item
11293: Class-wide variables
11294: 
11295: doc---oof-static
11296: 
11297: 
11298: @item
11299: End declaration
11300: 
11301: doc---oof-how:
11302: doc---oof-class;
11303: 
11304: 
11305: @end itemize
11306: 
11307: @c -------------------------------------------------------------
11308: @node Class Implementation,  , Class Declaration, OOF
11309: @subsubsection Class Implementation
11310: @cindex class implementation
11311: 
11312: @c -------------------------------------------------------------
11313: @node Mini-OOF, Comparison with other object models, OOF, Object-oriented Forth
11314: @subsection The @file{mini-oof.fs} model
11315: @cindex mini-oof
11316: 
11317: Gforth's third object oriented Forth package is a 12-liner. It uses a
11318: mixture of the @file{objects.fs} and the @file{oof.fs} syntax,
11319: and reduces to the bare minimum of features. This is based on a posting
11320: of Bernd Paysan in comp.lang.forth.
11321: 
11322: @menu
11323: * Basic Mini-OOF Usage::        
11324: * Mini-OOF Example::            
11325: * Mini-OOF Implementation::     
11326: @end menu
11327: 
11328: @c -------------------------------------------------------------
11329: @node Basic Mini-OOF Usage, Mini-OOF Example, Mini-OOF, Mini-OOF
11330: @subsubsection Basic @file{mini-oof.fs} Usage
11331: @cindex mini-oof usage
11332: 
11333: There is a base class (@code{class}, which allocates one cell for the
11334: object pointer) plus seven other words: to define a method, a variable,
11335: a class; to end a class, to resolve binding, to allocate an object and
11336: to compile a class method.
11337: @comment TODO better description of the last one
11338: 
11339: 
11340: doc-object
11341: doc-method
11342: doc-var
11343: doc-class
11344: doc-end-class
11345: doc-defines
11346: doc-new
11347: doc-::
11348: 
11349: 
11350: 
11351: @c -------------------------------------------------------------
11352: @node Mini-OOF Example, Mini-OOF Implementation, Basic Mini-OOF Usage, Mini-OOF
11353: @subsubsection Mini-OOF Example
11354: @cindex mini-oof example
11355: 
11356: A short example shows how to use this package. This example, in slightly
11357: extended form, is supplied as @file{moof-exm.fs}
11358: @comment TODO could flesh this out with some comments from the Forthwrite article
11359: 
11360: @example
11361: object class
11362:   method init
11363:   method draw
11364: end-class graphical
11365: @end example
11366: 
11367: This code defines a class @code{graphical} with an
11368: operation @code{draw}.  We can perform the operation
11369: @code{draw} on any @code{graphical} object, e.g.:
11370: 
11371: @example
11372: 100 100 t-rex draw
11373: @end example
11374: 
11375: where @code{t-rex} is an object or object pointer, created with e.g.
11376: @code{graphical new Constant t-rex}.
11377: 
11378: For concrete graphical objects, we define child classes of the
11379: class @code{graphical}, e.g.:
11380: 
11381: @example
11382: graphical class
11383:   cell var circle-radius
11384: end-class circle \ "graphical" is the parent class
11385: 
11386: :noname ( x y -- )
11387:   circle-radius @@ draw-circle ; circle defines draw
11388: :noname ( r -- )
11389:   circle-radius ! ; circle defines init
11390: @end example
11391: 
11392: There is no implicit init method, so we have to define one. The creation
11393: code of the object now has to call init explicitely.
11394: 
11395: @example
11396: circle new Constant my-circle
11397: 50 my-circle init
11398: @end example
11399: 
11400: It is also possible to add a function to create named objects with
11401: automatic call of @code{init}, given that all objects have @code{init}
11402: on the same place:
11403: 
11404: @example
11405: : new: ( .. o "name" -- )
11406:     new dup Constant init ;
11407: 80 circle new: large-circle
11408: @end example
11409: 
11410: We can draw this new circle at (100,100) with:
11411: 
11412: @example
11413: 100 100 my-circle draw
11414: @end example
11415: 
11416: @node Mini-OOF Implementation,  , Mini-OOF Example, Mini-OOF
11417: @subsubsection @file{mini-oof.fs} Implementation
11418: 
11419: Object-oriented systems with late binding typically use a
11420: ``vtable''-approach: the first variable in each object is a pointer to a
11421: table, which contains the methods as function pointers. The vtable
11422: may also contain other information.
11423: 
11424: So first, let's declare selectors:
11425: 
11426: @example
11427: : method ( m v "name" -- m' v ) Create  over , swap cell+ swap
11428:   DOES> ( ... o -- ... ) @@ over @@ + @@ execute ;
11429: @end example
11430: 
11431: During selector declaration, the number of selectors and instance
11432: variables is on the stack (in address units). @code{method} creates one
11433: selector and increments the selector number. To execute a selector, it
11434: takes the object, fetches the vtable pointer, adds the offset, and
11435: executes the method @i{xt} stored there. Each selector takes the object
11436: it is invoked with as top of stack parameter; it passes the parameters
11437: (including the object) unchanged to the appropriate method which should
11438: consume that object.
11439: 
11440: Now, we also have to declare instance variables
11441: 
11442: @example
11443: : var ( m v size "name" -- m v' ) Create  over , +
11444:   DOES> ( o -- addr ) @@ + ;
11445: @end example
11446: 
11447: As before, a word is created with the current offset. Instance
11448: variables can have different sizes (cells, floats, doubles, chars), so
11449: all we do is take the size and add it to the offset. If your machine
11450: has alignment restrictions, put the proper @code{aligned} or
11451: @code{faligned} before the variable, to adjust the variable
11452: offset. That's why it is on the top of stack.
11453: 
11454: We need a starting point (the base object) and some syntactic sugar:
11455: 
11456: @example
11457: Create object  1 cells , 2 cells ,
11458: : class ( class -- class selectors vars ) dup 2@@ ;
11459: @end example
11460: 
11461: For inheritance, the vtable of the parent object has to be
11462: copied when a new, derived class is declared. This gives all the
11463: methods of the parent class, which can be overridden, though.
11464: 
11465: @example
11466: : end-class  ( class selectors vars "name" -- )
11467:   Create  here >r , dup , 2 cells ?DO ['] noop , 1 cells +LOOP
11468:   cell+ dup cell+ r> rot @@ 2 cells /string move ;
11469: @end example
11470: 
11471: The first line creates the vtable, initialized with
11472: @code{noop}s. The second line is the inheritance mechanism, it
11473: copies the xts from the parent vtable.
11474: 
11475: We still have no way to define new methods, let's do that now:
11476: 
11477: @example
11478: : defines ( xt class "name" -- ) ' >body @@ + ! ;
11479: @end example
11480: 
11481: To allocate a new object, we need a word, too:
11482: 
11483: @example
11484: : new ( class -- o )  here over @@ allot swap over ! ;
11485: @end example
11486: 
11487: Sometimes derived classes want to access the method of the
11488: parent object. There are two ways to achieve this with Mini-OOF:
11489: first, you could use named words, and second, you could look up the
11490: vtable of the parent object.
11491: 
11492: @example
11493: : :: ( class "name" -- ) ' >body @@ + @@ compile, ;
11494: @end example
11495: 
11496: 
11497: Nothing can be more confusing than a good example, so here is
11498: one. First let's declare a text object (called
11499: @code{button}), that stores text and position:
11500: 
11501: @example
11502: object class
11503:   cell var text
11504:   cell var len
11505:   cell var x
11506:   cell var y
11507:   method init
11508:   method draw
11509: end-class button
11510: @end example
11511: 
11512: @noindent
11513: Now, implement the two methods, @code{draw} and @code{init}:
11514: 
11515: @example
11516: :noname ( o -- )
11517:  >r r@@ x @@ r@@ y @@ at-xy  r@@ text @@ r> len @@ type ;
11518:  button defines draw
11519: :noname ( addr u o -- )
11520:  >r 0 r@@ x ! 0 r@@ y ! r@@ len ! r> text ! ;
11521:  button defines init
11522: @end example
11523: 
11524: @noindent
11525: To demonstrate inheritance, we define a class @code{bold-button}, with no
11526: new data and no new selectors:
11527: 
11528: @example
11529: button class
11530: end-class bold-button
11531: 
11532: : bold   27 emit ." [1m" ;
11533: : normal 27 emit ." [0m" ;
11534: @end example
11535: 
11536: @noindent
11537: The class @code{bold-button} has a different draw method to
11538: @code{button}, but the new method is defined in terms of the draw method
11539: for @code{button}:
11540: 
11541: @example
11542: :noname bold [ button :: draw ] normal ; bold-button defines draw
11543: @end example
11544: 
11545: @noindent
11546: Finally, create two objects and apply selectors:
11547: 
11548: @example
11549: button new Constant foo
11550: s" thin foo" foo init
11551: page
11552: foo draw
11553: bold-button new Constant bar
11554: s" fat bar" bar init
11555: 1 bar y !
11556: bar draw
11557: @end example
11558: 
11559: 
11560: @node Comparison with other object models,  , Mini-OOF, Object-oriented Forth
11561: @subsection Comparison with other object models
11562: @cindex comparison of object models
11563: @cindex object models, comparison
11564: 
11565: Many object-oriented Forth extensions have been proposed (@cite{A survey
11566: of object-oriented Forths} (SIGPLAN Notices, April 1996) by Bradford
11567: J. Rodriguez and W. F. S. Poehlman lists 17). This section discusses the
11568: relation of the object models described here to two well-known and two
11569: closely-related (by the use of method maps) models.  Andras Zsoter
11570: helped us with this section.
11571: 
11572: @cindex Neon model
11573: The most popular model currently seems to be the Neon model (see
11574: @cite{Object-oriented programming in ANS Forth} (Forth Dimensions, March
11575: 1997) by Andrew McKewan) but this model has a number of limitations
11576: @footnote{A longer version of this critique can be
11577: found in @cite{On Standardizing Object-Oriented Forth Extensions} (Forth
11578: Dimensions, May 1997) by Anton Ertl.}:
11579: 
11580: @itemize @bullet
11581: @item
11582: It uses a @code{@emph{selector object}} syntax, which makes it unnatural
11583: to pass objects on the stack.
11584: 
11585: @item
11586: It requires that the selector parses the input stream (at
11587: compile time); this leads to reduced extensibility and to bugs that are
11588: hard to find.
11589: 
11590: @item
11591: It allows using every selector on every object; this eliminates the
11592: need for interfaces, but makes it harder to create efficient
11593: implementations.
11594: @end itemize
11595: 
11596: @cindex Pountain's object-oriented model
11597: Another well-known publication is @cite{Object-Oriented Forth} (Academic
11598: Press, London, 1987) by Dick Pountain. However, it is not really about
11599: object-oriented programming, because it hardly deals with late
11600: binding. Instead, it focuses on features like information hiding and
11601: overloading that are characteristic of modular languages like Ada (83).
11602: 
11603: @cindex Zsoter's object-oriented model
11604: In @uref{http://www.forth.org/oopf.html, Does late binding have to be
11605: slow?} (Forth Dimensions 18(1) 1996, pages 31-35) Andras Zsoter
11606: describes a model that makes heavy use of an active object (like
11607: @code{this} in @file{objects.fs}): The active object is not only used
11608: for accessing all fields, but also specifies the receiving object of
11609: every selector invocation; you have to change the active object
11610: explicitly with @code{@{ ... @}}, whereas in @file{objects.fs} it
11611: changes more or less implicitly at @code{m: ... ;m}. Such a change at
11612: the method entry point is unnecessary with Zsoter's model, because the
11613: receiving object is the active object already. On the other hand, the
11614: explicit change is absolutely necessary in that model, because otherwise
11615: no one could ever change the active object. An ANS Forth implementation
11616: of this model is available through
11617: @uref{http://www.forth.org/oopf.html}.
11618: 
11619: @cindex @file{oof.fs}, differences to other models
11620: The @file{oof.fs} model combines information hiding and overloading
11621: resolution (by keeping names in various word lists) with object-oriented
11622: programming. It sets the active object implicitly on method entry, but
11623: also allows explicit changing (with @code{>o...o>} or with
11624: @code{with...endwith}). It uses parsing and state-smart objects and
11625: classes for resolving overloading and for early binding: the object or
11626: class parses the selector and determines the method from this. If the
11627: selector is not parsed by an object or class, it performs a call to the
11628: selector for the active object (late binding), like Zsoter's model.
11629: Fields are always accessed through the active object. The big
11630: disadvantage of this model is the parsing and the state-smartness, which
11631: reduces extensibility and increases the opportunities for subtle bugs;
11632: essentially, you are only safe if you never tick or @code{postpone} an
11633: object or class (Bernd disagrees, but I (Anton) am not convinced).
11634: 
11635: @cindex @file{mini-oof.fs}, differences to other models
11636: The @file{mini-oof.fs} model is quite similar to a very stripped-down
11637: version of the @file{objects.fs} model, but syntactically it is a
11638: mixture of the @file{objects.fs} and @file{oof.fs} models.
11639: 
11640: 
11641: @c -------------------------------------------------------------
11642: @node Programming Tools, C Interface, Object-oriented Forth, Words
11643: @section Programming Tools
11644: @cindex programming tools
11645: 
11646: @c !! move this and assembler down below OO stuff.
11647: 
11648: @menu
11649: * Examining::                   Data and Code.
11650: * Forgetting words::            Usually before reloading.
11651: * Debugging::                   Simple and quick.
11652: * Assertions::                  Making your programs self-checking.
11653: * Singlestep Debugger::         Executing your program word by word.
11654: @end menu
11655: 
11656: @node Examining, Forgetting words, Programming Tools, Programming Tools
11657: @subsection Examining data and code
11658: @cindex examining data and code
11659: @cindex data examination
11660: @cindex code examination
11661: 
11662: The following words inspect the stack non-destructively:
11663: 
11664: doc-.s
11665: doc-f.s
11666: doc-maxdepth-.s
11667: 
11668: There is a word @code{.r} but it does @i{not} display the return stack!
11669: It is used for formatted numeric output (@pxref{Simple numeric output}).
11670: 
11671: doc-depth
11672: doc-fdepth
11673: doc-clearstack
11674: doc-clearstacks
11675: 
11676: The following words inspect memory.
11677: 
11678: doc-?
11679: doc-dump
11680: 
11681: And finally, @code{see} allows to inspect code:
11682: 
11683: doc-see
11684: doc-xt-see
11685: doc-simple-see
11686: doc-simple-see-range
11687: doc-see-code
11688: doc-see-code-range
11689: 
11690: @node Forgetting words, Debugging, Examining, Programming Tools
11691: @subsection Forgetting words
11692: @cindex words, forgetting
11693: @cindex forgeting words
11694: 
11695: @c  anton: other, maybe better places for this subsection: Defining Words;
11696: @c  Dictionary allocation.  At least a reference should be there.
11697: 
11698: Forth allows you to forget words (and everything that was alloted in the
11699: dictonary after them) in a LIFO manner.
11700: 
11701: doc-marker
11702: 
11703: The most common use of this feature is during progam development: when
11704: you change a source file, forget all the words it defined and load it
11705: again (since you also forget everything defined after the source file
11706: was loaded, you have to reload that, too).  Note that effects like
11707: storing to variables and destroyed system words are not undone when you
11708: forget words.  With a system like Gforth, that is fast enough at
11709: starting up and compiling, I find it more convenient to exit and restart
11710: Gforth, as this gives me a clean slate.
11711: 
11712: Here's an example of using @code{marker} at the start of a source file
11713: that you are debugging; it ensures that you only ever have one copy of
11714: the file's definitions compiled at any time:
11715: 
11716: @example
11717: [IFDEF] my-code
11718:     my-code
11719: [ENDIF]
11720: 
11721: marker my-code
11722: init-included-files
11723: 
11724: \ .. definitions start here
11725: \ .
11726: \ .
11727: \ end
11728: @end example
11729: 
11730: 
11731: @node Debugging, Assertions, Forgetting words, Programming Tools
11732: @subsection Debugging
11733: @cindex debugging
11734: 
11735: Languages with a slow edit/compile/link/test development loop tend to
11736: require sophisticated tracing/stepping debuggers to facilate debugging.
11737: 
11738: A much better (faster) way in fast-compiling languages is to add
11739: printing code at well-selected places, let the program run, look at
11740: the output, see where things went wrong, add more printing code, etc.,
11741: until the bug is found.
11742: 
11743: The simple debugging aids provided in @file{debugs.fs}
11744: are meant to support this style of debugging.
11745: 
11746: The word @code{~~} prints debugging information (by default the source
11747: location and the stack contents). It is easy to insert. If you use Emacs
11748: it is also easy to remove (@kbd{C-x ~} in the Emacs Forth mode to
11749: query-replace them with nothing). The deferred words
11750: @code{printdebugdata} and @code{.debugline} control the output of
11751: @code{~~}. The default source location output format works well with
11752: Emacs' compilation mode, so you can step through the program at the
11753: source level using @kbd{C-x `} (the advantage over a stepping debugger
11754: is that you can step in any direction and you know where the crash has
11755: happened or where the strange data has occurred).
11756: 
11757: doc-~~
11758: doc-printdebugdata
11759: doc-.debugline
11760: 
11761: @cindex filenames in @code{~~} output
11762: @code{~~} (and assertions) will usually print the wrong file name if a
11763: marker is executed in the same file after their occurance.  They will
11764: print @samp{*somewhere*} as file name if a marker is executed in the
11765: same file before their occurance.
11766: 
11767: 
11768: @node Assertions, Singlestep Debugger, Debugging, Programming Tools
11769: @subsection Assertions
11770: @cindex assertions
11771: 
11772: It is a good idea to make your programs self-checking, especially if you
11773: make an assumption that may become invalid during maintenance (for
11774: example, that a certain field of a data structure is never zero). Gforth
11775: supports @dfn{assertions} for this purpose. They are used like this:
11776: 
11777: @example
11778: assert( @i{flag} )
11779: @end example
11780: 
11781: The code between @code{assert(} and @code{)} should compute a flag, that
11782: should be true if everything is alright and false otherwise. It should
11783: not change anything else on the stack. The overall stack effect of the
11784: assertion is @code{( -- )}. E.g.
11785: 
11786: @example
11787: assert( 1 1 + 2 = ) \ what we learn in school
11788: assert( dup 0<> ) \ assert that the top of stack is not zero
11789: assert( false ) \ this code should not be reached
11790: @end example
11791: 
11792: The need for assertions is different at different times. During
11793: debugging, we want more checking, in production we sometimes care more
11794: for speed. Therefore, assertions can be turned off, i.e., the assertion
11795: becomes a comment. Depending on the importance of an assertion and the
11796: time it takes to check it, you may want to turn off some assertions and
11797: keep others turned on. Gforth provides several levels of assertions for
11798: this purpose:
11799: 
11800: 
11801: doc-assert0(
11802: doc-assert1(
11803: doc-assert2(
11804: doc-assert3(
11805: doc-assert(
11806: doc-)
11807: 
11808: 
11809: The variable @code{assert-level} specifies the highest assertions that
11810: are turned on. I.e., at the default @code{assert-level} of one,
11811: @code{assert0(} and @code{assert1(} assertions perform checking, while
11812: @code{assert2(} and @code{assert3(} assertions are treated as comments.
11813: 
11814: The value of @code{assert-level} is evaluated at compile-time, not at
11815: run-time. Therefore you cannot turn assertions on or off at run-time;
11816: you have to set the @code{assert-level} appropriately before compiling a
11817: piece of code. You can compile different pieces of code at different
11818: @code{assert-level}s (e.g., a trusted library at level 1 and
11819: newly-written code at level 3).
11820: 
11821: 
11822: doc-assert-level
11823: 
11824: 
11825: If an assertion fails, a message compatible with Emacs' compilation mode
11826: is produced and the execution is aborted (currently with @code{ABORT"}.
11827: If there is interest, we will introduce a special throw code. But if you
11828: intend to @code{catch} a specific condition, using @code{throw} is
11829: probably more appropriate than an assertion).
11830: 
11831: @cindex filenames in assertion output
11832: Assertions (and @code{~~}) will usually print the wrong file name if a
11833: marker is executed in the same file after their occurance.  They will
11834: print @samp{*somewhere*} as file name if a marker is executed in the
11835: same file before their occurance.
11836: 
11837: Definitions in ANS Forth for these assertion words are provided
11838: in @file{compat/assert.fs}.
11839: 
11840: 
11841: @node Singlestep Debugger,  , Assertions, Programming Tools
11842: @subsection Singlestep Debugger
11843: @cindex singlestep Debugger
11844: @cindex debugging Singlestep
11845: 
11846: The singlestep debugger works only with the engine @code{gforth-ditc}.
11847: 
11848: When you create a new word there's often the need to check whether it
11849: behaves correctly or not. You can do this by typing @code{dbg
11850: badword}. A debug session might look like this:
11851: 
11852: @example
11853: : badword 0 DO i . LOOP ;  ok
11854: 2 dbg badword 
11855: : badword  
11856: Scanning code...
11857: 
11858: Nesting debugger ready!
11859: 
11860: 400D4738  8049BC4 0              -> [ 2 ] 00002 00000 
11861: 400D4740  8049F68 DO             -> [ 0 ] 
11862: 400D4744  804A0C8 i              -> [ 1 ] 00000 
11863: 400D4748 400C5E60 .              -> 0 [ 0 ] 
11864: 400D474C  8049D0C LOOP           -> [ 0 ] 
11865: 400D4744  804A0C8 i              -> [ 1 ] 00001 
11866: 400D4748 400C5E60 .              -> 1 [ 0 ] 
11867: 400D474C  8049D0C LOOP           -> [ 0 ] 
11868: 400D4758  804B384 ;              ->  ok
11869: @end example
11870: 
11871: Each line displayed is one step. You always have to hit return to
11872: execute the next word that is displayed. If you don't want to execute
11873: the next word in a whole, you have to type @kbd{n} for @code{nest}. Here is
11874: an overview what keys are available:
11875: 
11876: @table @i
11877: 
11878: @item @key{RET}
11879: Next; Execute the next word.
11880: 
11881: @item n
11882: Nest; Single step through next word.
11883: 
11884: @item u
11885: Unnest; Stop debugging and execute rest of word. If we got to this word
11886: with nest, continue debugging with the calling word.
11887: 
11888: @item d
11889: Done; Stop debugging and execute rest.
11890: 
11891: @item s
11892: Stop; Abort immediately.
11893: 
11894: @end table
11895: 
11896: Debugging large application with this mechanism is very difficult, because
11897: you have to nest very deeply into the program before the interesting part
11898: begins. This takes a lot of time. 
11899: 
11900: To do it more directly put a @code{BREAK:} command into your source code.
11901: When program execution reaches @code{BREAK:} the single step debugger is
11902: invoked and you have all the features described above.
11903: 
11904: If you have more than one part to debug it is useful to know where the
11905: program has stopped at the moment. You can do this by the 
11906: @code{BREAK" string"} command. This behaves like @code{BREAK:} except that
11907: string is typed out when the ``breakpoint'' is reached.
11908: 
11909: 
11910: doc-dbg
11911: doc-break:
11912: doc-break"
11913: 
11914: @c ------------------------------------------------------------
11915: @node C Interface, Assembler and Code Words, Programming Tools, Words
11916: @section C Interface
11917: @cindex C interface
11918: @cindex foreign language interface
11919: @cindex interface to C functions
11920: 
11921: Note that the C interface is not yet complete; callbacks are missing,
11922: as well as a way of declaring structs, unions, and their fields.
11923: 
11924: @menu
11925: * Calling C Functions::         
11926: * Declaring C Functions::       
11927: * Calling C function pointers::  
11928: * Callbacks::                   
11929: * C interface internals::       
11930: * Low-Level C Interface Words::  
11931: @end menu
11932: 
11933: @node Calling C Functions, Declaring C Functions, C Interface, C Interface
11934: @subsection Calling C functions
11935: @cindex C functions, calls to
11936: @cindex calling C functions
11937: 
11938: Once a C function is declared (see @pxref{Declaring C Functions}), you
11939: can call it as follows: You push the arguments on the stack(s), and
11940: then call the word for the C function.  The arguments have to be
11941: pushed in the same order as the arguments appear in the C
11942: documentation (i.e., the first argument is deepest on the stack).
11943: Integer and pointer arguments have to be pushed on the data stack,
11944: floating-point arguments on the FP stack; these arguments are consumed
11945: by the called C function.
11946: 
11947: On returning from the C function, the return value, if any, resides on
11948: the appropriate stack: an integer return value is pushed on the data
11949: stack, an FP return value on the FP stack, and a void return value
11950: results in not pushing anything.  Note that most C functions have a
11951: return value, even if that is often not used in C; in Forth, you have
11952: to @code{drop} this return value explicitly if you do not use it.
11953: 
11954: The C interface automatically converts between the C type and the
11955: Forth type as necessary, on a best-effort basis (in some cases, there
11956: may be some loss).
11957: 
11958: As an example, consider the POSIX function @code{lseek()}:
11959: 
11960: @example
11961: off_t lseek(int fd, off_t offset, int whence);
11962: @end example
11963: 
11964: This function takes three integer arguments, and returns an integer
11965: argument, so a Forth call for setting the current file offset to the
11966: start of the file could look like this:
11967: 
11968: @example
11969: fd @@ 0 SEEK_SET lseek -1 = if
11970:   ... \ error handling
11971: then
11972: @end example
11973: 
11974: You might be worried that an @code{off_t} does not fit into a cell, so
11975: you could not pass larger offsets to lseek, and might get only a part
11976: of the return values.  In that case, in your declaration of the
11977: function (@pxref{Declaring C Functions}) you should declare it to use
11978: double-cells for the off_t argument and return value, and maybe give
11979: the resulting Forth word a different name, like @code{dlseek}; the
11980: result could be called like this:
11981: 
11982: @example
11983: fd @@ 0. SEEK_SET dlseek -1. d= if
11984:   ... \ error handling
11985: then
11986: @end example
11987: 
11988: Passing and returning structs or unions is currently not supported by
11989: our interface@footnote{If you know the calling convention of your C
11990: compiler, you usually can call such functions in some way, but that
11991: way is usually not portable between platforms, and sometimes not even
11992: between C compilers.}.
11993: 
11994: Calling functions with a variable number of arguments (@emph{variadic}
11995: functions, e.g., @code{printf()}) is only supported by having you
11996: declare one function-calling word for each argument pattern, and
11997: calling the appropriate word for the desired pattern.
11998: 
11999: 
12000: 
12001: @node Declaring C Functions, Calling C function pointers, Calling C Functions, C Interface
12002: @subsection Declaring C Functions
12003: @cindex C functions, declarations
12004: @cindex declaring C functions
12005: 
12006: Before you can call @code{lseek} or @code{dlseek}, you have to declare
12007: it.  The declaration consists of two parts: 
12008: 
12009: @table @b
12010: 
12011: @item The C part
12012: is the C declaration of the function, or more typically and portably,
12013: a C-style @code{#include} of a file that contains the declaration of
12014: the C function.
12015: 
12016: @item The Forth part
12017: declares the Forth types of the parameters and the Forth word name
12018: corresponding to the C function.
12019: 
12020: @end table
12021: 
12022: For the words @code{lseek} and @code{dlseek} mentioned earlier, the
12023: declarations are:
12024: 
12025: @example
12026: \c #define _FILE_OFFSET_BITS 64
12027: \c #include <sys/types.h>
12028: \c #include <unistd.h>
12029: c-function lseek lseek n n n -- n
12030: c-function dlseek lseek n d n -- d
12031: @end example
12032: 
12033: The C part of the declarations is prefixed by @code{\c}, and the rest
12034: of the line is ordinary C code.  You can use as many lines of C
12035: declarations as you like, and they are visible for all further
12036: function declarations.
12037: 
12038: The Forth part declares each interface word with @code{c-function},
12039: followed by the Forth name of the word, the C name of the called
12040: function, and the stack effect of the word.  The stack effect contains
12041: an arbitrary number of types of parameters, then @code{--}, and then
12042: exactly one type for the return value.  The possible types are:
12043: 
12044: @table @code
12045: 
12046: @item n
12047: single-cell integer
12048: 
12049: @item a
12050: address (single-cell)
12051: 
12052: @item d
12053: double-cell integer
12054: 
12055: @item r
12056: floating-point value
12057: 
12058: @item func
12059: C function pointer
12060: 
12061: @item void
12062: no value (used as return type for void functions)
12063: 
12064: @end table
12065: 
12066: @cindex variadic C functions
12067: 
12068: To deal with variadic C functions, you can declare one Forth word for
12069: every pattern you want to use, e.g.:
12070: 
12071: @example
12072: \c #include <stdio.h>
12073: c-function printf-nr printf a n r -- n
12074: c-function printf-rn printf a r n -- n
12075: @end example
12076: 
12077: Note that with C functions declared as variadic (or if you don't
12078: provide a prototype), the C interface has no C type to convert to, so
12079: no automatic conversion happens, which may lead to portability
12080: problems in some cases.  In such cases you can perform the conversion
12081: explicitly on the C level, e.g., as follows:
12082: 
12083: @example
12084: \c #define printfll(s,ll) printf(s,(long long)ll)
12085: c-function printfll printfll a n -- n
12086: @end example
12087: 
12088: Here, instead of calling @code{printf()} directly, we define a macro
12089: that casts (converts) the Forth single-cell integer into a
12090: C @code{long long} before calling @code{printf()}.
12091: 
12092: doc-\c
12093: doc-c-function
12094: 
12095: In order to work, this C interface invokes GCC at run-time and uses
12096: dynamic linking.  If these features are not available, there are
12097: other, less convenient and less portable C interfaces in @file{lib.fs}
12098: and @file{oldlib.fs}.  These interfaces are mostly undocumented and
12099: mostly incompatible with each other and with the documented C
12100: interface; you can find some examples for the @file{lib.fs} interface
12101: in @file{lib.fs}.
12102: 
12103: 
12104: @node Calling C function pointers, Callbacks, Declaring C Functions, C Interface
12105: @subsection Calling C function pointers from Forth
12106: @cindex C function pointers, calling from Forth
12107: 
12108: If you come across a C function pointer (e.g., in some C-constructed
12109: structure) and want to call it from your Forth program, you can also
12110: use the features explained until now to achieve that, as follows:
12111: 
12112: Let us assume that there is a C function pointer type @code{func1}
12113: defined in some header file @file{func1.h}, and you know that these
12114: functions take one integer argument and return an integer result; and
12115: you want to call functions through such pointers.  Just define
12116: 
12117: @example
12118: \c #include <func1.h>
12119: \c #define call_func1(par1,fptr) ((func1)fptr)(par1)
12120: c-function call-func1 call_func1 n func -- n
12121: @end example
12122: 
12123: and then you can call a function pointed to by, say @code{func1a} as
12124: follows:
12125: 
12126: @example
12127: -5 func1a call-func1 .
12128: @end example
12129: 
12130: In the C part, @code{call_func} is defined as a macro to avoid having
12131: to declare the exact parameter and return types, so the C compiler
12132: knows them from the declaration of @code{func1}.
12133: 
12134: The Forth word @code{call-func1} is similar to @code{execute}, except
12135: that it takes a C @code{func1} pointer instead of a Forth execution
12136: token, and it is specific to @code{func1} pointers.  For each type of
12137: function pointer you want to call from Forth, you have to define
12138: a separate calling word.
12139: 
12140: 
12141: @node Callbacks, C interface internals, Calling C function pointers, C Interface
12142: @subsection Callbacks
12143: @cindex Callback functions written in Forth
12144: @cindex C function pointers to Forth words
12145: 
12146: Callbacks are not yet supported by the documented C interface.  You
12147: can use the undocumented @file{lib.fs} interface for callbacks.
12148: 
12149: In some cases you have to pass a function pointer to a C function,
12150: i.e., the library wants to call back to your application (and the
12151: pointed-to function is called a callback function).  You can pass the
12152: address of an existing C function (that you get with @code{lib-sym},
12153: @pxref{Low-Level C Interface Words}), but if there is no appropriate C
12154: function, you probably want to define the function as a Forth word.
12155: 
12156: @c I don't understand the existing callback interface from the example - anton
12157: 
12158: 
12159: @c > > Und dann gibt's noch die fptr-Deklaration, die einem
12160: @c > > C-Funktionspointer entspricht (Deklaration gleich wie bei
12161: @c > > Library-Funktionen, nur ohne den C-Namen, Aufruf mit der
12162: @c > > C-Funktionsadresse auf dem TOS).
12163: @c >
12164: @c > Ja, da bin ich dann ausgestiegen, weil ich aus dem Beispiel nicht
12165: @c > gesehen habe, wozu das gut ist.
12166: @c 
12167: @c Irgendwie muss ich den Callback ja testen. Und es soll ja auch 
12168: @c vorkommen, dass man von irgendwelchen kranken Interfaces einen 
12169: @c Funktionspointer übergeben bekommt, den man dann bei Gelegenheit 
12170: @c aufrufen muss. Also kann man den deklarieren, und das damit deklarierte 
12171: @c Wort verhält sich dann wie ein EXECUTE für alle C-Funktionen mit 
12172: @c demselben Prototyp.
12173: 
12174: 
12175: @node C interface internals, Low-Level C Interface Words, Callbacks, C Interface
12176: @subsection How the C interface works
12177: 
12178: The documented C interface works by generating a C code out of the
12179: declarations.
12180: 
12181: In particular, for every Forth word declared with @code{c-function},
12182: it generates a wrapper function in C that takes the Forth data from
12183: the Forth stacks, and calls the target C function with these data as
12184: arguments.  The C compiler then performs an implicit conversion
12185: between the Forth type from the stack, and the C type for the
12186: parameter, which is given by the C function prototype.  After the C
12187: function returns, the return value is likewise implicitly converted to
12188: a Forth type and written back on the stack.
12189: 
12190: The @code{\c} lines are literally included in the C code (but without
12191: the @code{\c}), and provide the necessary declarations so that the C
12192: compiler knows the C types and has enough information to perform the
12193: conversion.
12194: 
12195: These wrapper functions are eventually compiled and dynamically linked
12196: into Gforth, and then they can be called.
12197: 
12198: 
12199: @node Low-Level C Interface Words,  , C interface internals, C Interface
12200: @subsection Low-Level C Interface Words
12201: 
12202: doc-open-lib
12203: doc-lib-sym
12204: doc-call-c
12205: 
12206: @c -------------------------------------------------------------
12207: @node Assembler and Code Words, Threading Words, C Interface, Words
12208: @section Assembler and Code Words
12209: @cindex assembler
12210: @cindex code words
12211: 
12212: @menu
12213: * Code and ;code::              
12214: * Common Assembler::            Assembler Syntax
12215: * Common Disassembler::         
12216: * 386 Assembler::               Deviations and special cases
12217: * Alpha Assembler::             Deviations and special cases
12218: * MIPS assembler::              Deviations and special cases
12219: * PowerPC assembler::           Deviations and special cases
12220: * Other assemblers::            How to write them
12221: @end menu
12222: 
12223: @node Code and ;code, Common Assembler, Assembler and Code Words, Assembler and Code Words
12224: @subsection @code{Code} and @code{;code}
12225: 
12226: Gforth provides some words for defining primitives (words written in
12227: machine code), and for defining the machine-code equivalent of
12228: @code{DOES>}-based defining words. However, the machine-independent
12229: nature of Gforth poses a few problems: First of all, Gforth runs on
12230: several architectures, so it can provide no standard assembler. What's
12231: worse is that the register allocation not only depends on the processor,
12232: but also on the @code{gcc} version and options used.
12233: 
12234: The words that Gforth offers encapsulate some system dependences (e.g.,
12235: the header structure), so a system-independent assembler may be used in
12236: Gforth. If you do not have an assembler, you can compile machine code
12237: directly with @code{,} and @code{c,}@footnote{This isn't portable,
12238: because these words emit stuff in @i{data} space; it works because
12239: Gforth has unified code/data spaces. Assembler isn't likely to be
12240: portable anyway.}.
12241: 
12242: 
12243: doc-assembler
12244: doc-init-asm
12245: doc-code
12246: doc-end-code
12247: doc-;code
12248: doc-flush-icache
12249: 
12250: 
12251: If @code{flush-icache} does not work correctly, @code{code} words
12252: etc. will not work (reliably), either.
12253: 
12254: The typical usage of these @code{code} words can be shown most easily by
12255: analogy to the equivalent high-level defining words:
12256: 
12257: @example
12258: : foo                              code foo
12259:    <high-level Forth words>              <assembler>
12260: ;                                  end-code
12261:                                 
12262: : bar                              : bar
12263:    <high-level Forth words>           <high-level Forth words>
12264:    CREATE                             CREATE
12265:       <high-level Forth words>           <high-level Forth words>
12266:    DOES>                              ;code
12267:       <high-level Forth words>           <assembler>
12268: ;                                  end-code
12269: @end example
12270: 
12271: @c anton: the following stuff is also in "Common Assembler", in less detail.
12272: 
12273: @cindex registers of the inner interpreter
12274: In the assembly code you will want to refer to the inner interpreter's
12275: registers (e.g., the data stack pointer) and you may want to use other
12276: registers for temporary storage. Unfortunately, the register allocation
12277: is installation-dependent.
12278: 
12279: In particular, @code{ip} (Forth instruction pointer) and @code{rp}
12280: (return stack pointer) may be in different places in @code{gforth} and
12281: @code{gforth-fast}, or different installations.  This means that you
12282: cannot write a @code{NEXT} routine that works reliably on both versions
12283: or different installations; so for doing @code{NEXT}, I recommend
12284: jumping to @code{' noop >code-address}, which contains nothing but a
12285: @code{NEXT}.
12286: 
12287: For general accesses to the inner interpreter's registers, the easiest
12288: solution is to use explicit register declarations (@pxref{Explicit Reg
12289: Vars, , Variables in Specified Registers, gcc.info, GNU C Manual}) for
12290: all of the inner interpreter's registers: You have to compile Gforth
12291: with @code{-DFORCE_REG} (configure option @code{--enable-force-reg}) and
12292: the appropriate declarations must be present in the @code{machine.h}
12293: file (see @code{mips.h} for an example; you can find a full list of all
12294: declarable register symbols with @code{grep register engine.c}). If you
12295: give explicit registers to all variables that are declared at the
12296: beginning of @code{engine()}, you should be able to use the other
12297: caller-saved registers for temporary storage. Alternatively, you can use
12298: the @code{gcc} option @code{-ffixed-REG} (@pxref{Code Gen Options, ,
12299: Options for Code Generation Conventions, gcc.info, GNU C Manual}) to
12300: reserve a register (however, this restriction on register allocation may
12301: slow Gforth significantly).
12302: 
12303: If this solution is not viable (e.g., because @code{gcc} does not allow
12304: you to explicitly declare all the registers you need), you have to find
12305: out by looking at the code where the inner interpreter's registers
12306: reside and which registers can be used for temporary storage. You can
12307: get an assembly listing of the engine's code with @code{make engine.s}.
12308: 
12309: In any case, it is good practice to abstract your assembly code from the
12310: actual register allocation. E.g., if the data stack pointer resides in
12311: register @code{$17}, create an alias for this register called @code{sp},
12312: and use that in your assembly code.
12313: 
12314: @cindex code words, portable
12315: Another option for implementing normal and defining words efficiently
12316: is to add the desired functionality to the source of Gforth. For normal
12317: words you just have to edit @file{primitives} (@pxref{Automatic
12318: Generation}). Defining words (equivalent to @code{;CODE} words, for fast
12319: defined words) may require changes in @file{engine.c}, @file{kernel.fs},
12320: @file{prims2x.fs}, and possibly @file{cross.fs}.
12321: 
12322: @node Common Assembler, Common Disassembler, Code and ;code, Assembler and Code Words
12323: @subsection Common Assembler
12324: 
12325: The assemblers in Gforth generally use a postfix syntax, i.e., the
12326: instruction name follows the operands.
12327: 
12328: The operands are passed in the usual order (the same that is used in the
12329: manual of the architecture).  Since they all are Forth words, they have
12330: to be separated by spaces; you can also use Forth words to compute the
12331: operands.
12332: 
12333: The instruction names usually end with a @code{,}.  This makes it easier
12334: to visually separate instructions if you put several of them on one
12335: line; it also avoids shadowing other Forth words (e.g., @code{and}).
12336: 
12337: Registers are usually specified by number; e.g., (decimal) @code{11}
12338: specifies registers R11 and F11 on the Alpha architecture (which one,
12339: depends on the instruction).  The usual names are also available, e.g.,
12340: @code{s2} for R11 on Alpha.
12341: 
12342: Control flow is specified similar to normal Forth code (@pxref{Arbitrary
12343: control structures}), with @code{if,}, @code{ahead,}, @code{then,},
12344: @code{begin,}, @code{until,}, @code{again,}, @code{cs-roll},
12345: @code{cs-pick}, @code{else,}, @code{while,}, and @code{repeat,}.  The
12346: conditions are specified in a way specific to each assembler.
12347: 
12348: Note that the register assignments of the Gforth engine can change
12349: between Gforth versions, or even between different compilations of the
12350: same Gforth version (e.g., if you use a different GCC version).  So if
12351: you want to refer to Gforth's registers (e.g., the stack pointer or
12352: TOS), I recommend defining your own words for refering to these
12353: registers, and using them later on; then you can easily adapt to a
12354: changed register assignment.  The stability of the register assignment
12355: is usually better if you build Gforth with @code{--enable-force-reg}.
12356: 
12357: The most common use of these registers is to dispatch to the next word
12358: (the @code{next} routine).  A portable way to do this is to jump to
12359: @code{' noop >code-address} (of course, this is less efficient than
12360: integrating the @code{next} code and scheduling it well).
12361: 
12362: Another difference between Gforth version is that the top of stack is
12363: kept in memory in @code{gforth} and, on most platforms, in a register in
12364: @code{gforth-fast}.
12365: 
12366: @node  Common Disassembler, 386 Assembler, Common Assembler, Assembler and Code Words
12367: @subsection Common Disassembler
12368: @cindex disassembler, general
12369: @cindex gdb disassembler
12370: 
12371: You can disassemble a @code{code} word with @code{see}
12372: (@pxref{Debugging}).  You can disassemble a section of memory with
12373: 
12374: doc-discode
12375: 
12376: There are two kinds of disassembler for Gforth: The Forth disassembler
12377: (available on some CPUs) and the gdb disassembler (available on
12378: platforms with @command{gdb} and @command{mktemp}).  If both are
12379: available, the Forth disassembler is used by default.  If you prefer
12380: the gdb disassembler, say
12381: 
12382: @example
12383: ' disasm-gdb is discode
12384: @end example
12385: 
12386: If neither is available, @code{discode} performs @code{dump}.
12387: 
12388: The Forth disassembler generally produces output that can be fed into the
12389: assembler (i.e., same syntax, etc.).  It also includes additional
12390: information in comments.  In particular, the address of the instruction
12391: is given in a comment before the instruction.
12392: 
12393: The gdb disassembler produces output in the same format as the gdb
12394: @code{disassemble} command (@pxref{Machine Code,,Source and machine
12395: code,gdb,Debugging with GDB}), in the default flavour (AT&T syntax for
12396: the 386 and AMD64 architectures).
12397: 
12398: @code{See} may display more or less than the actual code of the word,
12399: because the recognition of the end of the code is unreliable.  You can
12400: use @code{discode} if it did not display enough.  It may display more, if
12401: the code word is not immediately followed by a named word.  If you have
12402: something else there, you can follow the word with @code{align latest ,}
12403: to ensure that the end is recognized.
12404: 
12405: @node 386 Assembler, Alpha Assembler, Common Disassembler, Assembler and Code Words
12406: @subsection 386 Assembler
12407: 
12408: The 386 assembler included in Gforth was written by Bernd Paysan, it's
12409: available under GPL, and originally part of bigFORTH.
12410: 
12411: The 386 disassembler included in Gforth was written by Andrew McKewan
12412: and is in the public domain.
12413: 
12414: The disassembler displays code in an Intel-like prefix syntax.
12415: 
12416: The assembler uses a postfix syntax with reversed parameters.
12417: 
12418: The assembler includes all instruction of the Athlon, i.e. 486 core
12419: instructions, Pentium and PPro extensions, floating point, MMX, 3Dnow!,
12420: but not ISSE. It's an integrated 16- and 32-bit assembler. Default is 32
12421: bit, you can switch to 16 bit with .86 and back to 32 bit with .386.
12422: 
12423: There are several prefixes to switch between different operation sizes,
12424: @code{.b} for byte accesses, @code{.w} for word accesses, @code{.d} for
12425: double-word accesses. Addressing modes can be switched with @code{.wa}
12426: for 16 bit addresses, and @code{.da} for 32 bit addresses. You don't
12427: need a prefix for byte register names (@code{AL} et al).
12428: 
12429: For floating point operations, the prefixes are @code{.fs} (IEEE
12430: single), @code{.fl} (IEEE double), @code{.fx} (extended), @code{.fw}
12431: (word), @code{.fd} (double-word), and @code{.fq} (quad-word).
12432: 
12433: The MMX opcodes don't have size prefixes, they are spelled out like in
12434: the Intel assembler. Instead of move from and to memory, there are
12435: PLDQ/PLDD and PSTQ/PSTD.
12436: 
12437: The registers lack the 'e' prefix; even in 32 bit mode, eax is called
12438: ax.  Immediate values are indicated by postfixing them with @code{#},
12439: e.g., @code{3 #}.  Here are some examples of addressing modes in various
12440: syntaxes:
12441: 
12442: @example
12443: Gforth          Intel (NASM)   AT&T (gas)      Name
12444: .w ax           ax             %ax             register (16 bit)
12445: ax              eax            %eax            register (32 bit)
12446: 3 #             offset 3       $3              immediate
12447: 1000 #)         byte ptr 1000  1000            displacement
12448: bx )            [ebx]          (%ebx)          base
12449: 100 di d)       100[edi]       100(%edi)       base+displacement
12450: 20 ax *4 i#)    20[eax*4]      20(,%eax,4)     (index*scale)+displacement
12451: di ax *4 i)     [edi][eax*4]   (%edi,%eax,4)   base+(index*scale)
12452: 4 bx cx di)     4[ebx][ecx]    4(%ebx,%ecx)    base+index+displacement
12453: 12 sp ax *2 di) 12[esp][eax*2] 12(%esp,%eax,2) base+(index*scale)+displacement
12454: @end example
12455: 
12456: You can use @code{L)} and @code{LI)} instead of @code{D)} and
12457: @code{DI)} to enforce 32-bit displacement fields (useful for
12458: later patching).
12459: 
12460: Some example of instructions are:
12461: 
12462: @example
12463: ax bx mov             \ move ebx,eax
12464: 3 # ax mov            \ mov eax,3
12465: 100 di d) ax mov      \ mov eax,100[edi]
12466: 4 bx cx di) ax mov    \ mov eax,4[ebx][ecx]
12467: .w ax bx mov          \ mov bx,ax
12468: @end example
12469: 
12470: The following forms are supported for binary instructions:
12471: 
12472: @example
12473: <reg> <reg> <inst>
12474: <n> # <reg> <inst>
12475: <mem> <reg> <inst>
12476: <reg> <mem> <inst>
12477: <n> # <mem> <inst>
12478: @end example
12479: 
12480: The shift/rotate syntax is:
12481: 
12482: @example
12483: <reg/mem> 1 # shl \ shortens to shift without immediate
12484: <reg/mem> 4 # shl
12485: <reg/mem> cl shl
12486: @end example
12487: 
12488: Precede string instructions (@code{movs} etc.) with @code{.b} to get
12489: the byte version.
12490: 
12491: The control structure words @code{IF} @code{UNTIL} etc. must be preceded
12492: by one of these conditions: @code{vs vc u< u>= 0= 0<> u<= u> 0< 0>= ps
12493: pc < >= <= >}. (Note that most of these words shadow some Forth words
12494: when @code{assembler} is in front of @code{forth} in the search path,
12495: e.g., in @code{code} words).  Currently the control structure words use
12496: one stack item, so you have to use @code{roll} instead of @code{cs-roll}
12497: to shuffle them (you can also use @code{swap} etc.).
12498: 
12499: Here is an example of a @code{code} word (assumes that the stack pointer
12500: is in esi and the TOS is in ebx):
12501: 
12502: @example
12503: code my+ ( n1 n2 -- n )
12504:     4 si D) bx add
12505:     4 # si add
12506:     Next
12507: end-code
12508: @end example
12509: 
12510: 
12511: @node Alpha Assembler, MIPS assembler, 386 Assembler, Assembler and Code Words
12512: @subsection Alpha Assembler
12513: 
12514: The Alpha assembler and disassembler were originally written by Bernd
12515: Thallner.
12516: 
12517: The register names @code{a0}--@code{a5} are not available to avoid
12518: shadowing hex numbers.
12519: 
12520: Immediate forms of arithmetic instructions are distinguished by a
12521: @code{#} just before the @code{,}, e.g., @code{and#,} (note: @code{lda,}
12522: does not count as arithmetic instruction).
12523: 
12524: You have to specify all operands to an instruction, even those that
12525: other assemblers consider optional, e.g., the destination register for
12526: @code{br,}, or the destination register and hint for @code{jmp,}.
12527: 
12528: You can specify conditions for @code{if,} by removing the first @code{b}
12529: and the trailing @code{,} from a branch with a corresponding name; e.g.,
12530: 
12531: @example
12532: 11 fgt if, \ if F11>0e
12533:   ...
12534: endif,
12535: @end example
12536: 
12537: @code{fbgt,} gives @code{fgt}.  
12538: 
12539: @node MIPS assembler, PowerPC assembler, Alpha Assembler, Assembler and Code Words
12540: @subsection MIPS assembler
12541: 
12542: The MIPS assembler was originally written by Christian Pirker.
12543: 
12544: Currently the assembler and disassembler only cover the MIPS-I
12545: architecture (R3000), and don't support FP instructions.
12546: 
12547: The register names @code{$a0}--@code{$a3} are not available to avoid
12548: shadowing hex numbers.
12549: 
12550: Because there is no way to distinguish registers from immediate values,
12551: you have to explicitly use the immediate forms of instructions, i.e.,
12552: @code{addiu,}, not just @code{addu,} (@command{as} does this
12553: implicitly).
12554: 
12555: If the architecture manual specifies several formats for the instruction
12556: (e.g., for @code{jalr,}), you usually have to use the one with more
12557: arguments (i.e., two for @code{jalr,}).  When in doubt, see
12558: @code{arch/mips/testasm.fs} for an example of correct use.
12559: 
12560: Branches and jumps in the MIPS architecture have a delay slot.  You have
12561: to fill it yourself (the simplest way is to use @code{nop,}), the
12562: assembler does not do it for you (unlike @command{as}).  Even
12563: @code{if,}, @code{ahead,}, @code{until,}, @code{again,}, @code{while,},
12564: @code{else,} and @code{repeat,} need a delay slot.  Since @code{begin,}
12565: and @code{then,} just specify branch targets, they are not affected.
12566: 
12567: Note that you must not put branches, jumps, or @code{li,} into the delay
12568: slot: @code{li,} may expand to several instructions, and control flow
12569: instructions may not be put into the branch delay slot in any case.
12570: 
12571: For branches the argument specifying the target is a relative address;
12572: You have to add the address of the delay slot to get the absolute
12573: address.
12574: 
12575: The MIPS architecture also has load delay slots and restrictions on
12576: using @code{mfhi,} and @code{mflo,}; you have to order the instructions
12577: yourself to satisfy these restrictions, the assembler does not do it for
12578: you.
12579: 
12580: You can specify the conditions for @code{if,} etc. by taking a
12581: conditional branch and leaving away the @code{b} at the start and the
12582: @code{,} at the end.  E.g.,
12583: 
12584: @example
12585: 4 5 eq if,
12586:   ... \ do something if $4 equals $5
12587: then,
12588: @end example
12589: 
12590: 
12591: @node PowerPC assembler, Other assemblers, MIPS assembler, Assembler and Code Words
12592: @subsection PowerPC assembler
12593: 
12594: The PowerPC assembler and disassembler were contributed by Michal
12595: Revucky.
12596: 
12597: This assembler does not follow the convention of ending mnemonic names
12598: with a ``,'', so some mnemonic names shadow regular Forth words (in
12599: particular: @code{and or xor fabs}); so if you want to use the Forth
12600: words, you have to make them visible first, e.g., with @code{also
12601: forth}.
12602: 
12603: Registers are referred to by their number, e.g., @code{9} means the
12604: integer register 9 or the FP register 9 (depending on the
12605: instruction).
12606: 
12607: Because there is no way to distinguish registers from immediate values,
12608: you have to explicitly use the immediate forms of instructions, i.e.,
12609: @code{addi,}, not just @code{add,}.
12610: 
12611: The assembler and disassembler usually support the most general form
12612: of an instruction, but usually not the shorter forms (especially for
12613: branches).
12614: 
12615: 
12616: 
12617: @node Other assemblers,  , PowerPC assembler, Assembler and Code Words
12618: @subsection Other assemblers
12619: 
12620: If you want to contribute another assembler/disassembler, please contact
12621: us (@email{anton@@mips.complang.tuwien.ac.at}) to check if we have such
12622: an assembler already.  If you are writing them from scratch, please use
12623: a similar syntax style as the one we use (i.e., postfix, commas at the
12624: end of the instruction names, @pxref{Common Assembler}); make the output
12625: of the disassembler be valid input for the assembler, and keep the style
12626: similar to the style we used.
12627: 
12628: Hints on implementation: The most important part is to have a good test
12629: suite that contains all instructions.  Once you have that, the rest is
12630: easy.  For actual coding you can take a look at
12631: @file{arch/mips/disasm.fs} to get some ideas on how to use data for both
12632: the assembler and disassembler, avoiding redundancy and some potential
12633: bugs.  You can also look at that file (and @pxref{Advanced does> usage
12634: example}) to get ideas how to factor a disassembler.
12635: 
12636: Start with the disassembler, because it's easier to reuse data from the
12637: disassembler for the assembler than the other way round.
12638: 
12639: For the assembler, take a look at @file{arch/alpha/asm.fs}, which shows
12640: how simple it can be.
12641: 
12642: 
12643: 
12644: 
12645: @c -------------------------------------------------------------
12646: @node Threading Words, Passing Commands to the OS, Assembler and Code Words, Words
12647: @section Threading Words
12648: @cindex threading words
12649: 
12650: @cindex code address
12651: These words provide access to code addresses and other threading stuff
12652: in Gforth (and, possibly, other interpretive Forths). It more or less
12653: abstracts away the differences between direct and indirect threading
12654: (and, for direct threading, the machine dependences). However, at
12655: present this wordset is still incomplete. It is also pretty low-level;
12656: some day it will hopefully be made unnecessary by an internals wordset
12657: that abstracts implementation details away completely.
12658: 
12659: The terminology used here stems from indirect threaded Forth systems; in
12660: such a system, the XT of a word is represented by the CFA (code field
12661: address) of a word; the CFA points to a cell that contains the code
12662: address.  The code address is the address of some machine code that
12663: performs the run-time action of invoking the word (e.g., the
12664: @code{dovar:} routine pushes the address of the body of the word (a
12665: variable) on the stack
12666: ).
12667: 
12668: @cindex code address
12669: @cindex code field address
12670: In an indirect threaded Forth, you can get the code address of @i{name}
12671: with @code{' @i{name} @@}; in Gforth you can get it with @code{' @i{name}
12672: >code-address}, independent of the threading method.
12673: 
12674: doc-threading-method
12675: doc->code-address
12676: doc-code-address!
12677: 
12678: @cindex @code{does>}-handler
12679: @cindex @code{does>}-code
12680: For a word defined with @code{DOES>}, the code address usually points to
12681: a jump instruction (the @dfn{does-handler}) that jumps to the dodoes
12682: routine (in Gforth on some platforms, it can also point to the dodoes
12683: routine itself).  What you are typically interested in, though, is
12684: whether a word is a @code{DOES>}-defined word, and what Forth code it
12685: executes; @code{>does-code} tells you that.
12686: 
12687: doc->does-code
12688: 
12689: To create a @code{DOES>}-defined word with the following basic words,
12690: you have to set up a @code{DOES>}-handler with @code{does-handler!};
12691: @code{/does-handler} aus behind you have to place your executable Forth
12692: code.  Finally you have to create a word and modify its behaviour with
12693: @code{does-handler!}.
12694: 
12695: doc-does-code!
12696: doc-does-handler!
12697: doc-/does-handler
12698: 
12699: The code addresses produced by various defining words are produced by
12700: the following words:
12701: 
12702: doc-docol:
12703: doc-docon:
12704: doc-dovar:
12705: doc-douser:
12706: doc-dodefer:
12707: doc-dofield:
12708: 
12709: @cindex definer
12710: The following two words generalize @code{>code-address},
12711: @code{>does-code}, @code{code-address!}, and @code{does-code!}:
12712: 
12713: doc->definer
12714: doc-definer!
12715: 
12716: @c -------------------------------------------------------------
12717: @node Passing Commands to the OS, Keeping track of Time, Threading Words, Words
12718: @section Passing Commands to the Operating System
12719: @cindex operating system - passing commands
12720: @cindex shell commands
12721: 
12722: Gforth allows you to pass an arbitrary string to the host operating
12723: system shell (if such a thing exists) for execution.
12724: 
12725: doc-sh
12726: doc-system
12727: doc-$?
12728: doc-getenv
12729: 
12730: @c -------------------------------------------------------------
12731: @node Keeping track of Time, Miscellaneous Words, Passing Commands to the OS, Words
12732: @section Keeping track of Time
12733: @cindex time-related words
12734: 
12735: doc-ms
12736: doc-time&date
12737: doc-utime
12738: doc-cputime
12739: 
12740: 
12741: @c -------------------------------------------------------------
12742: @node Miscellaneous Words,  , Keeping track of Time, Words
12743: @section Miscellaneous Words
12744: @cindex miscellaneous words
12745: 
12746: @comment TODO find homes for these
12747: 
12748: These section lists the ANS Forth words that are not documented
12749: elsewhere in this manual. Ultimately, they all need proper homes.
12750: 
12751: doc-quit
12752: 
12753: The following ANS Forth words are not currently supported by Gforth 
12754: (@pxref{ANS conformance}):
12755: 
12756: @code{EDITOR} 
12757: @code{EMIT?} 
12758: @code{FORGET} 
12759: 
12760: @c ******************************************************************
12761: @node Error messages, Tools, Words, Top
12762: @chapter Error messages
12763: @cindex error messages
12764: @cindex backtrace
12765: 
12766: A typical Gforth error message looks like this:
12767: 
12768: @example
12769: in file included from \evaluated string/:-1
12770: in file included from ./yyy.fs:1
12771: ./xxx.fs:4: Invalid memory address
12772: >>>bar<<<
12773: Backtrace:
12774: $400E664C @@
12775: $400E6664 foo
12776: @end example
12777: 
12778: The message identifying the error is @code{Invalid memory address}.  The
12779: error happened when text-interpreting line 4 of the file
12780: @file{./xxx.fs}. This line is given (it contains @code{bar}), and the
12781: word on the line where the error happened, is pointed out (with
12782: @code{>>>} and @code{<<<}).
12783: 
12784: The file containing the error was included in line 1 of @file{./yyy.fs},
12785: and @file{yyy.fs} was included from a non-file (in this case, by giving
12786: @file{yyy.fs} as command-line parameter to Gforth).
12787: 
12788: At the end of the error message you find a return stack dump that can be
12789: interpreted as a backtrace (possibly empty). On top you find the top of
12790: the return stack when the @code{throw} happened, and at the bottom you
12791: find the return stack entry just above the return stack of the topmost
12792: text interpreter.
12793: 
12794: To the right of most return stack entries you see a guess for the word
12795: that pushed that return stack entry as its return address. This gives a
12796: backtrace. In our case we see that @code{bar} called @code{foo}, and
12797: @code{foo} called @code{@@} (and @code{@@} had an @emph{Invalid memory
12798: address} exception).
12799: 
12800: Note that the backtrace is not perfect: We don't know which return stack
12801: entries are return addresses (so we may get false positives); and in
12802: some cases (e.g., for @code{abort"}) we cannot determine from the return
12803: address the word that pushed the return address, so for some return
12804: addresses you see no names in the return stack dump.
12805: 
12806: @cindex @code{catch} and backtraces
12807: The return stack dump represents the return stack at the time when a
12808: specific @code{throw} was executed.  In programs that make use of
12809: @code{catch}, it is not necessarily clear which @code{throw} should be
12810: used for the return stack dump (e.g., consider one @code{throw} that
12811: indicates an error, which is caught, and during recovery another error
12812: happens; which @code{throw} should be used for the stack dump?).
12813: Gforth presents the return stack dump for the first @code{throw} after
12814: the last executed (not returned-to) @code{catch} or @code{nothrow};
12815: this works well in the usual case. To get the right backtrace, you
12816: usually want to insert @code{nothrow} or @code{['] false catch drop}
12817: after a @code{catch} if the error is not rethrown.
12818: 
12819: @cindex @code{gforth-fast} and backtraces
12820: @cindex @code{gforth-fast}, difference from @code{gforth}
12821: @cindex backtraces with @code{gforth-fast}
12822: @cindex return stack dump with @code{gforth-fast}
12823: @code{Gforth} is able to do a return stack dump for throws generated
12824: from primitives (e.g., invalid memory address, stack empty etc.);
12825: @code{gforth-fast} is only able to do a return stack dump from a
12826: directly called @code{throw} (including @code{abort} etc.).  Given an
12827: exception caused by a primitive in @code{gforth-fast}, you will
12828: typically see no return stack dump at all; however, if the exception is
12829: caught by @code{catch} (e.g., for restoring some state), and then
12830: @code{throw}n again, the return stack dump will be for the first such
12831: @code{throw}.
12832: 
12833: @c ******************************************************************
12834: @node Tools, ANS conformance, Error messages, Top
12835: @chapter Tools
12836: 
12837: @menu
12838: * ANS Report::                  Report the words used, sorted by wordset.
12839: * Stack depth changes::         Where does this stack item come from?
12840: @end menu
12841: 
12842: See also @ref{Emacs and Gforth}.
12843: 
12844: @node ANS Report, Stack depth changes, Tools, Tools
12845: @section @file{ans-report.fs}: Report the words used, sorted by wordset
12846: @cindex @file{ans-report.fs}
12847: @cindex report the words used in your program
12848: @cindex words used in your program
12849: 
12850: If you want to label a Forth program as ANS Forth Program, you must
12851: document which wordsets the program uses; for extension wordsets, it is
12852: helpful to list the words the program requires from these wordsets
12853: (because Forth systems are allowed to provide only some words of them).
12854: 
12855: The @file{ans-report.fs} tool makes it easy for you to determine which
12856: words from which wordset and which non-ANS words your application
12857: uses. You simply have to include @file{ans-report.fs} before loading the
12858: program you want to check. After loading your program, you can get the
12859: report with @code{print-ans-report}. A typical use is to run this as
12860: batch job like this:
12861: @example
12862: gforth ans-report.fs myprog.fs -e "print-ans-report bye"
12863: @end example
12864: 
12865: The output looks like this (for @file{compat/control.fs}):
12866: @example
12867: The program uses the following words
12868: from CORE :
12869: : POSTPONE THEN ; immediate ?dup IF 0= 
12870: from BLOCK-EXT :
12871: \ 
12872: from FILE :
12873: ( 
12874: @end example
12875: 
12876: @subsection Caveats
12877: 
12878: Note that @file{ans-report.fs} just checks which words are used, not whether
12879: they are used in an ANS Forth conforming way!
12880: 
12881: Some words are defined in several wordsets in the
12882: standard. @file{ans-report.fs} reports them for only one of the
12883: wordsets, and not necessarily the one you expect. It depends on usage
12884: which wordset is the right one to specify. E.g., if you only use the
12885: compilation semantics of @code{S"}, it is a Core word; if you also use
12886: its interpretation semantics, it is a File word.
12887: 
12888: 
12889: @node Stack depth changes,  , ANS Report, Tools
12890: @section Stack depth changes during interpretation
12891: @cindex @file{depth-changes.fs}
12892: @cindex depth changes during interpretation
12893: @cindex stack depth changes during interpretation
12894: @cindex items on the stack after interpretation
12895: 
12896: Sometimes you notice that, after loading a file, there are items left
12897: on the stack.  The tool @file{depth-changes.fs} helps you find out
12898: quickly where in the file these stack items are coming from.
12899: 
12900: The simplest way of using @file{depth-changes.fs} is to include it
12901: before the file(s) you want to check, e.g.:
12902: 
12903: @example
12904: gforth depth-changes.fs my-file.fs
12905: @end example
12906: 
12907: This will compare the stack depths of the data and FP stack at every
12908: empty line (in interpretation state) against these depths at the last
12909: empty line (in interpretation state).  If the depths are not equal,
12910: the position in the file and the stack contents are printed with
12911: @code{~~} (@pxref{Debugging}).  This indicates that a stack depth
12912: change has occured in the paragraph of non-empty lines before the
12913: indicated line.  It is a good idea to leave an empty line at the end
12914: of the file, so the last paragraph is checked, too.
12915: 
12916: Checking only at empty lines usually works well, but sometimes you
12917: have big blocks of non-empty lines (e.g., when building a big table),
12918: and you want to know where in this block the stack depth changed.  You
12919: can check all interpreted lines with
12920: 
12921: @example
12922: gforth depth-changes.fs -e "' all-lines is depth-changes-filter" my-file.fs
12923: @end example
12924: 
12925: This checks the stack depth at every end-of-line.  So the depth change
12926: occured in the line reported by the @code{~~} (not in the line
12927: before).
12928: 
12929: Note that, while this offers better accuracy in indicating where the
12930: stack depth changes, it will often report many intentional stack depth
12931: changes (e.g., when an interpreted computation stretches across
12932: several lines).  You can suppress the checking of some lines by
12933: putting backslashes at the end of these lines (not followed by white
12934: space), and using
12935: 
12936: @example
12937: gforth depth-changes.fs -e "' most-lines is depth-changes-filter" my-file.fs
12938: @end example
12939: 
12940: @c ******************************************************************
12941: @node ANS conformance, Standard vs Extensions, Tools, Top
12942: @chapter ANS conformance
12943: @cindex ANS conformance of Gforth
12944: 
12945: To the best of our knowledge, Gforth is an
12946: 
12947: ANS Forth System
12948: @itemize @bullet
12949: @item providing the Core Extensions word set
12950: @item providing the Block word set
12951: @item providing the Block Extensions word set
12952: @item providing the Double-Number word set
12953: @item providing the Double-Number Extensions word set
12954: @item providing the Exception word set
12955: @item providing the Exception Extensions word set
12956: @item providing the Facility word set
12957: @item providing @code{EKEY}, @code{EKEY>CHAR}, @code{EKEY?}, @code{MS} and @code{TIME&DATE} from the Facility Extensions word set
12958: @item providing the File Access word set
12959: @item providing the File Access Extensions word set
12960: @item providing the Floating-Point word set
12961: @item providing the Floating-Point Extensions word set
12962: @item providing the Locals word set
12963: @item providing the Locals Extensions word set
12964: @item providing the Memory-Allocation word set
12965: @item providing the Memory-Allocation Extensions word set (that one's easy)
12966: @item providing the Programming-Tools word set
12967: @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
12968: @item providing the Search-Order word set
12969: @item providing the Search-Order Extensions word set
12970: @item providing the String word set
12971: @item providing the String Extensions word set (another easy one)
12972: @end itemize
12973: 
12974: Gforth has the following environmental restrictions:
12975: 
12976: @cindex environmental restrictions
12977: @itemize @bullet
12978: @item
12979: While processing the OS command line, if an exception is not caught,
12980: Gforth exits with a non-zero exit code instyead of performing QUIT.
12981: 
12982: @item
12983: When an @code{throw} is performed after a @code{query}, Gforth does not
12984: allways restore the input source specification in effect at the
12985: corresponding catch.
12986: 
12987: @end itemize
12988: 
12989: 
12990: @cindex system documentation
12991: In addition, ANS Forth systems are required to document certain
12992: implementation choices. This chapter tries to meet these
12993: requirements. In many cases it gives a way to ask the system for the
12994: information instead of providing the information directly, in
12995: particular, if the information depends on the processor, the operating
12996: system or the installation options chosen, or if they are likely to
12997: change during the maintenance of Gforth.
12998: 
12999: @comment The framework for the rest has been taken from pfe.
13000: 
13001: @menu
13002: * The Core Words::              
13003: * The optional Block word set::  
13004: * The optional Double Number word set::  
13005: * The optional Exception word set::  
13006: * The optional Facility word set::  
13007: * The optional File-Access word set::  
13008: * The optional Floating-Point word set::  
13009: * The optional Locals word set::  
13010: * The optional Memory-Allocation word set::  
13011: * The optional Programming-Tools word set::  
13012: * The optional Search-Order word set::  
13013: @end menu
13014: 
13015: 
13016: @c =====================================================================
13017: @node The Core Words, The optional Block word set, ANS conformance, ANS conformance
13018: @comment  node-name,  next,  previous,  up
13019: @section The Core Words
13020: @c =====================================================================
13021: @cindex core words, system documentation
13022: @cindex system documentation, core words
13023: 
13024: @menu
13025: * core-idef::                   Implementation Defined Options                   
13026: * core-ambcond::                Ambiguous Conditions                
13027: * core-other::                  Other System Documentation                  
13028: @end menu
13029: 
13030: @c ---------------------------------------------------------------------
13031: @node core-idef, core-ambcond, The Core Words, The Core Words
13032: @subsection Implementation Defined Options
13033: @c ---------------------------------------------------------------------
13034: @cindex core words, implementation-defined options
13035: @cindex implementation-defined options, core words
13036: 
13037: 
13038: @table @i
13039: @item (Cell) aligned addresses:
13040: @cindex cell-aligned addresses
13041: @cindex aligned addresses
13042: processor-dependent. Gforth's alignment words perform natural alignment
13043: (e.g., an address aligned for a datum of size 8 is divisible by
13044: 8). Unaligned accesses usually result in a @code{-23 THROW}.
13045: 
13046: @item @code{EMIT} and non-graphic characters:
13047: @cindex @code{EMIT} and non-graphic characters
13048: @cindex non-graphic characters and @code{EMIT}
13049: The character is output using the C library function (actually, macro)
13050: @code{putc}.
13051: 
13052: @item character editing of @code{ACCEPT} and @code{EXPECT}:
13053: @cindex character editing of @code{ACCEPT} and @code{EXPECT}
13054: @cindex editing in @code{ACCEPT} and @code{EXPECT}
13055: @cindex @code{ACCEPT}, editing
13056: @cindex @code{EXPECT}, editing
13057: This is modeled on the GNU readline library (@pxref{Readline
13058: Interaction, , Command Line Editing, readline, The GNU Readline
13059: Library}) with Emacs-like key bindings. @kbd{Tab} deviates a little by
13060: producing a full word completion every time you type it (instead of
13061: producing the common prefix of all completions). @xref{Command-line editing}.
13062: 
13063: @item character set:
13064: @cindex character set
13065: The character set of your computer and display device. Gforth is
13066: 8-bit-clean (but some other component in your system may make trouble).
13067: 
13068: @item Character-aligned address requirements:
13069: @cindex character-aligned address requirements
13070: installation-dependent. Currently a character is represented by a C
13071: @code{unsigned char}; in the future we might switch to @code{wchar_t}
13072: (Comments on that requested).
13073: 
13074: @item character-set extensions and matching of names:
13075: @cindex character-set extensions and matching of names
13076: @cindex case-sensitivity for name lookup
13077: @cindex name lookup, case-sensitivity
13078: @cindex locale and case-sensitivity
13079: Any character except the ASCII NUL character can be used in a
13080: name. Matching is case-insensitive (except in @code{TABLE}s). The
13081: matching is performed using the C library function @code{strncasecmp}, whose
13082: function is probably influenced by the locale. E.g., the @code{C} locale
13083: does not know about accents and umlauts, so they are matched
13084: case-sensitively in that locale. For portability reasons it is best to
13085: write programs such that they work in the @code{C} locale. Then one can
13086: use libraries written by a Polish programmer (who might use words
13087: containing ISO Latin-2 encoded characters) and by a French programmer
13088: (ISO Latin-1) in the same program (of course, @code{WORDS} will produce
13089: funny results for some of the words (which ones, depends on the font you
13090: are using)). Also, the locale you prefer may not be available in other
13091: operating systems. Hopefully, Unicode will solve these problems one day.
13092: 
13093: @item conditions under which control characters match a space delimiter:
13094: @cindex space delimiters
13095: @cindex control characters as delimiters
13096: If @code{word} is called with the space character as a delimiter, all
13097: white-space characters (as identified by the C macro @code{isspace()})
13098: are delimiters. @code{Parse}, on the other hand, treats space like other
13099: delimiters.  @code{Parse-name}, which is used by the outer
13100: interpreter (aka text interpreter) by default, treats all white-space
13101: characters as delimiters.
13102: 
13103: @item format of the control-flow stack:
13104: @cindex control-flow stack, format
13105: The data stack is used as control-flow stack. The size of a control-flow
13106: stack item in cells is given by the constant @code{cs-item-size}. At the
13107: time of this writing, an item consists of a (pointer to a) locals list
13108: (third), an address in the code (second), and a tag for identifying the
13109: item (TOS). The following tags are used: @code{defstart},
13110: @code{live-orig}, @code{dead-orig}, @code{dest}, @code{do-dest},
13111: @code{scopestart}.
13112: 
13113: @item conversion of digits > 35
13114: @cindex digits > 35
13115: The characters @code{[\]^_'} are the digits with the decimal value
13116: 36@minus{}41. There is no way to input many of the larger digits.
13117: 
13118: @item display after input terminates in @code{ACCEPT} and @code{EXPECT}:
13119: @cindex @code{EXPECT}, display after end of input
13120: @cindex @code{ACCEPT}, display after end of input
13121: The cursor is moved to the end of the entered string. If the input is
13122: terminated using the @kbd{Return} key, a space is typed.
13123: 
13124: @item exception abort sequence of @code{ABORT"}:
13125: @cindex exception abort sequence of @code{ABORT"}
13126: @cindex @code{ABORT"}, exception abort sequence
13127: The error string is stored into the variable @code{"error} and a
13128: @code{-2 throw} is performed.
13129: 
13130: @item input line terminator:
13131: @cindex input line terminator
13132: @cindex line terminator on input
13133: @cindex newline character on input
13134: For interactive input, @kbd{C-m} (CR) and @kbd{C-j} (LF) terminate
13135: lines. One of these characters is typically produced when you type the
13136: @kbd{Enter} or @kbd{Return} key.
13137: 
13138: @item maximum size of a counted string:
13139: @cindex maximum size of a counted string
13140: @cindex counted string, maximum size
13141: @code{s" /counted-string" environment? drop .}. Currently 255 characters
13142: on all platforms, but this may change.
13143: 
13144: @item maximum size of a parsed string:
13145: @cindex maximum size of a parsed string
13146: @cindex parsed string, maximum size
13147: Given by the constant @code{/line}. Currently 255 characters.
13148: 
13149: @item maximum size of a definition name, in characters:
13150: @cindex maximum size of a definition name, in characters
13151: @cindex name, maximum length
13152: MAXU/8
13153: 
13154: @item maximum string length for @code{ENVIRONMENT?}, in characters:
13155: @cindex maximum string length for @code{ENVIRONMENT?}, in characters
13156: @cindex @code{ENVIRONMENT?} string length, maximum
13157: MAXU/8
13158: 
13159: @item method of selecting the user input device:
13160: @cindex user input device, method of selecting
13161: The user input device is the standard input. There is currently no way to
13162: change it from within Gforth. However, the input can typically be
13163: redirected in the command line that starts Gforth.
13164: 
13165: @item method of selecting the user output device:
13166: @cindex user output device, method of selecting
13167: @code{EMIT} and @code{TYPE} output to the file-id stored in the value
13168: @code{outfile-id} (@code{stdout} by default). Gforth uses unbuffered
13169: output when the user output device is a terminal, otherwise the output
13170: is buffered.
13171: 
13172: @item methods of dictionary compilation:
13173: What are we expected to document here?
13174: 
13175: @item number of bits in one address unit:
13176: @cindex number of bits in one address unit
13177: @cindex address unit, size in bits
13178: @code{s" address-units-bits" environment? drop .}. 8 in all current
13179: platforms.
13180: 
13181: @item number representation and arithmetic:
13182: @cindex number representation and arithmetic
13183: Processor-dependent. Binary two's complement on all current platforms.
13184: 
13185: @item ranges for integer types:
13186: @cindex ranges for integer types
13187: @cindex integer types, ranges
13188: Installation-dependent. Make environmental queries for @code{MAX-N},
13189: @code{MAX-U}, @code{MAX-D} and @code{MAX-UD}. The lower bounds for
13190: unsigned (and positive) types is 0. The lower bound for signed types on
13191: two's complement and one's complement machines machines can be computed
13192: by adding 1 to the upper bound.
13193: 
13194: @item read-only data space regions:
13195: @cindex read-only data space regions
13196: @cindex data-space, read-only regions
13197: The whole Forth data space is writable.
13198: 
13199: @item size of buffer at @code{WORD}:
13200: @cindex size of buffer at @code{WORD}
13201: @cindex @code{WORD} buffer size
13202: @code{PAD HERE - .}. 104 characters on 32-bit machines. The buffer is
13203: shared with the pictured numeric output string. If overwriting
13204: @code{PAD} is acceptable, it is as large as the remaining dictionary
13205: space, although only as much can be sensibly used as fits in a counted
13206: string.
13207: 
13208: @item size of one cell in address units:
13209: @cindex cell size
13210: @code{1 cells .}.
13211: 
13212: @item size of one character in address units:
13213: @cindex char size
13214: @code{1 chars .}. 1 on all current platforms.
13215: 
13216: @item size of the keyboard terminal buffer:
13217: @cindex size of the keyboard terminal buffer
13218: @cindex terminal buffer, size
13219: Varies. You can determine the size at a specific time using @code{lp@@
13220: tib - .}. It is shared with the locals stack and TIBs of files that
13221: include the current file. You can change the amount of space for TIBs
13222: and locals stack at Gforth startup with the command line option
13223: @code{-l}.
13224: 
13225: @item size of the pictured numeric output buffer:
13226: @cindex size of the pictured numeric output buffer
13227: @cindex pictured numeric output buffer, size
13228: @code{PAD HERE - .}. 104 characters on 32-bit machines. The buffer is
13229: shared with @code{WORD}.
13230: 
13231: @item size of the scratch area returned by @code{PAD}:
13232: @cindex size of the scratch area returned by @code{PAD}
13233: @cindex @code{PAD} size
13234: The remainder of dictionary space. @code{unused pad here - - .}.
13235: 
13236: @item system case-sensitivity characteristics:
13237: @cindex case-sensitivity characteristics
13238: Dictionary searches are case-insensitive (except in
13239: @code{TABLE}s). However, as explained above under @i{character-set
13240: extensions}, the matching for non-ASCII characters is determined by the
13241: locale you are using. In the default @code{C} locale all non-ASCII
13242: characters are matched case-sensitively.
13243: 
13244: @item system prompt:
13245: @cindex system prompt
13246: @cindex prompt
13247: @code{ ok} in interpret state, @code{ compiled} in compile state.
13248: 
13249: @item division rounding:
13250: @cindex division rounding
13251: The ordinary division words @code{/ mod /mod */ */mod} perform floored
13252: division (with the default installation of Gforth).  You can check
13253: this with @code{s" floored" environment? drop .}.  If you write
13254: programs that need a specific division rounding, best use
13255: @code{fm/mod} or @code{sm/rem} for portability.
13256: 
13257: @item values of @code{STATE} when true:
13258: @cindex @code{STATE} values
13259: -1.
13260: 
13261: @item values returned after arithmetic overflow:
13262: On two's complement machines, arithmetic is performed modulo
13263: 2**bits-per-cell for single arithmetic and 4**bits-per-cell for double
13264: arithmetic (with appropriate mapping for signed types). Division by
13265: zero typically results in a @code{-55 throw} (Floating-point
13266: unidentified fault) or @code{-10 throw} (divide by zero).  Integer
13267: division overflow can result in these throws, or in @code{-11 throw};
13268: in @code{gforth-fast} division overflow and divide by zero may also
13269: result in returning bogus results without producing an exception.
13270: 
13271: @item whether the current definition can be found after @t{DOES>}:
13272: @cindex @t{DOES>}, visibility of current definition
13273: No.
13274: 
13275: @end table
13276: 
13277: @c ---------------------------------------------------------------------
13278: @node core-ambcond, core-other, core-idef, The Core Words
13279: @subsection Ambiguous conditions
13280: @c ---------------------------------------------------------------------
13281: @cindex core words, ambiguous conditions
13282: @cindex ambiguous conditions, core words
13283: 
13284: @table @i
13285: 
13286: @item a name is neither a word nor a number:
13287: @cindex name not found
13288: @cindex undefined word
13289: @code{-13 throw} (Undefined word).
13290: 
13291: @item a definition name exceeds the maximum length allowed:
13292: @cindex word name too long
13293: @code{-19 throw} (Word name too long)
13294: 
13295: @item addressing a region not inside the various data spaces of the forth system:
13296: @cindex Invalid memory address
13297: The stacks, code space and header space are accessible. Machine code space is
13298: typically readable. Accessing other addresses gives results dependent on
13299: the operating system. On decent systems: @code{-9 throw} (Invalid memory
13300: address).
13301: 
13302: @item argument type incompatible with parameter:
13303: @cindex argument type mismatch
13304: This is usually not caught. Some words perform checks, e.g., the control
13305: flow words, and issue a @code{ABORT"} or @code{-12 THROW} (Argument type
13306: mismatch).
13307: 
13308: @item attempting to obtain the execution token of a word with undefined execution semantics:
13309: @cindex Interpreting a compile-only word, for @code{'} etc.
13310: @cindex execution token of words with undefined execution semantics
13311: @code{-14 throw} (Interpreting a compile-only word). In some cases, you
13312: get an execution token for @code{compile-only-error} (which performs a
13313: @code{-14 throw} when executed).
13314: 
13315: @item dividing by zero:
13316: @cindex dividing by zero
13317: @cindex floating point unidentified fault, integer division
13318: On some platforms, this produces a @code{-10 throw} (Division by
13319: zero); on other systems, this typically results in a @code{-55 throw}
13320: (Floating-point unidentified fault).
13321: 
13322: @item insufficient data stack or return stack space:
13323: @cindex insufficient data stack or return stack space
13324: @cindex stack overflow
13325: @cindex address alignment exception, stack overflow
13326: @cindex Invalid memory address, stack overflow
13327: Depending on the operating system, the installation, and the invocation
13328: of Gforth, this is either checked by the memory management hardware, or
13329: it is not checked. If it is checked, you typically get a @code{-3 throw}
13330: (Stack overflow), @code{-5 throw} (Return stack overflow), or @code{-9
13331: throw} (Invalid memory address) (depending on the platform and how you
13332: achieved the overflow) as soon as the overflow happens. If it is not
13333: checked, overflows typically result in mysterious illegal memory
13334: accesses, producing @code{-9 throw} (Invalid memory address) or
13335: @code{-23 throw} (Address alignment exception); they might also destroy
13336: the internal data structure of @code{ALLOCATE} and friends, resulting in
13337: various errors in these words.
13338: 
13339: @item insufficient space for loop control parameters:
13340: @cindex insufficient space for loop control parameters
13341: Like other return stack overflows.
13342: 
13343: @item insufficient space in the dictionary:
13344: @cindex insufficient space in the dictionary
13345: @cindex dictionary overflow
13346: If you try to allot (either directly with @code{allot}, or indirectly
13347: with @code{,}, @code{create} etc.) more memory than available in the
13348: dictionary, you get a @code{-8 throw} (Dictionary overflow). If you try
13349: to access memory beyond the end of the dictionary, the results are
13350: similar to stack overflows.
13351: 
13352: @item interpreting a word with undefined interpretation semantics:
13353: @cindex interpreting a word with undefined interpretation semantics
13354: @cindex Interpreting a compile-only word
13355: For some words, we have defined interpretation semantics. For the
13356: others: @code{-14 throw} (Interpreting a compile-only word).
13357: 
13358: @item modifying the contents of the input buffer or a string literal:
13359: @cindex modifying the contents of the input buffer or a string literal
13360: These are located in writable memory and can be modified.
13361: 
13362: @item overflow of the pictured numeric output string:
13363: @cindex overflow of the pictured numeric output string
13364: @cindex pictured numeric output string, overflow
13365: @code{-17 throw} (Pictured numeric ouput string overflow).
13366: 
13367: @item parsed string overflow:
13368: @cindex parsed string overflow
13369: @code{PARSE} cannot overflow. @code{WORD} does not check for overflow.
13370: 
13371: @item producing a result out of range:
13372: @cindex result out of range
13373: On two's complement machines, arithmetic is performed modulo
13374: 2**bits-per-cell for single arithmetic and 4**bits-per-cell for double
13375: arithmetic (with appropriate mapping for signed types). Division by
13376: zero typically results in a @code{-10 throw} (divide by zero) or
13377: @code{-55 throw} (floating point unidentified fault). Overflow on
13378: division may result in these errors or in @code{-11 throw} (result out
13379: of range).  @code{Gforth-fast} may silently produce bogus results on
13380: division overflow or division by zero.  @code{Convert} and
13381: @code{>number} currently overflow silently.
13382: 
13383: @item reading from an empty data or return stack:
13384: @cindex stack empty
13385: @cindex stack underflow
13386: @cindex return stack underflow
13387: The data stack is checked by the outer (aka text) interpreter after
13388: every word executed. If it has underflowed, a @code{-4 throw} (Stack
13389: underflow) is performed. Apart from that, stacks may be checked or not,
13390: depending on operating system, installation, and invocation. If they are
13391: caught by a check, they typically result in @code{-4 throw} (Stack
13392: underflow), @code{-6 throw} (Return stack underflow) or @code{-9 throw}
13393: (Invalid memory address), depending on the platform and which stack
13394: underflows and by how much. Note that even if the system uses checking
13395: (through the MMU), your program may have to underflow by a significant
13396: number of stack items to trigger the reaction (the reason for this is
13397: that the MMU, and therefore the checking, works with a page-size
13398: granularity).  If there is no checking, the symptoms resulting from an
13399: underflow are similar to those from an overflow.  Unbalanced return
13400: stack errors can result in a variety of symptoms, including @code{-9 throw}
13401: (Invalid memory address) and Illegal Instruction (typically @code{-260
13402: throw}).
13403: 
13404: @item unexpected end of the input buffer, resulting in an attempt to use a zero-length string as a name:
13405: @cindex unexpected end of the input buffer
13406: @cindex zero-length string as a name
13407: @cindex Attempt to use zero-length string as a name
13408: @code{Create} and its descendants perform a @code{-16 throw} (Attempt to
13409: use zero-length string as a name). Words like @code{'} probably will not
13410: find what they search. Note that it is possible to create zero-length
13411: names with @code{nextname} (should it not?).
13412: 
13413: @item @code{>IN} greater than input buffer:
13414: @cindex @code{>IN} greater than input buffer
13415: The next invocation of a parsing word returns a string with length 0.
13416: 
13417: @item @code{RECURSE} appears after @code{DOES>}:
13418: @cindex @code{RECURSE} appears after @code{DOES>}
13419: Compiles a recursive call to the defining word, not to the defined word.
13420: 
13421: @item argument input source different than current input source for @code{RESTORE-INPUT}:
13422: @cindex argument input source different than current input source for @code{RESTORE-INPUT}
13423: @cindex argument type mismatch, @code{RESTORE-INPUT}
13424: @cindex @code{RESTORE-INPUT}, Argument type mismatch
13425: @code{-12 THROW}. Note that, once an input file is closed (e.g., because
13426: the end of the file was reached), its source-id may be
13427: reused. Therefore, restoring an input source specification referencing a
13428: closed file may lead to unpredictable results instead of a @code{-12
13429: THROW}.
13430: 
13431: In the future, Gforth may be able to restore input source specifications
13432: from other than the current input source.
13433: 
13434: @item data space containing definitions gets de-allocated:
13435: @cindex data space containing definitions gets de-allocated
13436: Deallocation with @code{allot} is not checked. This typically results in
13437: memory access faults or execution of illegal instructions.
13438: 
13439: @item data space read/write with incorrect alignment:
13440: @cindex data space read/write with incorrect alignment
13441: @cindex alignment faults
13442: @cindex address alignment exception
13443: Processor-dependent. Typically results in a @code{-23 throw} (Address
13444: alignment exception). Under Linux-Intel on a 486 or later processor with
13445: alignment turned on, incorrect alignment results in a @code{-9 throw}
13446: (Invalid memory address). There are reportedly some processors with
13447: alignment restrictions that do not report violations.
13448: 
13449: @item data space pointer not properly aligned, @code{,}, @code{C,}:
13450: @cindex data space pointer not properly aligned, @code{,}, @code{C,}
13451: Like other alignment errors.
13452: 
13453: @item less than u+2 stack items (@code{PICK} and @code{ROLL}):
13454: Like other stack underflows.
13455: 
13456: @item loop control parameters not available:
13457: @cindex loop control parameters not available
13458: Not checked. The counted loop words simply assume that the top of return
13459: stack items are loop control parameters and behave accordingly.
13460: 
13461: @item most recent definition does not have a name (@code{IMMEDIATE}):
13462: @cindex most recent definition does not have a name (@code{IMMEDIATE})
13463: @cindex last word was headerless
13464: @code{abort" last word was headerless"}.
13465: 
13466: @item name not defined by @code{VALUE} used by @code{TO}:
13467: @cindex name not defined by @code{VALUE} used by @code{TO}
13468: @cindex @code{TO} on non-@code{VALUE}s
13469: @cindex Invalid name argument, @code{TO}
13470: @code{-32 throw} (Invalid name argument) (unless name is a local or was
13471: defined by @code{CONSTANT}; in the latter case it just changes the constant).
13472: 
13473: @item name not found (@code{'}, @code{POSTPONE}, @code{[']}, @code{[COMPILE]}):
13474: @cindex name not found (@code{'}, @code{POSTPONE}, @code{[']}, @code{[COMPILE]})
13475: @cindex undefined word, @code{'}, @code{POSTPONE}, @code{[']}, @code{[COMPILE]}
13476: @code{-13 throw} (Undefined word)
13477: 
13478: @item parameters are not of the same type (@code{DO}, @code{?DO}, @code{WITHIN}):
13479: @cindex parameters are not of the same type (@code{DO}, @code{?DO}, @code{WITHIN})
13480: Gforth behaves as if they were of the same type. I.e., you can predict
13481: the behaviour by interpreting all parameters as, e.g., signed.
13482: 
13483: @item @code{POSTPONE} or @code{[COMPILE]} applied to @code{TO}:
13484: @cindex @code{POSTPONE} or @code{[COMPILE]} applied to @code{TO}
13485: Assume @code{: X POSTPONE TO ; IMMEDIATE}. @code{X} performs the
13486: compilation semantics of @code{TO}.
13487: 
13488: @item String longer than a counted string returned by @code{WORD}:
13489: @cindex string longer than a counted string returned by @code{WORD}
13490: @cindex @code{WORD}, string overflow
13491: Not checked. The string will be ok, but the count will, of course,
13492: contain only the least significant bits of the length.
13493: 
13494: @item u greater than or equal to the number of bits in a cell (@code{LSHIFT}, @code{RSHIFT}):
13495: @cindex @code{LSHIFT}, large shift counts
13496: @cindex @code{RSHIFT}, large shift counts
13497: Processor-dependent. Typical behaviours are returning 0 and using only
13498: the low bits of the shift count.
13499: 
13500: @item word not defined via @code{CREATE}:
13501: @cindex @code{>BODY} of non-@code{CREATE}d words
13502: @code{>BODY} produces the PFA of the word no matter how it was defined.
13503: 
13504: @cindex @code{DOES>} of non-@code{CREATE}d words
13505: @code{DOES>} changes the execution semantics of the last defined word no
13506: matter how it was defined. E.g., @code{CONSTANT DOES>} is equivalent to
13507: @code{CREATE , DOES>}.
13508: 
13509: @item words improperly used outside @code{<#} and @code{#>}:
13510: Not checked. As usual, you can expect memory faults.
13511: 
13512: @end table
13513: 
13514: 
13515: @c ---------------------------------------------------------------------
13516: @node core-other,  , core-ambcond, The Core Words
13517: @subsection Other system documentation
13518: @c ---------------------------------------------------------------------
13519: @cindex other system documentation, core words
13520: @cindex core words, other system documentation
13521: 
13522: @table @i
13523: @item nonstandard words using @code{PAD}:
13524: @cindex @code{PAD} use by nonstandard words
13525: None.
13526: 
13527: @item operator's terminal facilities available:
13528: @cindex operator's terminal facilities available
13529: After processing the OS's command line, Gforth goes into interactive mode,
13530: and you can give commands to Gforth interactively. The actual facilities
13531: available depend on how you invoke Gforth.
13532: 
13533: @item program data space available:
13534: @cindex program data space available
13535: @cindex data space available
13536: @code{UNUSED .} gives the remaining dictionary space. The total
13537: dictionary space can be specified with the @code{-m} switch
13538: (@pxref{Invoking Gforth}) when Gforth starts up.
13539: 
13540: @item return stack space available:
13541: @cindex return stack space available
13542: You can compute the total return stack space in cells with
13543: @code{s" RETURN-STACK-CELLS" environment? drop .}. You can specify it at
13544: startup time with the @code{-r} switch (@pxref{Invoking Gforth}).
13545: 
13546: @item stack space available:
13547: @cindex stack space available
13548: You can compute the total data stack space in cells with
13549: @code{s" STACK-CELLS" environment? drop .}. You can specify it at
13550: startup time with the @code{-d} switch (@pxref{Invoking Gforth}).
13551: 
13552: @item system dictionary space required, in address units:
13553: @cindex system dictionary space required, in address units
13554: Type @code{here forthstart - .} after startup. At the time of this
13555: writing, this gives 80080 (bytes) on a 32-bit system.
13556: @end table
13557: 
13558: 
13559: @c =====================================================================
13560: @node The optional Block word set, The optional Double Number word set, The Core Words, ANS conformance
13561: @section The optional Block word set
13562: @c =====================================================================
13563: @cindex system documentation, block words
13564: @cindex block words, system documentation
13565: 
13566: @menu
13567: * block-idef::                  Implementation Defined Options
13568: * block-ambcond::               Ambiguous Conditions               
13569: * block-other::                 Other System Documentation                 
13570: @end menu
13571: 
13572: 
13573: @c ---------------------------------------------------------------------
13574: @node block-idef, block-ambcond, The optional Block word set, The optional Block word set
13575: @subsection Implementation Defined Options
13576: @c ---------------------------------------------------------------------
13577: @cindex implementation-defined options, block words
13578: @cindex block words, implementation-defined options
13579: 
13580: @table @i
13581: @item the format for display by @code{LIST}:
13582: @cindex @code{LIST} display format
13583: First the screen number is displayed, then 16 lines of 64 characters,
13584: each line preceded by the line number.
13585: 
13586: @item the length of a line affected by @code{\}:
13587: @cindex length of a line affected by @code{\}
13588: @cindex @code{\}, line length in blocks
13589: 64 characters.
13590: @end table
13591: 
13592: 
13593: @c ---------------------------------------------------------------------
13594: @node block-ambcond, block-other, block-idef, The optional Block word set
13595: @subsection Ambiguous conditions
13596: @c ---------------------------------------------------------------------
13597: @cindex block words, ambiguous conditions
13598: @cindex ambiguous conditions, block words
13599: 
13600: @table @i
13601: @item correct block read was not possible:
13602: @cindex block read not possible
13603: Typically results in a @code{throw} of some OS-derived value (between
13604: -512 and -2048). If the blocks file was just not long enough, blanks are
13605: supplied for the missing portion.
13606: 
13607: @item I/O exception in block transfer:
13608: @cindex I/O exception in block transfer
13609: @cindex block transfer, I/O exception
13610: Typically results in a @code{throw} of some OS-derived value (between
13611: -512 and -2048).
13612: 
13613: @item invalid block number:
13614: @cindex invalid block number
13615: @cindex block number invalid
13616: @code{-35 throw} (Invalid block number)
13617: 
13618: @item a program directly alters the contents of @code{BLK}:
13619: @cindex @code{BLK}, altering @code{BLK}
13620: The input stream is switched to that other block, at the same
13621: position. If the storing to @code{BLK} happens when interpreting
13622: non-block input, the system will get quite confused when the block ends.
13623: 
13624: @item no current block buffer for @code{UPDATE}:
13625: @cindex @code{UPDATE}, no current block buffer
13626: @code{UPDATE} has no effect.
13627: 
13628: @end table
13629: 
13630: @c ---------------------------------------------------------------------
13631: @node block-other,  , block-ambcond, The optional Block word set
13632: @subsection Other system documentation
13633: @c ---------------------------------------------------------------------
13634: @cindex other system documentation, block words
13635: @cindex block words, other system documentation
13636: 
13637: @table @i
13638: @item any restrictions a multiprogramming system places on the use of buffer addresses:
13639: No restrictions (yet).
13640: 
13641: @item the number of blocks available for source and data:
13642: depends on your disk space.
13643: 
13644: @end table
13645: 
13646: 
13647: @c =====================================================================
13648: @node The optional Double Number word set, The optional Exception word set, The optional Block word set, ANS conformance
13649: @section The optional Double Number word set
13650: @c =====================================================================
13651: @cindex system documentation, double words
13652: @cindex double words, system documentation
13653: 
13654: @menu
13655: * double-ambcond::              Ambiguous Conditions              
13656: @end menu
13657: 
13658: 
13659: @c ---------------------------------------------------------------------
13660: @node double-ambcond,  , The optional Double Number word set, The optional Double Number word set
13661: @subsection Ambiguous conditions
13662: @c ---------------------------------------------------------------------
13663: @cindex double words, ambiguous conditions
13664: @cindex ambiguous conditions, double words
13665: 
13666: @table @i
13667: @item @i{d} outside of range of @i{n} in @code{D>S}:
13668: @cindex @code{D>S}, @i{d} out of range of @i{n} 
13669: The least significant cell of @i{d} is produced.
13670: 
13671: @end table
13672: 
13673: 
13674: @c =====================================================================
13675: @node The optional Exception word set, The optional Facility word set, The optional Double Number word set, ANS conformance
13676: @section The optional Exception word set
13677: @c =====================================================================
13678: @cindex system documentation, exception words
13679: @cindex exception words, system documentation
13680: 
13681: @menu
13682: * exception-idef::              Implementation Defined Options              
13683: @end menu
13684: 
13685: 
13686: @c ---------------------------------------------------------------------
13687: @node exception-idef,  , The optional Exception word set, The optional Exception word set
13688: @subsection Implementation Defined Options
13689: @c ---------------------------------------------------------------------
13690: @cindex implementation-defined options, exception words
13691: @cindex exception words, implementation-defined options
13692: 
13693: @table @i
13694: @item @code{THROW}-codes used in the system:
13695: @cindex @code{THROW}-codes used in the system
13696: The codes -256@minus{}-511 are used for reporting signals. The mapping
13697: from OS signal numbers to throw codes is -256@minus{}@i{signal}. The
13698: codes -512@minus{}-2047 are used for OS errors (for file and memory
13699: allocation operations). The mapping from OS error numbers to throw codes
13700: is -512@minus{}@code{errno}. One side effect of this mapping is that
13701: undefined OS errors produce a message with a strange number; e.g.,
13702: @code{-1000 THROW} results in @code{Unknown error 488} on my system.
13703: @end table
13704: 
13705: @c =====================================================================
13706: @node The optional Facility word set, The optional File-Access word set, The optional Exception word set, ANS conformance
13707: @section The optional Facility word set
13708: @c =====================================================================
13709: @cindex system documentation, facility words
13710: @cindex facility words, system documentation
13711: 
13712: @menu
13713: * facility-idef::               Implementation Defined Options               
13714: * facility-ambcond::            Ambiguous Conditions            
13715: @end menu
13716: 
13717: 
13718: @c ---------------------------------------------------------------------
13719: @node facility-idef, facility-ambcond, The optional Facility word set, The optional Facility word set
13720: @subsection Implementation Defined Options
13721: @c ---------------------------------------------------------------------
13722: @cindex implementation-defined options, facility words
13723: @cindex facility words, implementation-defined options
13724: 
13725: @table @i
13726: @item encoding of keyboard events (@code{EKEY}):
13727: @cindex keyboard events, encoding in @code{EKEY}
13728: @cindex @code{EKEY}, encoding of keyboard events
13729: Keys corresponding to ASCII characters are encoded as ASCII characters.
13730: Other keys are encoded with the constants @code{k-left}, @code{k-right},
13731: @code{k-up}, @code{k-down}, @code{k-home}, @code{k-end}, @code{k1},
13732: @code{k2}, @code{k3}, @code{k4}, @code{k5}, @code{k6}, @code{k7},
13733: @code{k8}, @code{k9}, @code{k10}, @code{k11}, @code{k12}.
13734: 
13735: 
13736: @item duration of a system clock tick:
13737: @cindex duration of a system clock tick
13738: @cindex clock tick duration
13739: System dependent. With respect to @code{MS}, the time is specified in
13740: microseconds. How well the OS and the hardware implement this, is
13741: another question.
13742: 
13743: @item repeatability to be expected from the execution of @code{MS}:
13744: @cindex repeatability to be expected from the execution of @code{MS}
13745: @cindex @code{MS}, repeatability to be expected
13746: System dependent. On Unix, a lot depends on load. If the system is
13747: lightly loaded, and the delay is short enough that Gforth does not get
13748: swapped out, the performance should be acceptable. Under MS-DOS and
13749: other single-tasking systems, it should be good.
13750: 
13751: @end table
13752: 
13753: 
13754: @c ---------------------------------------------------------------------
13755: @node facility-ambcond,  , facility-idef, The optional Facility word set
13756: @subsection Ambiguous conditions
13757: @c ---------------------------------------------------------------------
13758: @cindex facility words, ambiguous conditions
13759: @cindex ambiguous conditions, facility words
13760: 
13761: @table @i
13762: @item @code{AT-XY} can't be performed on user output device:
13763: @cindex @code{AT-XY} can't be performed on user output device
13764: Largely terminal dependent. No range checks are done on the arguments.
13765: No errors are reported. You may see some garbage appearing, you may see
13766: simply nothing happen.
13767: 
13768: @end table
13769: 
13770: 
13771: @c =====================================================================
13772: @node The optional File-Access word set, The optional Floating-Point word set, The optional Facility word set, ANS conformance
13773: @section The optional File-Access word set
13774: @c =====================================================================
13775: @cindex system documentation, file words
13776: @cindex file words, system documentation
13777: 
13778: @menu
13779: * file-idef::                   Implementation Defined Options
13780: * file-ambcond::                Ambiguous Conditions                
13781: @end menu
13782: 
13783: @c ---------------------------------------------------------------------
13784: @node file-idef, file-ambcond, The optional File-Access word set, The optional File-Access word set
13785: @subsection Implementation Defined Options
13786: @c ---------------------------------------------------------------------
13787: @cindex implementation-defined options, file words
13788: @cindex file words, implementation-defined options
13789: 
13790: @table @i
13791: @item file access methods used:
13792: @cindex file access methods used
13793: @code{R/O}, @code{R/W} and @code{BIN} work as you would
13794: expect. @code{W/O} translates into the C file opening mode @code{w} (or
13795: @code{wb}): The file is cleared, if it exists, and created, if it does
13796: not (with both @code{open-file} and @code{create-file}).  Under Unix
13797: @code{create-file} creates a file with 666 permissions modified by your
13798: umask.
13799: 
13800: @item file exceptions:
13801: @cindex file exceptions
13802: The file words do not raise exceptions (except, perhaps, memory access
13803: faults when you pass illegal addresses or file-ids).
13804: 
13805: @item file line terminator:
13806: @cindex file line terminator
13807: System-dependent. Gforth uses C's newline character as line
13808: terminator. What the actual character code(s) of this are is
13809: system-dependent.
13810: 
13811: @item file name format:
13812: @cindex file name format
13813: System dependent. Gforth just uses the file name format of your OS.
13814: 
13815: @item information returned by @code{FILE-STATUS}:
13816: @cindex @code{FILE-STATUS}, returned information
13817: @code{FILE-STATUS} returns the most powerful file access mode allowed
13818: for the file: Either @code{R/O}, @code{W/O} or @code{R/W}. If the file
13819: cannot be accessed, @code{R/O BIN} is returned. @code{BIN} is applicable
13820: along with the returned mode.
13821: 
13822: @item input file state after an exception when including source:
13823: @cindex exception when including source
13824: All files that are left via the exception are closed.
13825: 
13826: @item @i{ior} values and meaning:
13827: @cindex @i{ior} values and meaning
13828: @cindex @i{wior} values and meaning
13829: The @i{ior}s returned by the file and memory allocation words are
13830: intended as throw codes. They typically are in the range
13831: -512@minus{}-2047 of OS errors.  The mapping from OS error numbers to
13832: @i{ior}s is -512@minus{}@i{errno}.
13833: 
13834: @item maximum depth of file input nesting:
13835: @cindex maximum depth of file input nesting
13836: @cindex file input nesting, maximum depth
13837: limited by the amount of return stack, locals/TIB stack, and the number
13838: of open files available. This should not give you troubles.
13839: 
13840: @item maximum size of input line:
13841: @cindex maximum size of input line
13842: @cindex input line size, maximum
13843: @code{/line}. Currently 255.
13844: 
13845: @item methods of mapping block ranges to files:
13846: @cindex mapping block ranges to files
13847: @cindex files containing blocks
13848: @cindex blocks in files
13849: By default, blocks are accessed in the file @file{blocks.fb} in the
13850: current working directory. The file can be switched with @code{USE}.
13851: 
13852: @item number of string buffers provided by @code{S"}:
13853: @cindex @code{S"}, number of string buffers
13854: 1
13855: 
13856: @item size of string buffer used by @code{S"}:
13857: @cindex @code{S"}, size of string buffer
13858: @code{/line}. currently 255.
13859: 
13860: @end table
13861: 
13862: @c ---------------------------------------------------------------------
13863: @node file-ambcond,  , file-idef, The optional File-Access word set
13864: @subsection Ambiguous conditions
13865: @c ---------------------------------------------------------------------
13866: @cindex file words, ambiguous conditions
13867: @cindex ambiguous conditions, file words
13868: 
13869: @table @i
13870: @item attempting to position a file outside its boundaries:
13871: @cindex @code{REPOSITION-FILE}, outside the file's boundaries
13872: @code{REPOSITION-FILE} is performed as usual: Afterwards,
13873: @code{FILE-POSITION} returns the value given to @code{REPOSITION-FILE}.
13874: 
13875: @item attempting to read from file positions not yet written:
13876: @cindex reading from file positions not yet written
13877: End-of-file, i.e., zero characters are read and no error is reported.
13878: 
13879: @item @i{file-id} is invalid (@code{INCLUDE-FILE}):
13880: @cindex @code{INCLUDE-FILE}, @i{file-id} is invalid 
13881: An appropriate exception may be thrown, but a memory fault or other
13882: problem is more probable.
13883: 
13884: @item I/O exception reading or closing @i{file-id} (@code{INCLUDE-FILE}, @code{INCLUDED}):
13885: @cindex @code{INCLUDE-FILE}, I/O exception reading or closing @i{file-id}
13886: @cindex @code{INCLUDED}, I/O exception reading or closing @i{file-id}
13887: The @i{ior} produced by the operation, that discovered the problem, is
13888: thrown.
13889: 
13890: @item named file cannot be opened (@code{INCLUDED}):
13891: @cindex @code{INCLUDED}, named file cannot be opened
13892: The @i{ior} produced by @code{open-file} is thrown.
13893: 
13894: @item requesting an unmapped block number:
13895: @cindex unmapped block numbers
13896: There are no unmapped legal block numbers. On some operating systems,
13897: writing a block with a large number may overflow the file system and
13898: have an error message as consequence.
13899: 
13900: @item using @code{source-id} when @code{blk} is non-zero:
13901: @cindex @code{SOURCE-ID}, behaviour when @code{BLK} is non-zero
13902: @code{source-id} performs its function. Typically it will give the id of
13903: the source which loaded the block. (Better ideas?)
13904: 
13905: @end table
13906: 
13907: 
13908: @c =====================================================================
13909: @node  The optional Floating-Point word set, The optional Locals word set, The optional File-Access word set, ANS conformance
13910: @section The optional Floating-Point word set
13911: @c =====================================================================
13912: @cindex system documentation, floating-point words
13913: @cindex floating-point words, system documentation
13914: 
13915: @menu
13916: * floating-idef::               Implementation Defined Options
13917: * floating-ambcond::            Ambiguous Conditions            
13918: @end menu
13919: 
13920: 
13921: @c ---------------------------------------------------------------------
13922: @node floating-idef, floating-ambcond, The optional Floating-Point word set, The optional Floating-Point word set
13923: @subsection Implementation Defined Options
13924: @c ---------------------------------------------------------------------
13925: @cindex implementation-defined options, floating-point words
13926: @cindex floating-point words, implementation-defined options
13927: 
13928: @table @i
13929: @item format and range of floating point numbers:
13930: @cindex format and range of floating point numbers
13931: @cindex floating point numbers, format and range
13932: System-dependent; the @code{double} type of C.
13933: 
13934: @item results of @code{REPRESENT} when @i{float} is out of range:
13935: @cindex  @code{REPRESENT}, results when @i{float} is out of range
13936: System dependent; @code{REPRESENT} is implemented using the C library
13937: function @code{ecvt()} and inherits its behaviour in this respect.
13938: 
13939: @item rounding or truncation of floating-point numbers:
13940: @cindex rounding of floating-point numbers
13941: @cindex truncation of floating-point numbers
13942: @cindex floating-point numbers, rounding or truncation
13943: System dependent; the rounding behaviour is inherited from the hosting C
13944: compiler. IEEE-FP-based (i.e., most) systems by default round to
13945: nearest, and break ties by rounding to even (i.e., such that the last
13946: bit of the mantissa is 0).
13947: 
13948: @item size of floating-point stack:
13949: @cindex floating-point stack size
13950: @code{s" FLOATING-STACK" environment? drop .} gives the total size of
13951: the floating-point stack (in floats). You can specify this on startup
13952: with the command-line option @code{-f} (@pxref{Invoking Gforth}).
13953: 
13954: @item width of floating-point stack:
13955: @cindex floating-point stack width 
13956: @code{1 floats}.
13957: 
13958: @end table
13959: 
13960: 
13961: @c ---------------------------------------------------------------------
13962: @node floating-ambcond,  , floating-idef, The optional Floating-Point word set
13963: @subsection Ambiguous conditions
13964: @c ---------------------------------------------------------------------
13965: @cindex floating-point words, ambiguous conditions
13966: @cindex ambiguous conditions, floating-point words
13967: 
13968: @table @i
13969: @item @code{df@@} or @code{df!} used with an address that is not double-float  aligned:
13970: @cindex @code{df@@} or @code{df!} used with an address that is not double-float  aligned
13971: System-dependent. Typically results in a @code{-23 THROW} like other
13972: alignment violations.
13973: 
13974: @item @code{f@@} or @code{f!} used with an address that is not float  aligned:
13975: @cindex @code{f@@} used with an address that is not float aligned
13976: @cindex @code{f!} used with an address that is not float aligned
13977: System-dependent. Typically results in a @code{-23 THROW} like other
13978: alignment violations.
13979: 
13980: @item floating-point result out of range:
13981: @cindex floating-point result out of range
13982: System-dependent. Can result in a @code{-43 throw} (floating point
13983: overflow), @code{-54 throw} (floating point underflow), @code{-41 throw}
13984: (floating point inexact result), @code{-55 THROW} (Floating-point
13985: unidentified fault), or can produce a special value representing, e.g.,
13986: Infinity.
13987: 
13988: @item @code{sf@@} or @code{sf!} used with an address that is not single-float  aligned:
13989: @cindex @code{sf@@} or @code{sf!} used with an address that is not single-float  aligned
13990: System-dependent. Typically results in an alignment fault like other
13991: alignment violations.
13992: 
13993: @item @code{base} is not decimal (@code{REPRESENT}, @code{F.}, @code{FE.}, @code{FS.}):
13994: @cindex @code{base} is not decimal (@code{REPRESENT}, @code{F.}, @code{FE.}, @code{FS.})
13995: The floating-point number is converted into decimal nonetheless.
13996: 
13997: @item Both arguments are equal to zero (@code{FATAN2}):
13998: @cindex @code{FATAN2}, both arguments are equal to zero
13999: System-dependent. @code{FATAN2} is implemented using the C library
14000: function @code{atan2()}.
14001: 
14002: @item Using @code{FTAN} on an argument @i{r1} where cos(@i{r1}) is zero:
14003: @cindex @code{FTAN} on an argument @i{r1} where cos(@i{r1}) is zero
14004: System-dependent. Anyway, typically the cos of @i{r1} will not be zero
14005: because of small errors and the tan will be a very large (or very small)
14006: but finite number.
14007: 
14008: @item @i{d} cannot be presented precisely as a float in @code{D>F}:
14009: @cindex @code{D>F}, @i{d} cannot be presented precisely as a float
14010: The result is rounded to the nearest float.
14011: 
14012: @item dividing by zero:
14013: @cindex dividing by zero, floating-point
14014: @cindex floating-point dividing by zero
14015: @cindex floating-point unidentified fault, FP divide-by-zero
14016: Platform-dependent; can produce an Infinity, NaN, @code{-42 throw}
14017: (floating point divide by zero) or @code{-55 throw} (Floating-point
14018: unidentified fault).
14019: 
14020: @item exponent too big for conversion (@code{DF!}, @code{DF@@}, @code{SF!}, @code{SF@@}):
14021: @cindex exponent too big for conversion (@code{DF!}, @code{DF@@}, @code{SF!}, @code{SF@@})
14022: System dependent. On IEEE-FP based systems the number is converted into
14023: an infinity.
14024: 
14025: @item @i{float}<1 (@code{FACOSH}):
14026: @cindex @code{FACOSH}, @i{float}<1
14027: @cindex floating-point unidentified fault, @code{FACOSH}
14028: Platform-dependent; on IEEE-FP systems typically produces a NaN.
14029: 
14030: @item @i{float}=<-1 (@code{FLNP1}):
14031: @cindex @code{FLNP1}, @i{float}=<-1
14032: @cindex floating-point unidentified fault, @code{FLNP1}
14033: Platform-dependent; on IEEE-FP systems typically produces a NaN (or a
14034: negative infinity for @i{float}=-1).
14035: 
14036: @item @i{float}=<0 (@code{FLN}, @code{FLOG}):
14037: @cindex @code{FLN}, @i{float}=<0
14038: @cindex @code{FLOG}, @i{float}=<0
14039: @cindex floating-point unidentified fault, @code{FLN} or @code{FLOG}
14040: Platform-dependent; on IEEE-FP systems typically produces a NaN (or a
14041: negative infinity for @i{float}=0).
14042: 
14043: @item @i{float}<0 (@code{FASINH}, @code{FSQRT}):
14044: @cindex @code{FASINH}, @i{float}<0
14045: @cindex @code{FSQRT}, @i{float}<0
14046: @cindex floating-point unidentified fault, @code{FASINH} or @code{FSQRT}
14047: Platform-dependent; for @code{fsqrt} this typically gives a NaN, for
14048: @code{fasinh} some platforms produce a NaN, others a number (bug in the
14049: C library?).
14050: 
14051: @item |@i{float}|>1 (@code{FACOS}, @code{FASIN}, @code{FATANH}):
14052: @cindex @code{FACOS}, |@i{float}|>1
14053: @cindex @code{FASIN}, |@i{float}|>1
14054: @cindex @code{FATANH}, |@i{float}|>1
14055: @cindex floating-point unidentified fault, @code{FACOS}, @code{FASIN} or @code{FATANH}
14056: Platform-dependent; IEEE-FP systems typically produce a NaN.
14057: 
14058: @item integer part of float cannot be represented by @i{d} in @code{F>D}:
14059: @cindex @code{F>D}, integer part of float cannot be represented by @i{d}
14060: @cindex floating-point unidentified fault, @code{F>D}
14061: Platform-dependent; typically, some double number is produced and no
14062: error is reported.
14063: 
14064: @item string larger than pictured numeric output area (@code{f.}, @code{fe.}, @code{fs.}):
14065: @cindex string larger than pictured numeric output area (@code{f.}, @code{fe.}, @code{fs.})
14066: @code{Precision} characters of the numeric output area are used.  If
14067: @code{precision} is too high, these words will smash the data or code
14068: close to @code{here}.
14069: @end table
14070: 
14071: @c =====================================================================
14072: @node  The optional Locals word set, The optional Memory-Allocation word set, The optional Floating-Point word set, ANS conformance
14073: @section The optional Locals word set
14074: @c =====================================================================
14075: @cindex system documentation, locals words
14076: @cindex locals words, system documentation
14077: 
14078: @menu
14079: * locals-idef::                 Implementation Defined Options                 
14080: * locals-ambcond::              Ambiguous Conditions              
14081: @end menu
14082: 
14083: 
14084: @c ---------------------------------------------------------------------
14085: @node locals-idef, locals-ambcond, The optional Locals word set, The optional Locals word set
14086: @subsection Implementation Defined Options
14087: @c ---------------------------------------------------------------------
14088: @cindex implementation-defined options, locals words
14089: @cindex locals words, implementation-defined options
14090: 
14091: @table @i
14092: @item maximum number of locals in a definition:
14093: @cindex maximum number of locals in a definition
14094: @cindex locals, maximum number in a definition
14095: @code{s" #locals" environment? drop .}. Currently 15. This is a lower
14096: bound, e.g., on a 32-bit machine there can be 41 locals of up to 8
14097: characters. The number of locals in a definition is bounded by the size
14098: of locals-buffer, which contains the names of the locals.
14099: 
14100: @end table
14101: 
14102: 
14103: @c ---------------------------------------------------------------------
14104: @node locals-ambcond,  , locals-idef, The optional Locals word set
14105: @subsection Ambiguous conditions
14106: @c ---------------------------------------------------------------------
14107: @cindex locals words, ambiguous conditions
14108: @cindex ambiguous conditions, locals words
14109: 
14110: @table @i
14111: @item executing a named local in interpretation state:
14112: @cindex local in interpretation state
14113: @cindex Interpreting a compile-only word, for a local
14114: Locals have no interpretation semantics. If you try to perform the
14115: interpretation semantics, you will get a @code{-14 throw} somewhere
14116: (Interpreting a compile-only word). If you perform the compilation
14117: semantics, the locals access will be compiled (irrespective of state).
14118: 
14119: @item @i{name} not defined by @code{VALUE} or @code{(LOCAL)} (@code{TO}):
14120: @cindex name not defined by @code{VALUE} or @code{(LOCAL)} used by @code{TO}
14121: @cindex @code{TO} on non-@code{VALUE}s and non-locals
14122: @cindex Invalid name argument, @code{TO}
14123: @code{-32 throw} (Invalid name argument)
14124: 
14125: @end table
14126: 
14127: 
14128: @c =====================================================================
14129: @node  The optional Memory-Allocation word set, The optional Programming-Tools word set, The optional Locals word set, ANS conformance
14130: @section The optional Memory-Allocation word set
14131: @c =====================================================================
14132: @cindex system documentation, memory-allocation words
14133: @cindex memory-allocation words, system documentation
14134: 
14135: @menu
14136: * memory-idef::                 Implementation Defined Options                 
14137: @end menu
14138: 
14139: 
14140: @c ---------------------------------------------------------------------
14141: @node memory-idef,  , The optional Memory-Allocation word set, The optional Memory-Allocation word set
14142: @subsection Implementation Defined Options
14143: @c ---------------------------------------------------------------------
14144: @cindex implementation-defined options, memory-allocation words
14145: @cindex memory-allocation words, implementation-defined options
14146: 
14147: @table @i
14148: @item values and meaning of @i{ior}:
14149: @cindex  @i{ior} values and meaning
14150: The @i{ior}s returned by the file and memory allocation words are
14151: intended as throw codes. They typically are in the range
14152: -512@minus{}-2047 of OS errors.  The mapping from OS error numbers to
14153: @i{ior}s is -512@minus{}@i{errno}.
14154: 
14155: @end table
14156: 
14157: @c =====================================================================
14158: @node  The optional Programming-Tools word set, The optional Search-Order word set, The optional Memory-Allocation word set, ANS conformance
14159: @section The optional Programming-Tools word set
14160: @c =====================================================================
14161: @cindex system documentation, programming-tools words
14162: @cindex programming-tools words, system documentation
14163: 
14164: @menu
14165: * programming-idef::            Implementation Defined Options            
14166: * programming-ambcond::         Ambiguous Conditions         
14167: @end menu
14168: 
14169: 
14170: @c ---------------------------------------------------------------------
14171: @node programming-idef, programming-ambcond, The optional Programming-Tools word set, The optional Programming-Tools word set
14172: @subsection Implementation Defined Options
14173: @c ---------------------------------------------------------------------
14174: @cindex implementation-defined options, programming-tools words
14175: @cindex programming-tools words, implementation-defined options
14176: 
14177: @table @i
14178: @item ending sequence for input following @code{;CODE} and @code{CODE}:
14179: @cindex @code{;CODE} ending sequence
14180: @cindex @code{CODE} ending sequence
14181: @code{END-CODE}
14182: 
14183: @item manner of processing input following @code{;CODE} and @code{CODE}:
14184: @cindex @code{;CODE}, processing input
14185: @cindex @code{CODE}, processing input
14186: The @code{ASSEMBLER} vocabulary is pushed on the search order stack, and
14187: the input is processed by the text interpreter, (starting) in interpret
14188: state.
14189: 
14190: @item search order capability for @code{EDITOR} and @code{ASSEMBLER}:
14191: @cindex @code{ASSEMBLER}, search order capability
14192: The ANS Forth search order word set.
14193: 
14194: @item source and format of display by @code{SEE}:
14195: @cindex @code{SEE}, source and format of output
14196: The source for @code{see} is the executable code used by the inner
14197: interpreter.  The current @code{see} tries to output Forth source code
14198: (and on some platforms, assembly code for primitives) as well as
14199: possible.
14200: 
14201: @end table
14202: 
14203: @c ---------------------------------------------------------------------
14204: @node programming-ambcond,  , programming-idef, The optional Programming-Tools word set
14205: @subsection Ambiguous conditions
14206: @c ---------------------------------------------------------------------
14207: @cindex programming-tools words, ambiguous conditions
14208: @cindex ambiguous conditions, programming-tools words
14209: 
14210: @table @i
14211: 
14212: @item deleting the compilation word list (@code{FORGET}):
14213: @cindex @code{FORGET}, deleting the compilation word list
14214: Not implemented (yet).
14215: 
14216: @item fewer than @i{u}+1 items on the control-flow stack (@code{CS-PICK}, @code{CS-ROLL}):
14217: @cindex @code{CS-PICK}, fewer than @i{u}+1 items on the control flow-stack
14218: @cindex @code{CS-ROLL}, fewer than @i{u}+1 items on the control flow-stack
14219: @cindex control-flow stack underflow
14220: This typically results in an @code{abort"} with a descriptive error
14221: message (may change into a @code{-22 throw} (Control structure mismatch)
14222: in the future). You may also get a memory access error. If you are
14223: unlucky, this ambiguous condition is not caught.
14224: 
14225: @item @i{name} can't be found (@code{FORGET}):
14226: @cindex @code{FORGET}, @i{name} can't be found
14227: Not implemented (yet).
14228: 
14229: @item @i{name} not defined via @code{CREATE}:
14230: @cindex @code{;CODE}, @i{name} not defined via @code{CREATE}
14231: @code{;CODE} behaves like @code{DOES>} in this respect, i.e., it changes
14232: the execution semantics of the last defined word no matter how it was
14233: defined.
14234: 
14235: @item @code{POSTPONE} applied to @code{[IF]}:
14236: @cindex @code{POSTPONE} applied to @code{[IF]}
14237: @cindex @code{[IF]} and @code{POSTPONE}
14238: After defining @code{: X POSTPONE [IF] ; IMMEDIATE}. @code{X} is
14239: equivalent to @code{[IF]}.
14240: 
14241: @item reaching the end of the input source before matching @code{[ELSE]} or @code{[THEN]}:
14242: @cindex @code{[IF]}, end of the input source before matching @code{[ELSE]} or @code{[THEN]}
14243: Continue in the same state of conditional compilation in the next outer
14244: input source. Currently there is no warning to the user about this.
14245: 
14246: @item removing a needed definition (@code{FORGET}):
14247: @cindex @code{FORGET}, removing a needed definition
14248: Not implemented (yet).
14249: 
14250: @end table
14251: 
14252: 
14253: @c =====================================================================
14254: @node  The optional Search-Order word set,  , The optional Programming-Tools word set, ANS conformance
14255: @section The optional Search-Order word set
14256: @c =====================================================================
14257: @cindex system documentation, search-order words
14258: @cindex search-order words, system documentation
14259: 
14260: @menu
14261: * search-idef::                 Implementation Defined Options                 
14262: * search-ambcond::              Ambiguous Conditions              
14263: @end menu
14264: 
14265: 
14266: @c ---------------------------------------------------------------------
14267: @node search-idef, search-ambcond, The optional Search-Order word set, The optional Search-Order word set
14268: @subsection Implementation Defined Options
14269: @c ---------------------------------------------------------------------
14270: @cindex implementation-defined options, search-order words
14271: @cindex search-order words, implementation-defined options
14272: 
14273: @table @i
14274: @item maximum number of word lists in search order:
14275: @cindex maximum number of word lists in search order
14276: @cindex search order, maximum depth
14277: @code{s" wordlists" environment? drop .}. Currently 16.
14278: 
14279: @item minimum search order:
14280: @cindex minimum search order
14281: @cindex search order, minimum
14282: @code{root root}.
14283: 
14284: @end table
14285: 
14286: @c ---------------------------------------------------------------------
14287: @node search-ambcond,  , search-idef, The optional Search-Order word set
14288: @subsection Ambiguous conditions
14289: @c ---------------------------------------------------------------------
14290: @cindex search-order words, ambiguous conditions
14291: @cindex ambiguous conditions, search-order words
14292: 
14293: @table @i
14294: @item changing the compilation word list (during compilation):
14295: @cindex changing the compilation word list (during compilation)
14296: @cindex compilation word list, change before definition ends
14297: The word is entered into the word list that was the compilation word list
14298: at the start of the definition. Any changes to the name field (e.g.,
14299: @code{immediate}) or the code field (e.g., when executing @code{DOES>})
14300: are applied to the latest defined word (as reported by @code{latest} or
14301: @code{latestxt}), if possible, irrespective of the compilation word list.
14302: 
14303: @item search order empty (@code{previous}):
14304: @cindex @code{previous}, search order empty
14305: @cindex vocstack empty, @code{previous}
14306: @code{abort" Vocstack empty"}.
14307: 
14308: @item too many word lists in search order (@code{also}):
14309: @cindex @code{also}, too many word lists in search order
14310: @cindex vocstack full, @code{also}
14311: @code{abort" Vocstack full"}.
14312: 
14313: @end table
14314: 
14315: @c ***************************************************************
14316: @node Standard vs Extensions, Model, ANS conformance, Top
14317: @chapter Should I use Gforth extensions?
14318: @cindex Gforth extensions
14319: 
14320: As you read through the rest of this manual, you will see documentation
14321: for @i{Standard} words, and documentation for some appealing Gforth
14322: @i{extensions}. You might ask yourself the question: @i{``Should I
14323: restrict myself to the standard, or should I use the extensions?''}
14324: 
14325: The answer depends on the goals you have for the program you are working
14326: on:
14327: 
14328: @itemize @bullet
14329: 
14330: @item Is it just for yourself or do you want to share it with others?
14331: 
14332: @item
14333: If you want to share it, do the others all use Gforth?
14334: 
14335: @item
14336: If it is just for yourself, do you want to restrict yourself to Gforth?
14337: 
14338: @end itemize
14339: 
14340: If restricting the program to Gforth is ok, then there is no reason not
14341: to use extensions.  It is still a good idea to keep to the standard
14342: where it is easy, in case you want to reuse these parts in another
14343: program that you want to be portable.
14344: 
14345: If you want to be able to port the program to other Forth systems, there
14346: are the following points to consider:
14347: 
14348: @itemize @bullet
14349: 
14350: @item
14351: Most Forth systems that are being maintained support the ANS Forth
14352: standard.  So if your program complies with the standard, it will be
14353: portable among many systems.
14354: 
14355: @item
14356: A number of the Gforth extensions can be implemented in ANS Forth using
14357: public-domain files provided in the @file{compat/} directory. These are
14358: mentioned in the text in passing.  There is no reason not to use these
14359: extensions, your program will still be ANS Forth compliant; just include
14360: the appropriate compat files with your program.
14361: 
14362: @item
14363: The tool @file{ans-report.fs} (@pxref{ANS Report}) makes it easy to
14364: analyse your program and determine what non-Standard words it relies
14365: upon.  However, it does not check whether you use standard words in a
14366: non-standard way.
14367: 
14368: @item
14369: Some techniques are not standardized by ANS Forth, and are hard or
14370: impossible to implement in a standard way, but can be implemented in
14371: most Forth systems easily, and usually in similar ways (e.g., accessing
14372: word headers).  Forth has a rich historical precedent for programmers
14373: taking advantage of implementation-dependent features of their tools
14374: (for example, relying on a knowledge of the dictionary
14375: structure). Sometimes these techniques are necessary to extract every
14376: last bit of performance from the hardware, sometimes they are just a
14377: programming shorthand.
14378: 
14379: @item
14380: Does using a Gforth extension save more work than the porting this part
14381: to other Forth systems (if any) will cost?
14382: 
14383: @item
14384: Is the additional functionality worth the reduction in portability and
14385: the additional porting problems?
14386: 
14387: @end itemize
14388: 
14389: In order to perform these consideratios, you need to know what's
14390: standard and what's not.  This manual generally states if something is
14391: non-standard, but the authoritative source is the
14392: @uref{http://www.taygeta.com/forth/dpans.html,standard document}.
14393: Appendix A of the Standard (@var{Rationale}) provides a valuable insight
14394: into the thought processes of the technical committee.
14395: 
14396: Note also that portability between Forth systems is not the only
14397: portability issue; there is also the issue of portability between
14398: different platforms (processor/OS combinations).
14399: 
14400: @c ***************************************************************
14401: @node Model, Integrating Gforth, Standard vs Extensions, Top
14402: @chapter Model
14403: 
14404: This chapter has yet to be written. It will contain information, on
14405: which internal structures you can rely.
14406: 
14407: @c ***************************************************************
14408: @node Integrating Gforth, Emacs and Gforth, Model, Top
14409: @chapter Integrating Gforth into C programs
14410: 
14411: This is not yet implemented.
14412: 
14413: Several people like to use Forth as scripting language for applications
14414: that are otherwise written in C, C++, or some other language.
14415: 
14416: The Forth system ATLAST provides facilities for embedding it into
14417: applications; unfortunately it has several disadvantages: most
14418: importantly, it is not based on ANS Forth, and it is apparently dead
14419: (i.e., not developed further and not supported). The facilities
14420: provided by Gforth in this area are inspired by ATLAST's facilities, so
14421: making the switch should not be hard.
14422: 
14423: We also tried to design the interface such that it can easily be
14424: implemented by other Forth systems, so that we may one day arrive at a
14425: standardized interface. Such a standard interface would allow you to
14426: replace the Forth system without having to rewrite C code.
14427: 
14428: You embed the Gforth interpreter by linking with the library
14429: @code{libgforth.a} (give the compiler the option @code{-lgforth}).  All
14430: global symbols in this library that belong to the interface, have the
14431: prefix @code{forth_}. (Global symbols that are used internally have the
14432: prefix @code{gforth_}).
14433: 
14434: You can include the declarations of Forth types and the functions and
14435: variables of the interface with @code{#include <forth.h>}.
14436: 
14437: Types.
14438: 
14439: Variables.
14440: 
14441: Data and FP Stack pointer. Area sizes.
14442: 
14443: functions.
14444: 
14445: forth_init(imagefile)
14446: forth_evaluate(string) exceptions?
14447: forth_goto(address) (or forth_execute(xt)?)
14448: forth_continue() (a corountining mechanism)
14449: 
14450: Adding primitives.
14451: 
14452: No checking.
14453: 
14454: Signals?
14455: 
14456: Accessing the Stacks
14457: 
14458: @c ******************************************************************
14459: @node Emacs and Gforth, Image Files, Integrating Gforth, Top
14460: @chapter Emacs and Gforth
14461: @cindex Emacs and Gforth
14462: 
14463: @cindex @file{gforth.el}
14464: @cindex @file{forth.el}
14465: @cindex Rydqvist, Goran
14466: @cindex Kuehling, David
14467: @cindex comment editing commands
14468: @cindex @code{\}, editing with Emacs
14469: @cindex debug tracer editing commands
14470: @cindex @code{~~}, removal with Emacs
14471: @cindex Forth mode in Emacs
14472: 
14473: Gforth comes with @file{gforth.el}, an improved version of
14474: @file{forth.el} by Goran Rydqvist (included in the TILE package). The
14475: improvements are:
14476: 
14477: @itemize @bullet
14478: @item
14479: A better handling of indentation.
14480: @item
14481: A custom hilighting engine for Forth-code.
14482: @item
14483: Comment paragraph filling (@kbd{M-q})
14484: @item
14485: Commenting (@kbd{C-x \}) and uncommenting (@kbd{C-u C-x \}) of regions
14486: @item
14487: Removal of debugging tracers (@kbd{C-x ~}, @pxref{Debugging}).
14488: @item
14489: Support of the @code{info-lookup} feature for looking up the
14490: documentation of a word.
14491: @item
14492: Support for reading and writing blocks files.
14493: @end itemize
14494: 
14495: To get a basic description of these features, enter Forth mode and
14496: type @kbd{C-h m}.
14497: 
14498: @cindex source location of error or debugging output in Emacs
14499: @cindex error output, finding the source location in Emacs
14500: @cindex debugging output, finding the source location in Emacs
14501: In addition, Gforth supports Emacs quite well: The source code locations
14502: given in error messages, debugging output (from @code{~~}) and failed
14503: assertion messages are in the right format for Emacs' compilation mode
14504: (@pxref{Compilation, , Running Compilations under Emacs, emacs, Emacs
14505: Manual}) so the source location corresponding to an error or other
14506: message is only a few keystrokes away (@kbd{C-x `} for the next error,
14507: @kbd{C-c C-c} for the error under the cursor).
14508: 
14509: @cindex viewing the documentation of a word in Emacs
14510: @cindex context-sensitive help
14511: Moreover, for words documented in this manual, you can look up the
14512: glossary entry quickly by using @kbd{C-h TAB}
14513: (@code{info-lookup-symbol}, @pxref{Documentation, ,Documentation
14514: Commands, emacs, Emacs Manual}).  This feature requires Emacs 20.3 or
14515: later and does not work for words containing @code{:}.
14516: 
14517: @menu
14518: * Installing gforth.el::        Making Emacs aware of Forth.
14519: * Emacs Tags::                  Viewing the source of a word in Emacs.
14520: * Hilighting::                  Making Forth code look prettier.
14521: * Auto-Indentation::            Customizing auto-indentation.
14522: * Blocks Files::                Reading and writing blocks files.
14523: @end menu
14524: 
14525: @c ----------------------------------
14526: @node Installing gforth.el, Emacs Tags, Emacs and Gforth, Emacs and Gforth
14527: @section Installing gforth.el
14528: @cindex @file{.emacs}
14529: @cindex @file{gforth.el}, installation
14530: To make the features from @file{gforth.el} available in Emacs, add
14531: the following lines to your @file{.emacs} file:
14532: 
14533: @example
14534: (autoload 'forth-mode "gforth.el")
14535: (setq auto-mode-alist (cons '("\\.fs\\'" . forth-mode) 
14536: 			    auto-mode-alist))
14537: (autoload 'forth-block-mode "gforth.el")
14538: (setq auto-mode-alist (cons '("\\.fb\\'" . forth-block-mode) 
14539: 			    auto-mode-alist))
14540: (add-hook 'forth-mode-hook (function (lambda ()
14541:    ;; customize variables here:
14542:    (setq forth-indent-level 4)
14543:    (setq forth-minor-indent-level 2)
14544:    (setq forth-hilight-level 3)
14545:    ;;; ...
14546: )))
14547: @end example
14548: 
14549: @c ----------------------------------
14550: @node Emacs Tags, Hilighting, Installing gforth.el, Emacs and Gforth
14551: @section Emacs Tags
14552: @cindex @file{TAGS} file
14553: @cindex @file{etags.fs}
14554: @cindex viewing the source of a word in Emacs
14555: @cindex @code{require}, placement in files
14556: @cindex @code{include}, placement in files
14557: If you @code{require} @file{etags.fs}, a new @file{TAGS} file will be
14558: produced (@pxref{Tags, , Tags Tables, emacs, Emacs Manual}) that
14559: contains the definitions of all words defined afterwards. You can then
14560: find the source for a word using @kbd{M-.}. Note that Emacs can use
14561: several tags files at the same time (e.g., one for the Gforth sources
14562: and one for your program, @pxref{Select Tags Table,,Selecting a Tags
14563: Table,emacs, Emacs Manual}). The TAGS file for the preloaded words is
14564: @file{$(datadir)/gforth/$(VERSION)/TAGS} (e.g.,
14565: @file{/usr/local/share/gforth/0.2.0/TAGS}).  To get the best behaviour
14566: with @file{etags.fs}, you should avoid putting definitions both before
14567: and after @code{require} etc., otherwise you will see the same file
14568: visited several times by commands like @code{tags-search}.
14569: 
14570: @c ----------------------------------
14571: @node Hilighting, Auto-Indentation, Emacs Tags, Emacs and Gforth
14572: @section Hilighting
14573: @cindex hilighting Forth code in Emacs
14574: @cindex highlighting Forth code in Emacs
14575: @file{gforth.el} comes with a custom source hilighting engine.  When
14576: you open a file in @code{forth-mode}, it will be completely parsed,
14577: assigning faces to keywords, comments, strings etc.  While you edit
14578: the file, modified regions get parsed and updated on-the-fly. 
14579: 
14580: Use the variable `forth-hilight-level' to change the level of
14581: decoration from 0 (no hilighting at all) to 3 (the default).  Even if
14582: you set the hilighting level to 0, the parser will still work in the
14583: background, collecting information about whether regions of text are
14584: ``compiled'' or ``interpreted''.  Those information are required for
14585: auto-indentation to work properly.  Set `forth-disable-parser' to
14586: non-nil if your computer is too slow to handle parsing.  This will
14587: have an impact on the smartness of the auto-indentation engine,
14588: though.
14589: 
14590: Sometimes Forth sources define new features that should be hilighted,
14591: new control structures, defining-words etc.  You can use the variable
14592: `forth-custom-words' to make @code{forth-mode} hilight additional
14593: words and constructs.  See the docstring of `forth-words' for details
14594: (in Emacs, type @kbd{C-h v forth-words}).
14595: 
14596: `forth-custom-words' is meant to be customized in your
14597: @file{.emacs} file.  To customize hilighing in a file-specific manner,
14598: set `forth-local-words' in a local-variables section at the end of
14599: your source file (@pxref{Local Variables in Files,, Variables, emacs, Emacs Manual}).
14600: 
14601: Example:
14602: @example
14603: 0 [IF]
14604:    Local Variables:
14605:    forth-local-words:
14606:       ((("t:") definition-starter (font-lock-keyword-face . 1)
14607:         "[ \t\n]" t name (font-lock-function-name-face . 3))
14608:        ((";t") definition-ender (font-lock-keyword-face . 1)))
14609:    End:
14610: [THEN]
14611: @end example
14612: 
14613: @c ----------------------------------
14614: @node Auto-Indentation, Blocks Files, Hilighting, Emacs and Gforth
14615: @section Auto-Indentation
14616: @cindex auto-indentation of Forth code in Emacs
14617: @cindex indentation of Forth code in Emacs
14618: @code{forth-mode} automatically tries to indent lines in a smart way,
14619: whenever you type @key{TAB} or break a line with @kbd{C-m}.
14620: 
14621: Simple customization can be achieved by setting
14622: `forth-indent-level' and `forth-minor-indent-level' in your
14623: @file{.emacs} file. For historical reasons @file{gforth.el} indents
14624: per default by multiples of 4 columns.  To use the more traditional
14625: 3-column indentation, add the following lines to your @file{.emacs}:
14626: 
14627: @example
14628: (add-hook 'forth-mode-hook (function (lambda ()
14629:    ;; customize variables here:
14630:    (setq forth-indent-level 3)
14631:    (setq forth-minor-indent-level 1)
14632: )))
14633: @end example
14634: 
14635: If you want indentation to recognize non-default words, customize it
14636: by setting `forth-custom-indent-words' in your @file{.emacs}.  See the
14637: docstring of `forth-indent-words' for details (in Emacs, type @kbd{C-h
14638: v forth-indent-words}).
14639: 
14640: To customize indentation in a file-specific manner, set
14641: `forth-local-indent-words' in a local-variables section at the end of
14642: your source file (@pxref{Local Variables in Files, Variables,,emacs,
14643: Emacs Manual}).
14644: 
14645: Example:
14646: @example
14647: 0 [IF]
14648:    Local Variables:
14649:    forth-local-indent-words:
14650:       ((("t:") (0 . 2) (0 . 2))
14651:        ((";t") (-2 . 0) (0 . -2)))
14652:    End:
14653: [THEN]
14654: @end example
14655: 
14656: @c ----------------------------------
14657: @node Blocks Files,  , Auto-Indentation, Emacs and Gforth
14658: @section Blocks Files
14659: @cindex blocks files, use with Emacs
14660: @code{forth-mode} Autodetects blocks files by checking whether the
14661: length of the first line exceeds 1023 characters.  It then tries to
14662: convert the file into normal text format.  When you save the file, it
14663: will be written to disk as normal stream-source file.
14664: 
14665: If you want to write blocks files, use @code{forth-blocks-mode}.  It
14666: inherits all the features from @code{forth-mode}, plus some additions:
14667: 
14668: @itemize @bullet
14669: @item
14670: Files are written to disk in blocks file format.
14671: @item
14672: Screen numbers are displayed in the mode line (enumerated beginning
14673: with the value of `forth-block-base')
14674: @item
14675: Warnings are displayed when lines exceed 64 characters.
14676: @item
14677: The beginning of the currently edited block is marked with an
14678: overlay-arrow. 
14679: @end itemize
14680: 
14681: There are some restrictions you should be aware of.  When you open a
14682: blocks file that contains tabulator or newline characters, these
14683: characters will be translated into spaces when the file is written
14684: back to disk.  If tabs or newlines are encountered during blocks file
14685: reading, an error is output to the echo area. So have a look at the
14686: `*Messages*' buffer, when Emacs' bell rings during reading.
14687: 
14688: Please consult the docstring of @code{forth-blocks-mode} for more
14689: information by typing @kbd{C-h v forth-blocks-mode}).
14690: 
14691: @c ******************************************************************
14692: @node Image Files, Engine, Emacs and Gforth, Top
14693: @chapter Image Files
14694: @cindex image file
14695: @cindex @file{.fi} files
14696: @cindex precompiled Forth code
14697: @cindex dictionary in persistent form
14698: @cindex persistent form of dictionary
14699: 
14700: An image file is a file containing an image of the Forth dictionary,
14701: i.e., compiled Forth code and data residing in the dictionary.  By
14702: convention, we use the extension @code{.fi} for image files.
14703: 
14704: @menu
14705: * Image Licensing Issues::      Distribution terms for images.
14706: * Image File Background::       Why have image files?
14707: * Non-Relocatable Image Files::  don't always work.
14708: * Data-Relocatable Image Files::  are better.
14709: * Fully Relocatable Image Files::  better yet.
14710: * Stack and Dictionary Sizes::  Setting the default sizes for an image.
14711: * Running Image Files::         @code{gforth -i @i{file}} or @i{file}.
14712: * Modifying the Startup Sequence::  and turnkey applications.
14713: @end menu
14714: 
14715: @node Image Licensing Issues, Image File Background, Image Files, Image Files
14716: @section Image Licensing Issues
14717: @cindex license for images
14718: @cindex image license
14719: 
14720: An image created with @code{gforthmi} (@pxref{gforthmi}) or
14721: @code{savesystem} (@pxref{Non-Relocatable Image Files}) includes the
14722: original image; i.e., according to copyright law it is a derived work of
14723: the original image.
14724: 
14725: Since Gforth is distributed under the GNU GPL, the newly created image
14726: falls under the GNU GPL, too. In particular, this means that if you
14727: distribute the image, you have to make all of the sources for the image
14728: available, including those you wrote.  For details see @ref{Copying, ,
14729: GNU General Public License (Section 3)}.
14730: 
14731: If you create an image with @code{cross} (@pxref{cross.fs}), the image
14732: contains only code compiled from the sources you gave it; if none of
14733: these sources is under the GPL, the terms discussed above do not apply
14734: to the image. However, if your image needs an engine (a gforth binary)
14735: that is under the GPL, you should make sure that you distribute both in
14736: a way that is at most a @emph{mere aggregation}, if you don't want the
14737: terms of the GPL to apply to the image.
14738: 
14739: @node Image File Background, Non-Relocatable Image Files, Image Licensing Issues, Image Files
14740: @section Image File Background
14741: @cindex image file background
14742: 
14743: Gforth consists not only of primitives (in the engine), but also of
14744: definitions written in Forth. Since the Forth compiler itself belongs to
14745: those definitions, it is not possible to start the system with the
14746: engine and the Forth source alone. Therefore we provide the Forth
14747: code as an image file in nearly executable form. When Gforth starts up,
14748: a C routine loads the image file into memory, optionally relocates the
14749: addresses, then sets up the memory (stacks etc.) according to
14750: information in the image file, and (finally) starts executing Forth
14751: code.
14752: 
14753: The image file variants represent different compromises between the
14754: goals of making it easy to generate image files and making them
14755: portable.
14756: 
14757: @cindex relocation at run-time
14758: Win32Forth 3.4 and Mitch Bradley's @code{cforth} use relocation at
14759: run-time. This avoids many of the complications discussed below (image
14760: files are data relocatable without further ado), but costs performance
14761: (one addition per memory access).
14762: 
14763: @cindex relocation at load-time
14764: By contrast, the Gforth loader performs relocation at image load time. The
14765: loader also has to replace tokens that represent primitive calls with the
14766: appropriate code-field addresses (or code addresses in the case of
14767: direct threading).
14768: 
14769: There are three kinds of image files, with different degrees of
14770: relocatability: non-relocatable, data-relocatable, and fully relocatable
14771: image files.
14772: 
14773: @cindex image file loader
14774: @cindex relocating loader
14775: @cindex loader for image files
14776: These image file variants have several restrictions in common; they are
14777: caused by the design of the image file loader:
14778: 
14779: @itemize @bullet
14780: @item
14781: There is only one segment; in particular, this means, that an image file
14782: cannot represent @code{ALLOCATE}d memory chunks (and pointers to
14783: them). The contents of the stacks are not represented, either.
14784: 
14785: @item
14786: The only kinds of relocation supported are: adding the same offset to
14787: all cells that represent data addresses; and replacing special tokens
14788: with code addresses or with pieces of machine code.
14789: 
14790: If any complex computations involving addresses are performed, the
14791: results cannot be represented in the image file. Several applications that
14792: use such computations come to mind:
14793: @itemize @minus
14794: @item
14795: Hashing addresses (or data structures which contain addresses) for table
14796: lookup. If you use Gforth's @code{table}s or @code{wordlist}s for this
14797: purpose, you will have no problem, because the hash tables are
14798: recomputed automatically when the system is started. If you use your own
14799: hash tables, you will have to do something similar.
14800: 
14801: @item
14802: There's a cute implementation of doubly-linked lists that uses
14803: @code{XOR}ed addresses. You could represent such lists as singly-linked
14804: in the image file, and restore the doubly-linked representation on
14805: startup.@footnote{In my opinion, though, you should think thrice before
14806: using a doubly-linked list (whatever implementation).}
14807: 
14808: @item
14809: The code addresses of run-time routines like @code{docol:} cannot be
14810: represented in the image file (because their tokens would be replaced by
14811: machine code in direct threaded implementations). As a workaround,
14812: compute these addresses at run-time with @code{>code-address} from the
14813: executions tokens of appropriate words (see the definitions of
14814: @code{docol:} and friends in @file{kernel/getdoers.fs}).
14815: 
14816: @item
14817: On many architectures addresses are represented in machine code in some
14818: shifted or mangled form. You cannot put @code{CODE} words that contain
14819: absolute addresses in this form in a relocatable image file. Workarounds
14820: are representing the address in some relative form (e.g., relative to
14821: the CFA, which is present in some register), or loading the address from
14822: a place where it is stored in a non-mangled form.
14823: @end itemize
14824: @end itemize
14825: 
14826: @node  Non-Relocatable Image Files, Data-Relocatable Image Files, Image File Background, Image Files
14827: @section Non-Relocatable Image Files
14828: @cindex non-relocatable image files
14829: @cindex image file, non-relocatable
14830: 
14831: These files are simple memory dumps of the dictionary. They are specific
14832: to the executable (i.e., @file{gforth} file) they were created
14833: with. What's worse, they are specific to the place on which the
14834: dictionary resided when the image was created. Now, there is no
14835: guarantee that the dictionary will reside at the same place the next
14836: time you start Gforth, so there's no guarantee that a non-relocatable
14837: image will work the next time (Gforth will complain instead of crashing,
14838: though).
14839: 
14840: You can create a non-relocatable image file with
14841: 
14842: 
14843: doc-savesystem
14844: 
14845: 
14846: @node Data-Relocatable Image Files, Fully Relocatable Image Files, Non-Relocatable Image Files, Image Files
14847: @section Data-Relocatable Image Files
14848: @cindex data-relocatable image files
14849: @cindex image file, data-relocatable
14850: 
14851: These files contain relocatable data addresses, but fixed code addresses
14852: (instead of tokens). They are specific to the executable (i.e.,
14853: @file{gforth} file) they were created with. For direct threading on some
14854: architectures (e.g., the i386), data-relocatable images do not work. You
14855: get a data-relocatable image, if you use @file{gforthmi} with a
14856: Gforth binary that is not doubly indirect threaded (@pxref{Fully
14857: Relocatable Image Files}).
14858: 
14859: @node Fully Relocatable Image Files, Stack and Dictionary Sizes, Data-Relocatable Image Files, Image Files
14860: @section Fully Relocatable Image Files
14861: @cindex fully relocatable image files
14862: @cindex image file, fully relocatable
14863: 
14864: @cindex @file{kern*.fi}, relocatability
14865: @cindex @file{gforth.fi}, relocatability
14866: These image files have relocatable data addresses, and tokens for code
14867: addresses. They can be used with different binaries (e.g., with and
14868: without debugging) on the same machine, and even across machines with
14869: the same data formats (byte order, cell size, floating point
14870: format). However, they are usually specific to the version of Gforth
14871: they were created with. The files @file{gforth.fi} and @file{kernl*.fi}
14872: are fully relocatable.
14873: 
14874: There are two ways to create a fully relocatable image file:
14875: 
14876: @menu
14877: * gforthmi::                    The normal way
14878: * cross.fs::                    The hard way
14879: @end menu
14880: 
14881: @node gforthmi, cross.fs, Fully Relocatable Image Files, Fully Relocatable Image Files
14882: @subsection @file{gforthmi}
14883: @cindex @file{comp-i.fs}
14884: @cindex @file{gforthmi}
14885: 
14886: You will usually use @file{gforthmi}. If you want to create an
14887: image @i{file} that contains everything you would load by invoking
14888: Gforth with @code{gforth @i{options}}, you simply say:
14889: @example
14890: gforthmi @i{file} @i{options}
14891: @end example
14892: 
14893: E.g., if you want to create an image @file{asm.fi} that has the file
14894: @file{asm.fs} loaded in addition to the usual stuff, you could do it
14895: like this:
14896: 
14897: @example
14898: gforthmi asm.fi asm.fs
14899: @end example
14900: 
14901: @file{gforthmi} is implemented as a sh script and works like this: It
14902: produces two non-relocatable images for different addresses and then
14903: compares them. Its output reflects this: first you see the output (if
14904: any) of the two Gforth invocations that produce the non-relocatable image
14905: files, then you see the output of the comparing program: It displays the
14906: offset used for data addresses and the offset used for code addresses;
14907: moreover, for each cell that cannot be represented correctly in the
14908: image files, it displays a line like this:
14909: 
14910: @example
14911:      78DC         BFFFFA50         BFFFFA40
14912: @end example
14913: 
14914: This means that at offset $78dc from @code{forthstart}, one input image
14915: contains $bffffa50, and the other contains $bffffa40. Since these cells
14916: cannot be represented correctly in the output image, you should examine
14917: these places in the dictionary and verify that these cells are dead
14918: (i.e., not read before they are written).
14919: 
14920: @cindex --application, @code{gforthmi} option
14921: If you insert the option @code{--application} in front of the image file
14922: name, you will get an image that uses the @code{--appl-image} option
14923: instead of the @code{--image-file} option (@pxref{Invoking
14924: Gforth}). When you execute such an image on Unix (by typing the image
14925: name as command), the Gforth engine will pass all options to the image
14926: instead of trying to interpret them as engine options.
14927: 
14928: If you type @file{gforthmi} with no arguments, it prints some usage
14929: instructions.
14930: 
14931: @cindex @code{savesystem} during @file{gforthmi}
14932: @cindex @code{bye} during @file{gforthmi}
14933: @cindex doubly indirect threaded code
14934: @cindex environment variables
14935: @cindex @code{GFORTHD} -- environment variable
14936: @cindex @code{GFORTH} -- environment variable
14937: @cindex @code{gforth-ditc}
14938: There are a few wrinkles: After processing the passed @i{options}, the
14939: words @code{savesystem} and @code{bye} must be visible. A special doubly
14940: indirect threaded version of the @file{gforth} executable is used for
14941: creating the non-relocatable images; you can pass the exact filename of
14942: this executable through the environment variable @code{GFORTHD}
14943: (default: @file{gforth-ditc}); if you pass a version that is not doubly
14944: indirect threaded, you will not get a fully relocatable image, but a
14945: data-relocatable image (because there is no code address offset). The
14946: normal @file{gforth} executable is used for creating the relocatable
14947: image; you can pass the exact filename of this executable through the
14948: environment variable @code{GFORTH}.
14949: 
14950: @node cross.fs,  , gforthmi, Fully Relocatable Image Files
14951: @subsection @file{cross.fs}
14952: @cindex @file{cross.fs}
14953: @cindex cross-compiler
14954: @cindex metacompiler
14955: @cindex target compiler
14956: 
14957: You can also use @code{cross}, a batch compiler that accepts a Forth-like
14958: programming language (@pxref{Cross Compiler}).
14959: 
14960: @code{cross} allows you to create image files for machines with
14961: different data sizes and data formats than the one used for generating
14962: the image file. You can also use it to create an application image that
14963: does not contain a Forth compiler. These features are bought with
14964: restrictions and inconveniences in programming. E.g., addresses have to
14965: be stored in memory with special words (@code{A!}, @code{A,}, etc.) in
14966: order to make the code relocatable.
14967: 
14968: 
14969: @node Stack and Dictionary Sizes, Running Image Files, Fully Relocatable Image Files, Image Files
14970: @section Stack and Dictionary Sizes
14971: @cindex image file, stack and dictionary sizes
14972: @cindex dictionary size default
14973: @cindex stack size default
14974: 
14975: If you invoke Gforth with a command line flag for the size
14976: (@pxref{Invoking Gforth}), the size you specify is stored in the
14977: dictionary. If you save the dictionary with @code{savesystem} or create
14978: an image with @file{gforthmi}, this size will become the default
14979: for the resulting image file. E.g., the following will create a
14980: fully relocatable version of @file{gforth.fi} with a 1MB dictionary:
14981: 
14982: @example
14983: gforthmi gforth.fi -m 1M
14984: @end example
14985: 
14986: In other words, if you want to set the default size for the dictionary
14987: and the stacks of an image, just invoke @file{gforthmi} with the
14988: appropriate options when creating the image.
14989: 
14990: @cindex stack size, cache-friendly
14991: Note: For cache-friendly behaviour (i.e., good performance), you should
14992: make the sizes of the stacks modulo, say, 2K, somewhat different. E.g.,
14993: the default stack sizes are: data: 16k (mod 2k=0); fp: 15.5k (mod
14994: 2k=1.5k); return: 15k(mod 2k=1k); locals: 14.5k (mod 2k=0.5k).
14995: 
14996: @node Running Image Files, Modifying the Startup Sequence, Stack and Dictionary Sizes, Image Files
14997: @section Running Image Files
14998: @cindex running image files
14999: @cindex invoking image files
15000: @cindex image file invocation
15001: 
15002: @cindex -i, invoke image file
15003: @cindex --image file, invoke image file
15004: You can invoke Gforth with an image file @i{image} instead of the
15005: default @file{gforth.fi} with the @code{-i} flag (@pxref{Invoking Gforth}):
15006: @example
15007: gforth -i @i{image}
15008: @end example
15009: 
15010: @cindex executable image file
15011: @cindex image file, executable
15012: If your operating system supports starting scripts with a line of the
15013: form @code{#! ...}, you just have to type the image file name to start
15014: Gforth with this image file (note that the file extension @code{.fi} is
15015: just a convention). I.e., to run Gforth with the image file @i{image},
15016: you can just type @i{image} instead of @code{gforth -i @i{image}}.
15017: This works because every @code{.fi} file starts with a line of this
15018: format:
15019: 
15020: @example
15021: #! /usr/local/bin/gforth-0.4.0 -i
15022: @end example
15023: 
15024: The file and pathname for the Gforth engine specified on this line is
15025: the specific Gforth executable that it was built against; i.e. the value
15026: of the environment variable @code{GFORTH} at the time that
15027: @file{gforthmi} was executed.
15028: 
15029: You can make use of the same shell capability to make a Forth source
15030: file into an executable. For example, if you place this text in a file:
15031: 
15032: @example
15033: #! /usr/local/bin/gforth
15034: 
15035: ." Hello, world" CR
15036: bye
15037: @end example
15038: 
15039: @noindent
15040: and then make the file executable (chmod +x in Unix), you can run it
15041: directly from the command line. The sequence @code{#!} is used in two
15042: ways; firstly, it is recognised as a ``magic sequence'' by the operating
15043: system@footnote{The Unix kernel actually recognises two types of files:
15044: executable files and files of data, where the data is processed by an
15045: interpreter that is specified on the ``interpreter line'' -- the first
15046: line of the file, starting with the sequence #!. There may be a small
15047: limit (e.g., 32) on the number of characters that may be specified on
15048: the interpreter line.} secondly it is treated as a comment character by
15049: Gforth. Because of the second usage, a space is required between
15050: @code{#!} and the path to the executable (moreover, some Unixes
15051: require the sequence @code{#! /}).
15052: 
15053: The disadvantage of this latter technique, compared with using
15054: @file{gforthmi}, is that it is slightly slower; the Forth source code is
15055: compiled on-the-fly, each time the program is invoked.
15056: 
15057: doc-#!
15058: 
15059: 
15060: @node Modifying the Startup Sequence,  , Running Image Files, Image Files
15061: @section Modifying the Startup Sequence
15062: @cindex startup sequence for image file
15063: @cindex image file initialization sequence
15064: @cindex initialization sequence of image file
15065: 
15066: You can add your own initialization to the startup sequence of an image
15067: through the deferred word @code{'cold}. @code{'cold} is invoked just
15068: before the image-specific command line processing (i.e., loading files
15069: and evaluating (@code{-e}) strings) starts.
15070: 
15071: A sequence for adding your initialization usually looks like this:
15072: 
15073: @example
15074: :noname
15075:     Defers 'cold \ do other initialization stuff (e.g., rehashing wordlists)
15076:     ... \ your stuff
15077: ; IS 'cold
15078: @end example
15079: 
15080: After @code{'cold}, Gforth processes the image options
15081: (@pxref{Invoking Gforth}), and then it performs @code{bootmessage},
15082: another deferred word.  This normally prints Gforth's startup message
15083: and does nothing else.
15084: 
15085: @cindex turnkey image files
15086: @cindex image file, turnkey applications
15087: So, if you want to make a turnkey image (i.e., an image for an
15088: application instead of an extended Forth system), you can do this in
15089: two ways:
15090: 
15091: @itemize @bullet
15092: 
15093: @item
15094: If you want to do your interpretation of the OS command-line
15095: arguments, hook into @code{'cold}.  In that case you probably also
15096: want to build the image with @code{gforthmi --application}
15097: (@pxref{gforthmi}) to keep the engine from processing OS command line
15098: options.  You can then do your own command-line processing with
15099: @code{next-arg} 
15100: 
15101: @item
15102: If you want to have the normal Gforth processing of OS command-line
15103: arguments, hook into @code{bootmessage}.
15104: 
15105: @end itemize
15106: 
15107: In either case, you probably do not want the word that you execute in
15108: these hooks to exit normally, but use @code{bye} or @code{throw}.
15109: Otherwise the Gforth startup process would continue and eventually
15110: present the Forth command line to the user.
15111: 
15112: doc-'cold
15113: doc-bootmessage
15114: 
15115: @c ******************************************************************
15116: @node Engine, Cross Compiler, Image Files, Top
15117: @chapter Engine
15118: @cindex engine
15119: @cindex virtual machine
15120: 
15121: Reading this chapter is not necessary for programming with Gforth. It
15122: may be helpful for finding your way in the Gforth sources.
15123: 
15124: The ideas in this section have also been published in the following
15125: papers: Bernd Paysan, @cite{ANS fig/GNU/??? Forth} (in German),
15126: Forth-Tagung '93; M. Anton Ertl,
15127: @cite{@uref{http://www.complang.tuwien.ac.at/papers/ertl93.ps.Z, A
15128: Portable Forth Engine}}, EuroForth '93; M. Anton Ertl,
15129: @cite{@uref{http://www.complang.tuwien.ac.at/papers/ertl02.ps.gz,
15130: Threaded code variations and optimizations (extended version)}},
15131: Forth-Tagung '02.
15132: 
15133: @menu
15134: * Portability::                 
15135: * Threading::                   
15136: * Primitives::                  
15137: * Performance::                 
15138: @end menu
15139: 
15140: @node Portability, Threading, Engine, Engine
15141: @section Portability
15142: @cindex engine portability
15143: 
15144: An important goal of the Gforth Project is availability across a wide
15145: range of personal machines. fig-Forth, and, to a lesser extent, F83,
15146: achieved this goal by manually coding the engine in assembly language
15147: for several then-popular processors. This approach is very
15148: labor-intensive and the results are short-lived due to progress in
15149: computer architecture.
15150: 
15151: @cindex C, using C for the engine
15152: Others have avoided this problem by coding in C, e.g., Mitch Bradley
15153: (cforth), Mikael Patel (TILE) and Dirk Zoller (pfe). This approach is
15154: particularly popular for UNIX-based Forths due to the large variety of
15155: architectures of UNIX machines. Unfortunately an implementation in C
15156: does not mix well with the goals of efficiency and with using
15157: traditional techniques: Indirect or direct threading cannot be expressed
15158: in C, and switch threading, the fastest technique available in C, is
15159: significantly slower. Another problem with C is that it is very
15160: cumbersome to express double integer arithmetic.
15161: 
15162: @cindex GNU C for the engine
15163: @cindex long long
15164: Fortunately, there is a portable language that does not have these
15165: limitations: GNU C, the version of C processed by the GNU C compiler
15166: (@pxref{C Extensions, , Extensions to the C Language Family, gcc.info,
15167: GNU C Manual}). Its labels as values feature (@pxref{Labels as Values, ,
15168: Labels as Values, gcc.info, GNU C Manual}) makes direct and indirect
15169: threading possible, its @code{long long} type (@pxref{Long Long, ,
15170: Double-Word Integers, gcc.info, GNU C Manual}) corresponds to Forth's
15171: double numbers on many systems.  GNU C is freely available on all
15172: important (and many unimportant) UNIX machines, VMS, 80386s running
15173: MS-DOS, the Amiga, and the Atari ST, so a Forth written in GNU C can run
15174: on all these machines.
15175: 
15176: Writing in a portable language has the reputation of producing code that
15177: is slower than assembly. For our Forth engine we repeatedly looked at
15178: the code produced by the compiler and eliminated most compiler-induced
15179: inefficiencies by appropriate changes in the source code.
15180: 
15181: @cindex explicit register declarations
15182: @cindex --enable-force-reg, configuration flag
15183: @cindex -DFORCE_REG
15184: However, register allocation cannot be portably influenced by the
15185: programmer, leading to some inefficiencies on register-starved
15186: machines. We use explicit register declarations (@pxref{Explicit Reg
15187: Vars, , Variables in Specified Registers, gcc.info, GNU C Manual}) to
15188: improve the speed on some machines. They are turned on by using the
15189: configuration flag @code{--enable-force-reg} (@code{gcc} switch
15190: @code{-DFORCE_REG}). Unfortunately, this feature not only depends on the
15191: machine, but also on the compiler version: On some machines some
15192: compiler versions produce incorrect code when certain explicit register
15193: declarations are used. So by default @code{-DFORCE_REG} is not used.
15194: 
15195: @node Threading, Primitives, Portability, Engine
15196: @section Threading
15197: @cindex inner interpreter implementation
15198: @cindex threaded code implementation
15199: 
15200: @cindex labels as values
15201: GNU C's labels as values extension (available since @code{gcc-2.0},
15202: @pxref{Labels as Values, , Labels as Values, gcc.info, GNU C Manual})
15203: makes it possible to take the address of @i{label} by writing
15204: @code{&&@i{label}}.  This address can then be used in a statement like
15205: @code{goto *@i{address}}. I.e., @code{goto *&&x} is the same as
15206: @code{goto x}.
15207: 
15208: @cindex @code{NEXT}, indirect threaded
15209: @cindex indirect threaded inner interpreter
15210: @cindex inner interpreter, indirect threaded
15211: With this feature an indirect threaded @code{NEXT} looks like:
15212: @example
15213: cfa = *ip++;
15214: ca = *cfa;
15215: goto *ca;
15216: @end example
15217: @cindex instruction pointer
15218: For those unfamiliar with the names: @code{ip} is the Forth instruction
15219: pointer; the @code{cfa} (code-field address) corresponds to ANS Forths
15220: execution token and points to the code field of the next word to be
15221: executed; The @code{ca} (code address) fetched from there points to some
15222: executable code, e.g., a primitive or the colon definition handler
15223: @code{docol}.
15224: 
15225: @cindex @code{NEXT}, direct threaded
15226: @cindex direct threaded inner interpreter
15227: @cindex inner interpreter, direct threaded
15228: Direct threading is even simpler:
15229: @example
15230: ca = *ip++;
15231: goto *ca;
15232: @end example
15233: 
15234: Of course we have packaged the whole thing neatly in macros called
15235: @code{NEXT} and @code{NEXT1} (the part of @code{NEXT} after fetching the cfa).
15236: 
15237: @menu
15238: * Scheduling::                  
15239: * Direct or Indirect Threaded?::  
15240: * Dynamic Superinstructions::   
15241: * DOES>::                       
15242: @end menu
15243: 
15244: @node Scheduling, Direct or Indirect Threaded?, Threading, Threading
15245: @subsection Scheduling
15246: @cindex inner interpreter optimization
15247: 
15248: There is a little complication: Pipelined and superscalar processors,
15249: i.e., RISC and some modern CISC machines can process independent
15250: instructions while waiting for the results of an instruction. The
15251: compiler usually reorders (schedules) the instructions in a way that
15252: achieves good usage of these delay slots. However, on our first tries
15253: the compiler did not do well on scheduling primitives. E.g., for
15254: @code{+} implemented as
15255: @example
15256: n=sp[0]+sp[1];
15257: sp++;
15258: sp[0]=n;
15259: NEXT;
15260: @end example
15261: the @code{NEXT} comes strictly after the other code, i.e., there is
15262: nearly no scheduling. After a little thought the problem becomes clear:
15263: The compiler cannot know that @code{sp} and @code{ip} point to different
15264: addresses (and the version of @code{gcc} we used would not know it even
15265: if it was possible), so it could not move the load of the cfa above the
15266: store to the TOS. Indeed the pointers could be the same, if code on or
15267: very near the top of stack were executed. In the interest of speed we
15268: chose to forbid this probably unused ``feature'' and helped the compiler
15269: in scheduling: @code{NEXT} is divided into several parts:
15270: @code{NEXT_P0}, @code{NEXT_P1} and @code{NEXT_P2}). @code{+} now looks
15271: like:
15272: @example
15273: NEXT_P0;
15274: n=sp[0]+sp[1];
15275: sp++;
15276: NEXT_P1;
15277: sp[0]=n;
15278: NEXT_P2;
15279: @end example
15280: 
15281: There are various schemes that distribute the different operations of
15282: NEXT between these parts in several ways; in general, different schemes
15283: perform best on different processors.  We use a scheme for most
15284: architectures that performs well for most processors of this
15285: architecture; in the future we may switch to benchmarking and chosing
15286: the scheme on installation time.
15287: 
15288: 
15289: @node Direct or Indirect Threaded?, Dynamic Superinstructions, Scheduling, Threading
15290: @subsection Direct or Indirect Threaded?
15291: @cindex threading, direct or indirect?
15292: 
15293: Threaded forth code consists of references to primitives (simple machine
15294: code routines like @code{+}) and to non-primitives (e.g., colon
15295: definitions, variables, constants); for a specific class of
15296: non-primitives (e.g., variables) there is one code routine (e.g.,
15297: @code{dovar}), but each variable needs a separate reference to its data.
15298: 
15299: Traditionally Forth has been implemented as indirect threaded code,
15300: because this allows to use only one cell to reference a non-primitive
15301: (basically you point to the data, and find the code address there).
15302: 
15303: @cindex primitive-centric threaded code
15304: However, threaded code in Gforth (since 0.6.0) uses two cells for
15305: non-primitives, one for the code address, and one for the data address;
15306: the data pointer is an immediate argument for the virtual machine
15307: instruction represented by the code address.  We call this
15308: @emph{primitive-centric} threaded code, because all code addresses point
15309: to simple primitives.  E.g., for a variable, the code address is for
15310: @code{lit} (also used for integer literals like @code{99}).
15311: 
15312: Primitive-centric threaded code allows us to use (faster) direct
15313: threading as dispatch method, completely portably (direct threaded code
15314: in Gforth before 0.6.0 required architecture-specific code).  It also
15315: eliminates the performance problems related to I-cache consistency that
15316: 386 implementations have with direct threaded code, and allows
15317: additional optimizations.
15318: 
15319: @cindex hybrid direct/indirect threaded code
15320: There is a catch, however: the @var{xt} parameter of @code{execute} can
15321: occupy only one cell, so how do we pass non-primitives with their code
15322: @emph{and} data addresses to them?  Our answer is to use indirect
15323: threaded dispatch for @code{execute} and other words that use a
15324: single-cell xt.  So, normal threaded code in colon definitions uses
15325: direct threading, and @code{execute} and similar words, which dispatch
15326: to xts on the data stack, use indirect threaded code.  We call this
15327: @emph{hybrid direct/indirect} threaded code.
15328: 
15329: @cindex engines, gforth vs. gforth-fast vs. gforth-itc
15330: @cindex gforth engine
15331: @cindex gforth-fast engine
15332: The engines @command{gforth} and @command{gforth-fast} use hybrid
15333: direct/indirect threaded code.  This means that with these engines you
15334: cannot use @code{,} to compile an xt.  Instead, you have to use
15335: @code{compile,}.
15336: 
15337: @cindex gforth-itc engine
15338: If you want to compile xts with @code{,}, use @command{gforth-itc}.
15339: This engine uses plain old indirect threaded code.  It still compiles in
15340: a primitive-centric style, so you cannot use @code{compile,} instead of
15341: @code{,} (e.g., for producing tables of xts with @code{] word1 word2
15342: ... [}).  If you want to do that, you have to use @command{gforth-itc}
15343: and execute @code{' , is compile,}.  Your program can check if it is
15344: running on a hybrid direct/indirect threaded engine or a pure indirect
15345: threaded engine with @code{threading-method} (@pxref{Threading Words}).
15346: 
15347: 
15348: @node Dynamic Superinstructions, DOES>, Direct or Indirect Threaded?, Threading
15349: @subsection Dynamic Superinstructions
15350: @cindex Dynamic superinstructions with replication
15351: @cindex Superinstructions
15352: @cindex Replication
15353: 
15354: The engines @command{gforth} and @command{gforth-fast} use another
15355: optimization: Dynamic superinstructions with replication.  As an
15356: example, consider the following colon definition:
15357: 
15358: @example
15359: : squared ( n1 -- n2 )
15360:   dup * ;
15361: @end example
15362: 
15363: Gforth compiles this into the threaded code sequence
15364: 
15365: @example
15366: dup
15367: *
15368: ;s
15369: @end example
15370: 
15371: In normal direct threaded code there is a code address occupying one
15372: cell for each of these primitives.  Each code address points to a
15373: machine code routine, and the interpreter jumps to this machine code in
15374: order to execute the primitive.  The routines for these three
15375: primitives are (in @command{gforth-fast} on the 386):
15376: 
15377: @example
15378: Code dup  
15379: ( $804B950 )  add     esi , # -4  \ $83 $C6 $FC 
15380: ( $804B953 )  add     ebx , # 4  \ $83 $C3 $4 
15381: ( $804B956 )  mov     dword ptr 4 [esi] , ecx  \ $89 $4E $4 
15382: ( $804B959 )  jmp     dword ptr FC [ebx]  \ $FF $63 $FC 
15383: end-code
15384: Code *  
15385: ( $804ACC4 )  mov     eax , dword ptr 4 [esi]  \ $8B $46 $4 
15386: ( $804ACC7 )  add     esi , # 4  \ $83 $C6 $4 
15387: ( $804ACCA )  add     ebx , # 4  \ $83 $C3 $4 
15388: ( $804ACCD )  imul    ecx , eax  \ $F $AF $C8 
15389: ( $804ACD0 )  jmp     dword ptr FC [ebx]  \ $FF $63 $FC 
15390: end-code
15391: Code ;s  
15392: ( $804A693 )  mov     eax , dword ptr [edi]  \ $8B $7 
15393: ( $804A695 )  add     edi , # 4  \ $83 $C7 $4 
15394: ( $804A698 )  lea     ebx , dword ptr 4 [eax]  \ $8D $58 $4 
15395: ( $804A69B )  jmp     dword ptr FC [ebx]  \ $FF $63 $FC 
15396: end-code
15397: @end example
15398: 
15399: With dynamic superinstructions and replication the compiler does not
15400: just lay down the threaded code, but also copies the machine code
15401: fragments, usually without the jump at the end.
15402: 
15403: @example
15404: ( $4057D27D )  add     esi , # -4  \ $83 $C6 $FC 
15405: ( $4057D280 )  add     ebx , # 4  \ $83 $C3 $4 
15406: ( $4057D283 )  mov     dword ptr 4 [esi] , ecx  \ $89 $4E $4 
15407: ( $4057D286 )  mov     eax , dword ptr 4 [esi]  \ $8B $46 $4 
15408: ( $4057D289 )  add     esi , # 4  \ $83 $C6 $4 
15409: ( $4057D28C )  add     ebx , # 4  \ $83 $C3 $4 
15410: ( $4057D28F )  imul    ecx , eax  \ $F $AF $C8 
15411: ( $4057D292 )  mov     eax , dword ptr [edi]  \ $8B $7 
15412: ( $4057D294 )  add     edi , # 4  \ $83 $C7 $4 
15413: ( $4057D297 )  lea     ebx , dword ptr 4 [eax]  \ $8D $58 $4 
15414: ( $4057D29A )  jmp     dword ptr FC [ebx]  \ $FF $63 $FC 
15415: @end example
15416: 
15417: Only when a threaded-code control-flow change happens (e.g., in
15418: @code{;s}), the jump is appended.  This optimization eliminates many of
15419: these jumps and makes the rest much more predictable.  The speedup
15420: depends on the processor and the application; on the Athlon and Pentium
15421: III this optimization typically produces a speedup by a factor of 2.
15422: 
15423: The code addresses in the direct-threaded code are set to point to the
15424: appropriate points in the copied machine code, in this example like
15425: this:
15426: 
15427: @example
15428: primitive  code address
15429:    dup       $4057D27D
15430:    *         $4057D286
15431:    ;s        $4057D292
15432: @end example
15433: 
15434: Thus there can be threaded-code jumps to any place in this piece of
15435: code.  This also simplifies decompilation quite a bit.
15436: 
15437: @cindex --no-dynamic command-line option
15438: @cindex --no-super command-line option
15439: You can disable this optimization with @option{--no-dynamic}.  You can
15440: use the copying without eliminating the jumps (i.e., dynamic
15441: replication, but without superinstructions) with @option{--no-super};
15442: this gives the branch prediction benefit alone; the effect on
15443: performance depends on the CPU; on the Athlon and Pentium III the
15444: speedup is a little less than for dynamic superinstructions with
15445: replication.
15446: 
15447: @cindex patching threaded code
15448: One use of these options is if you want to patch the threaded code.
15449: With superinstructions, many of the dispatch jumps are eliminated, so
15450: patching often has no effect.  These options preserve all the dispatch
15451: jumps.
15452: 
15453: @cindex --dynamic command-line option
15454: On some machines dynamic superinstructions are disabled by default,
15455: because it is unsafe on these machines.  However, if you feel
15456: adventurous, you can enable it with @option{--dynamic}.
15457: 
15458: @node DOES>,  , Dynamic Superinstructions, Threading
15459: @subsection DOES>
15460: @cindex @code{DOES>} implementation
15461: 
15462: @cindex @code{dodoes} routine
15463: @cindex @code{DOES>}-code
15464: One of the most complex parts of a Forth engine is @code{dodoes}, i.e.,
15465: the chunk of code executed by every word defined by a
15466: @code{CREATE}...@code{DOES>} pair; actually with primitive-centric code,
15467: this is only needed if the xt of the word is @code{execute}d. The main
15468: problem here is: How to find the Forth code to be executed, i.e. the
15469: code after the @code{DOES>} (the @code{DOES>}-code)? There are two
15470: solutions:
15471: 
15472: In fig-Forth the code field points directly to the @code{dodoes} and the
15473: @code{DOES>}-code address is stored in the cell after the code address
15474: (i.e. at @code{@i{CFA} cell+}). It may seem that this solution is
15475: illegal in the Forth-79 and all later standards, because in fig-Forth
15476: this address lies in the body (which is illegal in these
15477: standards). However, by making the code field larger for all words this
15478: solution becomes legal again.  We use this approach.  Leaving a cell
15479: unused in most words is a bit wasteful, but on the machines we are
15480: targeting this is hardly a problem.
15481: 
15482: 
15483: @node Primitives, Performance, Threading, Engine
15484: @section Primitives
15485: @cindex primitives, implementation
15486: @cindex virtual machine instructions, implementation
15487: 
15488: @menu
15489: * Automatic Generation::        
15490: * TOS Optimization::            
15491: * Produced code::               
15492: @end menu
15493: 
15494: @node Automatic Generation, TOS Optimization, Primitives, Primitives
15495: @subsection Automatic Generation
15496: @cindex primitives, automatic generation
15497: 
15498: @cindex @file{prims2x.fs}
15499: 
15500: Since the primitives are implemented in a portable language, there is no
15501: longer any need to minimize the number of primitives. On the contrary,
15502: having many primitives has an advantage: speed. In order to reduce the
15503: number of errors in primitives and to make programming them easier, we
15504: provide a tool, the primitive generator (@file{prims2x.fs} aka Vmgen,
15505: @pxref{Top, Vmgen, Introduction, vmgen, Vmgen}), that automatically
15506: generates most (and sometimes all) of the C code for a primitive from
15507: the stack effect notation.  The source for a primitive has the following
15508: form:
15509: 
15510: @cindex primitive source format
15511: @format
15512: @i{Forth-name}  ( @i{stack-effect} )        @i{category}    [@i{pronounc.}]
15513: [@code{""}@i{glossary entry}@code{""}]
15514: @i{C code}
15515: [@code{:}
15516: @i{Forth code}]
15517: @end format
15518: 
15519: The items in brackets are optional. The category and glossary fields
15520: are there for generating the documentation, the Forth code is there
15521: for manual implementations on machines without GNU C. E.g., the source
15522: for the primitive @code{+} is:
15523: @example
15524: +    ( n1 n2 -- n )   core    plus
15525: n = n1+n2;
15526: @end example
15527: 
15528: This looks like a specification, but in fact @code{n = n1+n2} is C
15529: code. Our primitive generation tool extracts a lot of information from
15530: the stack effect notations@footnote{We use a one-stack notation, even
15531: though we have separate data and floating-point stacks; The separate
15532: notation can be generated easily from the unified notation.}: The number
15533: of items popped from and pushed on the stack, their type, and by what
15534: name they are referred to in the C code. It then generates a C code
15535: prelude and postlude for each primitive. The final C code for @code{+}
15536: looks like this:
15537: 
15538: @example
15539: I_plus: /* + ( n1 n2 -- n ) */  /* label, stack effect */
15540: /*  */                          /* documentation */
15541: NAME("+")                       /* debugging output (with -DDEBUG) */
15542: @{
15543: DEF_CA                          /* definition of variable ca (indirect threading) */
15544: Cell n1;                        /* definitions of variables */
15545: Cell n2;
15546: Cell n;
15547: NEXT_P0;                        /* NEXT part 0 */
15548: n1 = (Cell) sp[1];              /* input */
15549: n2 = (Cell) TOS;
15550: sp += 1;                        /* stack adjustment */
15551: @{
15552: n = n1+n2;                      /* C code taken from the source */
15553: @}
15554: NEXT_P1;                        /* NEXT part 1 */
15555: TOS = (Cell)n;                  /* output */
15556: NEXT_P2;                        /* NEXT part 2 */
15557: @}
15558: @end example
15559: 
15560: This looks long and inefficient, but the GNU C compiler optimizes quite
15561: well and produces optimal code for @code{+} on, e.g., the R3000 and the
15562: HP RISC machines: Defining the @code{n}s does not produce any code, and
15563: using them as intermediate storage also adds no cost.
15564: 
15565: There are also other optimizations that are not illustrated by this
15566: example: assignments between simple variables are usually for free (copy
15567: propagation). If one of the stack items is not used by the primitive
15568: (e.g.  in @code{drop}), the compiler eliminates the load from the stack
15569: (dead code elimination). On the other hand, there are some things that
15570: the compiler does not do, therefore they are performed by
15571: @file{prims2x.fs}: The compiler does not optimize code away that stores
15572: a stack item to the place where it just came from (e.g., @code{over}).
15573: 
15574: While programming a primitive is usually easy, there are a few cases
15575: where the programmer has to take the actions of the generator into
15576: account, most notably @code{?dup}, but also words that do not (always)
15577: fall through to @code{NEXT}.
15578: 
15579: For more information
15580: 
15581: @node TOS Optimization, Produced code, Automatic Generation, Primitives
15582: @subsection TOS Optimization
15583: @cindex TOS optimization for primitives
15584: @cindex primitives, keeping the TOS in a register
15585: 
15586: An important optimization for stack machine emulators, e.g., Forth
15587: engines, is keeping  one or more of the top stack items in
15588: registers.  If a word has the stack effect @i{in1}...@i{inx} @code{--}
15589: @i{out1}...@i{outy}, keeping the top @i{n} items in registers
15590: @itemize @bullet
15591: @item
15592: is better than keeping @i{n-1} items, if @i{x>=n} and @i{y>=n},
15593: due to fewer loads from and stores to the stack.
15594: @item is slower than keeping @i{n-1} items, if @i{x<>y} and @i{x<n} and
15595: @i{y<n}, due to additional moves between registers.
15596: @end itemize
15597: 
15598: @cindex -DUSE_TOS
15599: @cindex -DUSE_NO_TOS
15600: In particular, keeping one item in a register is never a disadvantage,
15601: if there are enough registers. Keeping two items in registers is a
15602: disadvantage for frequent words like @code{?branch}, constants,
15603: variables, literals and @code{i}. Therefore our generator only produces
15604: code that keeps zero or one items in registers. The generated C code
15605: covers both cases; the selection between these alternatives is made at
15606: C-compile time using the switch @code{-DUSE_TOS}. @code{TOS} in the C
15607: code for @code{+} is just a simple variable name in the one-item case,
15608: otherwise it is a macro that expands into @code{sp[0]}. Note that the
15609: GNU C compiler tries to keep simple variables like @code{TOS} in
15610: registers, and it usually succeeds, if there are enough registers.
15611: 
15612: @cindex -DUSE_FTOS
15613: @cindex -DUSE_NO_FTOS
15614: The primitive generator performs the TOS optimization for the
15615: floating-point stack, too (@code{-DUSE_FTOS}). For floating-point
15616: operations the benefit of this optimization is even larger:
15617: floating-point operations take quite long on most processors, but can be
15618: performed in parallel with other operations as long as their results are
15619: not used. If the FP-TOS is kept in a register, this works. If
15620: it is kept on the stack, i.e., in memory, the store into memory has to
15621: wait for the result of the floating-point operation, lengthening the
15622: execution time of the primitive considerably.
15623: 
15624: The TOS optimization makes the automatic generation of primitives a
15625: bit more complicated. Just replacing all occurrences of @code{sp[0]} by
15626: @code{TOS} is not sufficient. There are some special cases to
15627: consider:
15628: @itemize @bullet
15629: @item In the case of @code{dup ( w -- w w )} the generator must not
15630: eliminate the store to the original location of the item on the stack,
15631: if the TOS optimization is turned on.
15632: @item Primitives with stack effects of the form @code{--}
15633: @i{out1}...@i{outy} must store the TOS to the stack at the start.
15634: Likewise, primitives with the stack effect @i{in1}...@i{inx} @code{--}
15635: must load the TOS from the stack at the end. But for the null stack
15636: effect @code{--} no stores or loads should be generated.
15637: @end itemize
15638: 
15639: @node Produced code,  , TOS Optimization, Primitives
15640: @subsection Produced code
15641: @cindex primitives, assembly code listing
15642: 
15643: @cindex @file{engine.s}
15644: To see what assembly code is produced for the primitives on your machine
15645: with your compiler and your flag settings, type @code{make engine.s} and
15646: look at the resulting file @file{engine.s}.  Alternatively, you can also
15647: disassemble the code of primitives with @code{see} on some architectures.
15648: 
15649: @node  Performance,  , Primitives, Engine
15650: @section Performance
15651: @cindex performance of some Forth interpreters
15652: @cindex engine performance
15653: @cindex benchmarking Forth systems
15654: @cindex Gforth performance
15655: 
15656: On RISCs the Gforth engine is very close to optimal; i.e., it is usually
15657: impossible to write a significantly faster threaded-code engine.
15658: 
15659: On register-starved machines like the 386 architecture processors
15660: improvements are possible, because @code{gcc} does not utilize the
15661: registers as well as a human, even with explicit register declarations;
15662: e.g., Bernd Beuster wrote a Forth system fragment in assembly language
15663: and hand-tuned it for the 486; this system is 1.19 times faster on the
15664: Sieve benchmark on a 486DX2/66 than Gforth compiled with
15665: @code{gcc-2.6.3} with @code{-DFORCE_REG}.  The situation has improved
15666: with gcc-2.95 and gforth-0.4.9; now the most important virtual machine
15667: registers fit in real registers (and we can even afford to use the TOS
15668: optimization), resulting in a speedup of 1.14 on the sieve over the
15669: earlier results.  And dynamic superinstructions provide another speedup
15670: (but only around a factor 1.2 on the 486).
15671: 
15672: @cindex Win32Forth performance
15673: @cindex NT Forth performance
15674: @cindex eforth performance
15675: @cindex ThisForth performance
15676: @cindex PFE performance
15677: @cindex TILE performance
15678: The potential advantage of assembly language implementations is not
15679: necessarily realized in complete Forth systems: We compared Gforth-0.5.9
15680: (direct threaded, compiled with @code{gcc-2.95.1} and
15681: @code{-DFORCE_REG}) with Win32Forth 1.2093 (newer versions are
15682: reportedly much faster), LMI's NT Forth (Beta, May 1994) and Eforth
15683: (with and without peephole (aka pinhole) optimization of the threaded
15684: code); all these systems were written in assembly language. We also
15685: compared Gforth with three systems written in C: PFE-0.9.14 (compiled
15686: with @code{gcc-2.6.3} with the default configuration for Linux:
15687: @code{-O2 -fomit-frame-pointer -DUSE_REGS -DUNROLL_NEXT}), ThisForth
15688: Beta (compiled with @code{gcc-2.6.3 -O3 -fomit-frame-pointer}; ThisForth
15689: employs peephole optimization of the threaded code) and TILE (compiled
15690: with @code{make opt}). We benchmarked Gforth, PFE, ThisForth and TILE on
15691: a 486DX2/66 under Linux. Kenneth O'Heskin kindly provided the results
15692: for Win32Forth and NT Forth on a 486DX2/66 with similar memory
15693: performance under Windows NT. Marcel Hendrix ported Eforth to Linux,
15694: then extended it to run the benchmarks, added the peephole optimizer,
15695: ran the benchmarks and reported the results.
15696: 
15697: We used four small benchmarks: the ubiquitous Sieve; bubble-sorting and
15698: matrix multiplication come from the Stanford integer benchmarks and have
15699: been translated into Forth by Martin Fraeman; we used the versions
15700: included in the TILE Forth package, but with bigger data set sizes; and
15701: a recursive Fibonacci number computation for benchmarking calling
15702: performance. The following table shows the time taken for the benchmarks
15703: scaled by the time taken by Gforth (in other words, it shows the speedup
15704: factor that Gforth achieved over the other systems).
15705: 
15706: @example
15707: relative       Win32-    NT       eforth       This-      
15708: time     Gforth Forth Forth eforth  +opt   PFE Forth  TILE
15709: sieve      1.00  2.16  1.78   2.16  1.32  2.46  4.96 13.37
15710: bubble     1.00  1.93  2.07   2.18  1.29  2.21        5.70
15711: matmul     1.00  1.92  1.76   1.90  0.96  2.06        5.32
15712: fib        1.00  2.32  2.03   1.86  1.31  2.64  4.55  6.54
15713: @end example
15714: 
15715: You may be quite surprised by the good performance of Gforth when
15716: compared with systems written in assembly language. One important reason
15717: for the disappointing performance of these other systems is probably
15718: that they are not written optimally for the 486 (e.g., they use the
15719: @code{lods} instruction). In addition, Win32Forth uses a comfortable,
15720: but costly method for relocating the Forth image: like @code{cforth}, it
15721: computes the actual addresses at run time, resulting in two address
15722: computations per @code{NEXT} (@pxref{Image File Background}).
15723: 
15724: The speedup of Gforth over PFE, ThisForth and TILE can be easily
15725: explained with the self-imposed restriction of the latter systems to
15726: standard C, which makes efficient threading impossible (however, the
15727: measured implementation of PFE uses a GNU C extension: @pxref{Global Reg
15728: Vars, , Defining Global Register Variables, gcc.info, GNU C Manual}).
15729: Moreover, current C compilers have a hard time optimizing other aspects
15730: of the ThisForth and the TILE source.
15731: 
15732: The performance of Gforth on 386 architecture processors varies widely
15733: with the version of @code{gcc} used. E.g., @code{gcc-2.5.8} failed to
15734: allocate any of the virtual machine registers into real machine
15735: registers by itself and would not work correctly with explicit register
15736: declarations, giving a significantly slower engine (on a 486DX2/66
15737: running the Sieve) than the one measured above.
15738: 
15739: Note that there have been several releases of Win32Forth since the
15740: release presented here, so the results presented above may have little
15741: predictive value for the performance of Win32Forth today (results for
15742: the current release on an i486DX2/66 are welcome).
15743: 
15744: @cindex @file{Benchres}
15745: In
15746: @cite{@uref{http://www.complang.tuwien.ac.at/papers/ertl&maierhofer95.ps.gz,
15747: Translating Forth to Efficient C}} by M. Anton Ertl and Martin
15748: Maierhofer (presented at EuroForth '95), an indirect threaded version of
15749: Gforth is compared with Win32Forth, NT Forth, PFE, ThisForth, and
15750: several native code systems; that version of Gforth is slower on a 486
15751: than the version used here. You can find a newer version of these
15752: measurements at
15753: @uref{http://www.complang.tuwien.ac.at/forth/performance.html}. You can
15754: find numbers for Gforth on various machines in @file{Benchres}.
15755: 
15756: @c ******************************************************************
15757: @c @node Binding to System Library, Cross Compiler, Engine, Top
15758: @c @chapter Binding to System Library
15759: 
15760: @c ****************************************************************
15761: @node Cross Compiler, Bugs, Engine, Top
15762: @chapter Cross Compiler
15763: @cindex @file{cross.fs}
15764: @cindex cross-compiler
15765: @cindex metacompiler
15766: @cindex target compiler
15767: 
15768: The cross compiler is used to bootstrap a Forth kernel. Since Gforth is
15769: mostly written in Forth, including crucial parts like the outer
15770: interpreter and compiler, it needs compiled Forth code to get
15771: started. The cross compiler allows to create new images for other
15772: architectures, even running under another Forth system.
15773: 
15774: @menu
15775: * Using the Cross Compiler::    
15776: * How the Cross Compiler Works::  
15777: @end menu
15778: 
15779: @node Using the Cross Compiler, How the Cross Compiler Works, Cross Compiler, Cross Compiler
15780: @section Using the Cross Compiler
15781: 
15782: The cross compiler uses a language that resembles Forth, but isn't. The
15783: main difference is that you can execute Forth code after definition,
15784: while you usually can't execute the code compiled by cross, because the
15785: code you are compiling is typically for a different computer than the
15786: one you are compiling on.
15787: 
15788: @c anton: This chapter is somewhat different from waht I would expect: I
15789: @c would expect an explanation of the cross language and how to create an
15790: @c application image with it.  The section explains some aspects of
15791: @c creating a Gforth kernel.
15792: 
15793: The Makefile is already set up to allow you to create kernels for new
15794: architectures with a simple make command. The generic kernels using the
15795: GCC compiled virtual machine are created in the normal build process
15796: with @code{make}. To create a embedded Gforth executable for e.g. the
15797: 8086 processor (running on a DOS machine), type
15798: 
15799: @example
15800: make kernl-8086.fi
15801: @end example
15802: 
15803: This will use the machine description from the @file{arch/8086}
15804: directory to create a new kernel. A machine file may look like that:
15805: 
15806: @example
15807: \ Parameter for target systems                         06oct92py
15808: 
15809:     4 Constant cell             \ cell size in bytes
15810:     2 Constant cell<<           \ cell shift to bytes
15811:     5 Constant cell>bit         \ cell shift to bits
15812:     8 Constant bits/char        \ bits per character
15813:     8 Constant bits/byte        \ bits per byte [default: 8]
15814:     8 Constant float            \ bytes per float
15815:     8 Constant /maxalign        \ maximum alignment in bytes
15816: false Constant bigendian        \ byte order
15817: ( true=big, false=little )
15818: 
15819: include machpc.fs               \ feature list
15820: @end example
15821: 
15822: This part is obligatory for the cross compiler itself, the feature list
15823: is used by the kernel to conditionally compile some features in and out,
15824: depending on whether the target supports these features.
15825: 
15826: There are some optional features, if you define your own primitives,
15827: have an assembler, or need special, nonstandard preparation to make the
15828: boot process work. @code{asm-include} includes an assembler,
15829: @code{prims-include} includes primitives, and @code{>boot} prepares for
15830: booting.
15831: 
15832: @example
15833: : asm-include    ." Include assembler" cr
15834:   s" arch/8086/asm.fs" included ;
15835: 
15836: : prims-include  ." Include primitives" cr
15837:   s" arch/8086/prim.fs" included ;
15838: 
15839: : >boot          ." Prepare booting" cr
15840:   s" ' boot >body into-forth 1+ !" evaluate ;
15841: @end example
15842: 
15843: These words are used as sort of macro during the cross compilation in
15844: the file @file{kernel/main.fs}. Instead of using these macros, it would
15845: be possible --- but more complicated --- to write a new kernel project
15846: file, too.
15847: 
15848: @file{kernel/main.fs} expects the machine description file name on the
15849: stack; the cross compiler itself (@file{cross.fs}) assumes that either
15850: @code{mach-file} leaves a counted string on the stack, or
15851: @code{machine-file} leaves an address, count pair of the filename on the
15852: stack.
15853: 
15854: The feature list is typically controlled using @code{SetValue}, generic
15855: files that are used by several projects can use @code{DefaultValue}
15856: instead. Both functions work like @code{Value}, when the value isn't
15857: defined, but @code{SetValue} works like @code{to} if the value is
15858: defined, and @code{DefaultValue} doesn't set anything, if the value is
15859: defined.
15860: 
15861: @example
15862: \ generic mach file for pc gforth                       03sep97jaw
15863: 
15864: true DefaultValue NIL  \ relocating
15865: 
15866: >ENVIRON
15867: 
15868: true DefaultValue file          \ controls the presence of the
15869:                                 \ file access wordset
15870: true DefaultValue OS            \ flag to indicate a operating system
15871: 
15872: true DefaultValue prims         \ true: primitives are c-code
15873: 
15874: true DefaultValue floating      \ floating point wordset is present
15875: 
15876: true DefaultValue glocals       \ gforth locals are present
15877:                                 \ will be loaded
15878: true DefaultValue dcomps        \ double number comparisons
15879: 
15880: true DefaultValue hash          \ hashing primitives are loaded/present
15881: 
15882: true DefaultValue xconds        \ used together with glocals,
15883:                                 \ special conditionals supporting gforths'
15884:                                 \ local variables
15885: true DefaultValue header        \ save a header information
15886: 
15887: true DefaultValue backtrace     \ enables backtrace code
15888: 
15889: false DefaultValue ec
15890: false DefaultValue crlf
15891: 
15892: cell 2 = [IF] &32 [ELSE] &256 [THEN] KB DefaultValue kernel-size
15893: 
15894: &16 KB          DefaultValue stack-size
15895: &15 KB &512 +   DefaultValue fstack-size
15896: &15 KB          DefaultValue rstack-size
15897: &14 KB &512 +   DefaultValue lstack-size
15898: @end example
15899: 
15900: @node How the Cross Compiler Works,  , Using the Cross Compiler, Cross Compiler
15901: @section How the Cross Compiler Works
15902: 
15903: @node Bugs, Origin, Cross Compiler, Top
15904: @appendix Bugs
15905: @cindex bug reporting
15906: 
15907: Known bugs are described in the file @file{BUGS} in the Gforth distribution.
15908: 
15909: If you find a bug, please submit a bug report through
15910: @uref{https://savannah.gnu.org/bugs/?func=addbug&group=gforth}.
15911: 
15912: @itemize @bullet
15913: @item
15914: A program (or a sequence of keyboard commands) that reproduces the bug.
15915: @item
15916: A description of what you think constitutes the buggy behaviour.
15917: @item
15918: The Gforth version used (it is announced at the start of an
15919: interactive Gforth session).
15920: @item
15921: The machine and operating system (on Unix
15922: systems @code{uname -a} will report this information).
15923: @item
15924: The installation options (you can find the configure options at the
15925: start of @file{config.status}) and configuration (@code{configure}
15926: output or @file{config.cache}).
15927: @item
15928: A complete list of changes (if any) you (or your installer) have made to the
15929: Gforth sources.
15930: @end itemize
15931: 
15932: For a thorough guide on reporting bugs read @ref{Bug Reporting, , How
15933: to Report Bugs, gcc.info, GNU C Manual}.
15934: 
15935: 
15936: @node Origin, Forth-related information, Bugs, Top
15937: @appendix Authors and Ancestors of Gforth
15938: 
15939: @section Authors and Contributors
15940: @cindex authors of Gforth
15941: @cindex contributors to Gforth
15942: 
15943: The Gforth project was started in mid-1992 by Bernd Paysan and Anton
15944: Ertl. The third major author was Jens Wilke.  Neal Crook contributed a
15945: lot to the manual.  Assemblers and disassemblers were contributed by
15946: Andrew McKewan, Christian Pirker, Bernd Thallner, and Michal Revucky.
15947: Lennart Benschop (who was one of Gforth's first users, in mid-1993)
15948: and Stuart Ramsden inspired us with their continuous feedback. Lennart
15949: Benshop contributed @file{glosgen.fs}, while Stuart Ramsden has been
15950: working on automatic support for calling C libraries. Helpful comments
15951: also came from Paul Kleinrubatscher, Christian Pirker, Dirk Zoller,
15952: Marcel Hendrix, John Wavrik, Barrie Stott, Marc de Groot, Jorge
15953: Acerada, Bruce Hoyt, Robert Epprecht, Dennis Ruffer and David
15954: N. Williams. Since the release of Gforth-0.2.1 there were also helpful
15955: comments from many others; thank you all, sorry for not listing you
15956: here (but digging through my mailbox to extract your names is on my
15957: to-do list).
15958: 
15959: Gforth also owes a lot to the authors of the tools we used (GCC, CVS,
15960: and autoconf, among others), and to the creators of the Internet: Gforth
15961: was developed across the Internet, and its authors did not meet
15962: physically for the first 4 years of development.
15963: 
15964: @section Pedigree
15965: @cindex pedigree of Gforth
15966: 
15967: Gforth descends from bigFORTH (1993) and fig-Forth.  Of course, a
15968: significant part of the design of Gforth was prescribed by ANS Forth.
15969: 
15970: Bernd Paysan wrote bigFORTH, a descendent from TurboForth, an unreleased
15971: 32 bit native code version of VolksForth for the Atari ST, written
15972: mostly by Dietrich Weineck.
15973: 
15974: VolksForth was written by Klaus Schleisiek, Bernd Pennemann, Georg
15975: Rehfeld and Dietrich Weineck for the C64 (called UltraForth there) in
15976: the mid-80s and ported to the Atari ST in 1986.  It descends from fig-Forth.
15977: 
15978: @c Henry Laxen and Mike Perry wrote F83 as a model implementation of the
15979: @c Forth-83 standard. !! Pedigree? When?
15980: 
15981: A team led by Bill Ragsdale implemented fig-Forth on many processors in
15982: 1979. Robert Selzer and Bill Ragsdale developed the original
15983: implementation of fig-Forth for the 6502 based on microForth.
15984: 
15985: The principal architect of microForth was Dean Sanderson. microForth was
15986: FORTH, Inc.'s first off-the-shelf product. It was developed in 1976 for
15987: the 1802, and subsequently implemented on the 8080, the 6800 and the
15988: Z80.
15989: 
15990: All earlier Forth systems were custom-made, usually by Charles Moore,
15991: who discovered (as he puts it) Forth during the late 60s. The first full
15992: Forth existed in 1971.
15993: 
15994: A part of the information in this section comes from
15995: @cite{@uref{http://www.forth.com/Content/History/History1.htm,The
15996: Evolution of Forth}} by Elizabeth D. Rather, Donald R. Colburn and
15997: Charles H. Moore, presented at the HOPL-II conference and preprinted
15998: in SIGPLAN Notices 28(3), 1993.  You can find more historical and
15999: genealogical information about Forth there.  For a more general (and
16000: graphical) Forth family tree look see
16001: @cite{@uref{http://www.complang.tuwien.ac.at/forth/family-tree/},
16002: Forth Family Tree and Timeline}.
16003: 
16004: @c ------------------------------------------------------------------
16005: @node Forth-related information, Licenses, Origin, Top
16006: @appendix Other Forth-related information
16007: @cindex Forth-related information
16008: 
16009: @c anton: I threw most of this stuff out, because it can be found through
16010: @c the FAQ and the FAQ is more likely to be up-to-date.
16011: 
16012: @cindex comp.lang.forth
16013: @cindex frequently asked questions
16014: There is an active news group (comp.lang.forth) discussing Forth
16015: (including Gforth) and Forth-related issues. Its
16016: @uref{http://www.complang.tuwien.ac.at/forth/faq/faq-general-2.html,FAQs}
16017: (frequently asked questions and their answers) contains a lot of
16018: information on Forth.  You should read it before posting to
16019: comp.lang.forth.
16020: 
16021: The ANS Forth standard is most usable in its
16022: @uref{http://www.taygeta.com/forth/dpans.html, HTML form}.
16023: 
16024: @c ---------------------------------------------------
16025: @node  Licenses, Word Index, Forth-related information, Top
16026: @appendix Licenses
16027: 
16028: @menu
16029: * GNU Free Documentation License::  License for copying this manual.
16030: * Copying::                         GPL (for copying this software).
16031: @end menu
16032: 
16033: @include fdl.texi
16034: 
16035: @include gpl.texi
16036: 
16037: 
16038: 
16039: @c ------------------------------------------------------------------
16040: @node Word Index, Concept Index, Licenses, Top
16041: @unnumbered Word Index
16042: 
16043: This index is a list of Forth words that have ``glossary'' entries
16044: within this manual. Each word is listed with its stack effect and
16045: wordset.
16046: 
16047: @printindex fn
16048: 
16049: @c anton: the name index seems superfluous given the word and concept indices.
16050: 
16051: @c @node Name Index, Concept Index, Word Index, Top
16052: @c @unnumbered Name Index
16053: 
16054: @c This index is a list of Forth words that have ``glossary'' entries
16055: @c within this manual.
16056: 
16057: @c @printindex ky
16058: 
16059: @c -------------------------------------------------------
16060: @node Concept Index,  , Word Index, Top
16061: @unnumbered Concept and Word Index
16062: 
16063: Not all entries listed in this index are present verbatim in the
16064: text. This index also duplicates, in abbreviated form, all of the words
16065: listed in the Word Index (only the names are listed for the words here).
16066: 
16067: @printindex cp
16068: 
16069: @bye
16070: 
16071: 
16072: 

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