File:  [gforth] / gforth / doc / gforth.ds
Revision 1.153: download - view: text, annotated - select for diffs
Sat Mar 18 22:38:21 2006 UTC (18 years, 1 month ago) by anton
Branches: MAIN
CVS tags: HEAD
minor documentation fix

    1: \input texinfo   @c -*-texinfo-*-
    2: @comment The source is gforth.ds, from which gforth.texi is generated
    3: 
    4: @comment TODO: nac29jan99 - a list of things to add in the next edit:
    5: @comment 1. x-ref all ambiguous or implementation-defined features?
    6: @comment 2. Describe the use of Auser Avariable AConstant A, etc.
    7: @comment 3. words in miscellaneous section need a home.
    8: @comment 4. search for TODO for other minor and major works required.
    9: @comment 5. [rats] change all @var to @i in Forth source so that info
   10: @comment    file looks decent.
   11: @c          Not an improvement IMO - anton
   12: @c          and anyway, this should be taken up
   13: @c          with Karl Berry (the texinfo guy) - anton
   14: @c
   15: @c Karl Berry writes:
   16: @c  If they don't like the all-caps for @var Info output, all I can say is
   17: @c  that it's always been that way, and the usage of all-caps for
   18: @c  metavariables has a long tradition.  I think it's best to just let it be
   19: @c  what it is, for the sake of consistency among manuals.
   20: @c
   21: @comment .. would be useful to have a word that identified all deferred words
   22: @comment should semantics stuff in intro be moved to another section
   23: 
   24: @c POSTPONE, COMPILE, [COMPILE], LITERAL should have their own section
   25: 
   26: @comment %**start of header (This is for running Texinfo on a region.)
   27: @setfilename gforth.info
   28: @include version.texi
   29: @settitle Gforth Manual
   30: @c @syncodeindex pg cp
   31: 
   32: @macro progstyle {}
   33: Programming style note:
   34: @end macro
   35: 
   36: @macro assignment {}
   37: @table @i
   38: @item Assignment:
   39: @end macro
   40: @macro endassignment {}
   41: @end table
   42: @end macro
   43: 
   44: @comment macros for beautifying glossary entries
   45: @macro GLOSS-START {}
   46: @iftex
   47: @ninerm
   48: @end iftex
   49: @end macro
   50: 
   51: @macro GLOSS-END {}
   52: @iftex
   53: @rm
   54: @end iftex
   55: @end macro
   56: 
   57: @comment %**end of header (This is for running Texinfo on a region.)
   58: @copying
   59: This manual is for Gforth (version @value{VERSION}, @value{UPDATED}),
   60: a fast and portable implementation of the ANS Forth language.  It
   61: serves as reference manual, but it also contains an introduction to
   62: Forth and a Forth tutorial.
   63: 
   64: Copyright @copyright{} 1995, 1996, 1997, 1998, 2000, 2003, 2004,2005 Free Software Foundation, Inc.
   65: 
   66: @quotation
   67: Permission is granted to copy, distribute and/or modify this document
   68: under the terms of the GNU Free Documentation License, Version 1.1 or
   69: any later version published by the Free Software Foundation; with no
   70: Invariant Sections, with the Front-Cover texts being ``A GNU Manual,''
   71: and with the Back-Cover Texts as in (a) below.  A copy of the
   72: license is included in the section entitled ``GNU Free Documentation
   73: License.''
   74: 
   75: (a) The FSF's Back-Cover Text is: ``You have freedom to copy and modify
   76: this GNU Manual, like GNU software.  Copies published by the Free
   77: Software Foundation raise funds for GNU development.''
   78: @end quotation
   79: @end copying
   80: 
   81: @dircategory Software development
   82: @direntry
   83: * Gforth: (gforth).             A fast interpreter for the Forth language.
   84: @end direntry
   85: @c The Texinfo manual also recommends doing this, but for Gforth it may
   86: @c  not make much sense
   87: @c @dircategory Individual utilities
   88: @c @direntry
   89: @c * Gforth: (gforth)Invoking Gforth.      gforth, gforth-fast, gforthmi
   90: @c @end direntry
   91: 
   92: @titlepage
   93: @title Gforth
   94: @subtitle for version @value{VERSION}, @value{UPDATED}
   95: @author Neal Crook
   96: @author Anton Ertl
   97: @author David Kuehling
   98: @author Bernd Paysan
   99: @author Jens Wilke
  100: @page
  101: @vskip 0pt plus 1filll
  102: @insertcopying
  103: @end titlepage
  104: 
  105: @contents
  106: 
  107: @ifnottex
  108: @node Top, Goals, (dir), (dir)
  109: @top Gforth
  110: 
  111: @insertcopying
  112: @end ifnottex
  113: 
  114: @menu
  115: * Goals::                       About the Gforth Project
  116: * Gforth Environment::          Starting (and exiting) Gforth
  117: * Tutorial::                    Hands-on Forth Tutorial
  118: * Introduction::                An introduction to ANS Forth
  119: * Words::                       Forth words available in Gforth
  120: * Error messages::              How to interpret them
  121: * Tools::                       Programming tools
  122: * ANS conformance::             Implementation-defined options etc.
  123: * Standard vs Extensions::      Should I use extensions?
  124: * Model::                       The abstract machine of Gforth
  125: * Integrating Gforth::          Forth as scripting language for applications
  126: * Emacs and Gforth::            The Gforth Mode
  127: * Image Files::                 @code{.fi} files contain compiled code
  128: * Engine::                      The inner interpreter and the primitives
  129: * Cross Compiler::              The Cross Compiler
  130: * Bugs::                        How to report them
  131: * Origin::                      Authors and ancestors of Gforth
  132: * Forth-related information::   Books and places to look on the WWW
  133: * Licenses::                    
  134: * Word Index::                  An item for each Forth word
  135: * Concept Index::               A menu covering many topics
  136: 
  137: @detailmenu
  138:  --- The Detailed Node Listing ---
  139: 
  140: Gforth Environment
  141: 
  142: * Invoking Gforth::             Getting in
  143: * Leaving Gforth::              Getting out
  144: * Command-line editing::        
  145: * Environment variables::       that affect how Gforth starts up
  146: * Gforth Files::                What gets installed and where
  147: * Gforth in pipes::             
  148: * Startup speed::               When 35ms is not fast enough ...
  149: 
  150: Forth Tutorial
  151: 
  152: * Starting Gforth Tutorial::    
  153: * Syntax Tutorial::             
  154: * Crash Course Tutorial::       
  155: * Stack Tutorial::              
  156: * Arithmetics Tutorial::        
  157: * Stack Manipulation Tutorial::  
  158: * Using files for Forth code Tutorial::  
  159: * Comments Tutorial::           
  160: * Colon Definitions Tutorial::  
  161: * Decompilation Tutorial::      
  162: * Stack-Effect Comments Tutorial::  
  163: * Types Tutorial::              
  164: * Factoring Tutorial::          
  165: * Designing the stack effect Tutorial::  
  166: * Local Variables Tutorial::    
  167: * Conditional execution Tutorial::  
  168: * Flags and Comparisons Tutorial::  
  169: * General Loops Tutorial::      
  170: * Counted loops Tutorial::      
  171: * Recursion Tutorial::          
  172: * Leaving definitions or loops Tutorial::  
  173: * Return Stack Tutorial::       
  174: * Memory Tutorial::             
  175: * Characters and Strings Tutorial::  
  176: * Alignment Tutorial::          
  177: * Files Tutorial::              
  178: * Interpretation and Compilation Semantics and Immediacy Tutorial::  
  179: * Execution Tokens Tutorial::   
  180: * Exceptions Tutorial::         
  181: * Defining Words Tutorial::     
  182: * Arrays and Records Tutorial::  
  183: * POSTPONE Tutorial::           
  184: * Literal Tutorial::            
  185: * Advanced macros Tutorial::    
  186: * Compilation Tokens Tutorial::  
  187: * Wordlists and Search Order Tutorial::  
  188: 
  189: An Introduction to ANS Forth
  190: 
  191: * Introducing the Text Interpreter::  
  192: * Stacks and Postfix notation::  
  193: * Your first definition::       
  194: * How does that work?::         
  195: * Forth is written in Forth::   
  196: * Review - elements of a Forth system::  
  197: * Where to go next::            
  198: * Exercises::                   
  199: 
  200: Forth Words
  201: 
  202: * Notation::                    
  203: * Case insensitivity::          
  204: * Comments::                    
  205: * Boolean Flags::               
  206: * Arithmetic::                  
  207: * Stack Manipulation::          
  208: * Memory::                      
  209: * Control Structures::          
  210: * Defining Words::              
  211: * Interpretation and Compilation Semantics::  
  212: * Tokens for Words::            
  213: * Compiling words::             
  214: * The Text Interpreter::        
  215: * The Input Stream::            
  216: * Word Lists::                  
  217: * Environmental Queries::       
  218: * Files::                       
  219: * Blocks::                      
  220: * Other I/O::                   
  221: * OS command line arguments::   
  222: * Locals::                      
  223: * Structures::                  
  224: * Object-oriented Forth::       
  225: * Programming Tools::           
  226: * C Interface::                 
  227: * Assembler and Code Words::    
  228: * Threading Words::             
  229: * Passing Commands to the OS::  
  230: * Keeping track of Time::       
  231: * Miscellaneous Words::         
  232: 
  233: Arithmetic
  234: 
  235: * Single precision::            
  236: * Double precision::            Double-cell integer arithmetic
  237: * Bitwise operations::          
  238: * Numeric comparison::          
  239: * Mixed precision::             Operations with single and double-cell integers
  240: * Floating Point::              
  241: 
  242: Stack Manipulation
  243: 
  244: * Data stack::                  
  245: * Floating point stack::        
  246: * Return stack::                
  247: * Locals stack::                
  248: * Stack pointer manipulation::  
  249: 
  250: Memory
  251: 
  252: * Memory model::                
  253: * Dictionary allocation::       
  254: * Heap Allocation::             
  255: * Memory Access::               
  256: * Address arithmetic::          
  257: * Memory Blocks::               
  258: 
  259: Control Structures
  260: 
  261: * Selection::                   IF ... ELSE ... ENDIF
  262: * Simple Loops::                BEGIN ...
  263: * Counted Loops::               DO
  264: * Arbitrary control structures::  
  265: * Calls and returns::           
  266: * Exception Handling::          
  267: 
  268: Defining Words
  269: 
  270: * CREATE::                      
  271: * Variables::                   Variables and user variables
  272: * Constants::                   
  273: * Values::                      Initialised variables
  274: * Colon Definitions::           
  275: * Anonymous Definitions::       Definitions without names
  276: * Supplying names::             Passing definition names as strings
  277: * User-defined Defining Words::  
  278: * Deferred words::              Allow forward references
  279: * Aliases::                     
  280: 
  281: User-defined Defining Words
  282: 
  283: * CREATE..DOES> applications::  
  284: * CREATE..DOES> details::       
  285: * Advanced does> usage example::  
  286: * Const-does>::          
  287: 
  288: Interpretation and Compilation Semantics
  289: 
  290: * Combined words::              
  291: 
  292: Tokens for Words
  293: 
  294: * Execution token::             represents execution/interpretation semantics
  295: * Compilation token::           represents compilation semantics
  296: * Name token::                  represents named words
  297: 
  298: Compiling words
  299: 
  300: * Literals::                    Compiling data values
  301: * Macros::                      Compiling words
  302: 
  303: The Text Interpreter
  304: 
  305: * Input Sources::               
  306: * Number Conversion::           
  307: * Interpret/Compile states::    
  308: * Interpreter Directives::      
  309: 
  310: Word Lists
  311: 
  312: * Vocabularies::                
  313: * Why use word lists?::         
  314: * Word list example::           
  315: 
  316: Files
  317: 
  318: * Forth source files::          
  319: * General files::               
  320: * Search Paths::                
  321: 
  322: Search Paths
  323: 
  324: * Source Search Paths::         
  325: * General Search Paths::        
  326: 
  327: Other I/O
  328: 
  329: * Simple numeric output::       Predefined formats
  330: * Formatted numeric output::    Formatted (pictured) output
  331: * String Formats::              How Forth stores strings in memory
  332: * Displaying characters and strings::  Other stuff
  333: * Input::                       Input
  334: * Pipes::                       How to create your own pipes
  335: * Xchars and Unicode::          Non-ASCII characters
  336: 
  337: Locals
  338: 
  339: * Gforth locals::               
  340: * ANS Forth locals::            
  341: 
  342: Gforth locals
  343: 
  344: * Where are locals visible by name?::  
  345: * How long do locals live?::    
  346: * Locals programming style::    
  347: * Locals implementation::       
  348: 
  349: Structures
  350: 
  351: * Why explicit structure support?::  
  352: * Structure Usage::             
  353: * Structure Naming Convention::  
  354: * Structure Implementation::    
  355: * Structure Glossary::          
  356: 
  357: Object-oriented Forth
  358: 
  359: * Why object-oriented programming?::  
  360: * Object-Oriented Terminology::  
  361: * Objects::                     
  362: * OOF::                         
  363: * Mini-OOF::                    
  364: * Comparison with other object models::  
  365: 
  366: The @file{objects.fs} model
  367: 
  368: * Properties of the Objects model::  
  369: * Basic Objects Usage::         
  370: * The Objects base class::      
  371: * Creating objects::            
  372: * Object-Oriented Programming Style::  
  373: * Class Binding::               
  374: * Method conveniences::         
  375: * Classes and Scoping::         
  376: * Dividing classes::            
  377: * Object Interfaces::           
  378: * Objects Implementation::      
  379: * Objects Glossary::            
  380: 
  381: The @file{oof.fs} model
  382: 
  383: * Properties of the OOF model::  
  384: * Basic OOF Usage::             
  385: * The OOF base class::          
  386: * Class Declaration::           
  387: * Class Implementation::        
  388: 
  389: The @file{mini-oof.fs} model
  390: 
  391: * Basic Mini-OOF Usage::        
  392: * Mini-OOF Example::            
  393: * Mini-OOF Implementation::     
  394: 
  395: Programming Tools
  396: 
  397: * Examining::                   Data and Code.
  398: * Forgetting words::            Usually before reloading.
  399: * Debugging::                   Simple and quick.
  400: * Assertions::                  Making your programs self-checking.
  401: * Singlestep Debugger::         Executing your program word by word.
  402: 
  403: Assembler and Code Words
  404: 
  405: * Code and ;code::              
  406: * Common Assembler::            Assembler Syntax
  407: * Common Disassembler::         
  408: * 386 Assembler::               Deviations and special cases
  409: * Alpha Assembler::             Deviations and special cases
  410: * MIPS assembler::              Deviations and special cases
  411: * Other assemblers::            How to write them
  412: 
  413: Tools
  414: 
  415: * ANS Report::                  Report the words used, sorted by wordset.
  416: * Stack depth changes::         Where does this stack item come from?
  417: 
  418: ANS conformance
  419: 
  420: * The Core Words::              
  421: * The optional Block word set::  
  422: * The optional Double Number word set::  
  423: * The optional Exception word set::  
  424: * The optional Facility word set::  
  425: * The optional File-Access word set::  
  426: * The optional Floating-Point word set::  
  427: * The optional Locals word set::  
  428: * The optional Memory-Allocation word set::  
  429: * The optional Programming-Tools word set::  
  430: * The optional Search-Order word set::  
  431: 
  432: The Core Words
  433: 
  434: * core-idef::                   Implementation Defined Options                   
  435: * core-ambcond::                Ambiguous Conditions                
  436: * core-other::                  Other System Documentation                  
  437: 
  438: The optional Block word set
  439: 
  440: * block-idef::                  Implementation Defined Options
  441: * block-ambcond::               Ambiguous Conditions               
  442: * block-other::                 Other System Documentation                 
  443: 
  444: The optional Double Number word set
  445: 
  446: * double-ambcond::              Ambiguous Conditions              
  447: 
  448: The optional Exception word set
  449: 
  450: * exception-idef::              Implementation Defined Options              
  451: 
  452: The optional Facility word set
  453: 
  454: * facility-idef::               Implementation Defined Options               
  455: * facility-ambcond::            Ambiguous Conditions            
  456: 
  457: The optional File-Access word set
  458: 
  459: * file-idef::                   Implementation Defined Options
  460: * file-ambcond::                Ambiguous Conditions                
  461: 
  462: The optional Floating-Point word set
  463: 
  464: * floating-idef::               Implementation Defined Options
  465: * floating-ambcond::            Ambiguous Conditions            
  466: 
  467: The optional Locals word set
  468: 
  469: * locals-idef::                 Implementation Defined Options                 
  470: * locals-ambcond::              Ambiguous Conditions              
  471: 
  472: The optional Memory-Allocation word set
  473: 
  474: * memory-idef::                 Implementation Defined Options                 
  475: 
  476: The optional Programming-Tools word set
  477: 
  478: * programming-idef::            Implementation Defined Options            
  479: * programming-ambcond::         Ambiguous Conditions         
  480: 
  481: The optional Search-Order word set
  482: 
  483: * search-idef::                 Implementation Defined Options                 
  484: * search-ambcond::              Ambiguous Conditions              
  485: 
  486: Emacs and Gforth
  487: 
  488: * Installing gforth.el::        Making Emacs aware of Forth.
  489: * Emacs Tags::                  Viewing the source of a word in Emacs.
  490: * Hilighting::                  Making Forth code look prettier.
  491: * Auto-Indentation::            Customizing auto-indentation.
  492: * Blocks Files::                Reading and writing blocks files.
  493: 
  494: Image Files
  495: 
  496: * Image Licensing Issues::      Distribution terms for images.
  497: * Image File Background::       Why have image files?
  498: * Non-Relocatable Image Files::  don't always work.
  499: * Data-Relocatable Image Files::  are better.
  500: * Fully Relocatable Image Files::  better yet.
  501: * Stack and Dictionary Sizes::  Setting the default sizes for an image.
  502: * Running Image Files::         @code{gforth -i @i{file}} or @i{file}.
  503: * Modifying the Startup Sequence::  and turnkey applications.
  504: 
  505: Fully Relocatable Image Files
  506: 
  507: * gforthmi::                    The normal way
  508: * cross.fs::                    The hard way
  509: 
  510: Engine
  511: 
  512: * Portability::                 
  513: * Threading::                   
  514: * Primitives::                  
  515: * Performance::                 
  516: 
  517: Threading
  518: 
  519: * Scheduling::                  
  520: * Direct or Indirect Threaded?::  
  521: * Dynamic Superinstructions::   
  522: * DOES>::                       
  523: 
  524: Primitives
  525: 
  526: * Automatic Generation::        
  527: * TOS Optimization::            
  528: * Produced code::               
  529: 
  530: Cross Compiler
  531: 
  532: * Using the Cross Compiler::    
  533: * How the Cross Compiler Works::  
  534: 
  535: Licenses
  536: 
  537: * GNU Free Documentation License::  License for copying this manual.
  538: * Copying::                         GPL (for copying this software).
  539: 
  540: @end detailmenu
  541: @end menu
  542: 
  543: @c ----------------------------------------------------------
  544: @iftex
  545: @unnumbered Preface
  546: @cindex Preface
  547: This manual documents Gforth. Some introductory material is provided for
  548: readers who are unfamiliar with Forth or who are migrating to Gforth
  549: from other Forth compilers. However, this manual is primarily a
  550: reference manual.
  551: @end iftex
  552: 
  553: @comment TODO much more blurb here.
  554: 
  555: @c ******************************************************************
  556: @node Goals, Gforth Environment, Top, Top
  557: @comment node-name,     next,           previous, up
  558: @chapter Goals of Gforth
  559: @cindex goals of the Gforth project
  560: The goal of the Gforth Project is to develop a standard model for
  561: ANS Forth. This can be split into several subgoals:
  562: 
  563: @itemize @bullet
  564: @item
  565: Gforth should conform to the ANS Forth Standard.
  566: @item
  567: It should be a model, i.e. it should define all the
  568: implementation-dependent things.
  569: @item
  570: It should become standard, i.e. widely accepted and used. This goal
  571: is the most difficult one.
  572: @end itemize
  573: 
  574: To achieve these goals Gforth should be
  575: @itemize @bullet
  576: @item
  577: Similar to previous models (fig-Forth, F83)
  578: @item
  579: Powerful. It should provide for all the things that are considered
  580: necessary today and even some that are not yet considered necessary.
  581: @item
  582: Efficient. It should not get the reputation of being exceptionally
  583: slow.
  584: @item
  585: Free.
  586: @item
  587: Available on many machines/easy to port.
  588: @end itemize
  589: 
  590: Have we achieved these goals? Gforth conforms to the ANS Forth
  591: standard. It may be considered a model, but we have not yet documented
  592: which parts of the model are stable and which parts we are likely to
  593: change. It certainly has not yet become a de facto standard, but it
  594: appears to be quite popular. It has some similarities to and some
  595: differences from previous models. It has some powerful features, but not
  596: yet everything that we envisioned. We certainly have achieved our
  597: execution speed goals (@pxref{Performance})@footnote{However, in 1998
  598: the bar was raised when the major commercial Forth vendors switched to
  599: native code compilers.}.  It is free and available on many machines.
  600: 
  601: @c ******************************************************************
  602: @node Gforth Environment, Tutorial, Goals, Top
  603: @chapter Gforth Environment
  604: @cindex Gforth environment
  605: 
  606: Note: ultimately, the Gforth man page will be auto-generated from the
  607: material in this chapter.
  608: 
  609: @menu
  610: * Invoking Gforth::             Getting in
  611: * Leaving Gforth::              Getting out
  612: * Command-line editing::        
  613: * Environment variables::       that affect how Gforth starts up
  614: * Gforth Files::                What gets installed and where
  615: * Gforth in pipes::             
  616: * Startup speed::               When 35ms is not fast enough ...
  617: @end menu
  618: 
  619: For related information about the creation of images see @ref{Image Files}.
  620: 
  621: @comment ----------------------------------------------
  622: @node Invoking Gforth, Leaving Gforth, Gforth Environment, Gforth Environment
  623: @section Invoking Gforth
  624: @cindex invoking Gforth
  625: @cindex running Gforth
  626: @cindex command-line options
  627: @cindex options on the command line
  628: @cindex flags on the command line
  629: 
  630: Gforth is made up of two parts; an executable ``engine'' (named
  631: @command{gforth} or @command{gforth-fast}) and an image file. To start it, you
  632: will usually just say @code{gforth} -- this automatically loads the
  633: default image file @file{gforth.fi}. In many other cases the default
  634: Gforth image will be invoked like this:
  635: @example
  636: gforth [file | -e forth-code] ...
  637: @end example
  638: @noindent
  639: This interprets the contents of the files and the Forth code in the order they
  640: are given.
  641: 
  642: In addition to the @command{gforth} engine, there is also an engine
  643: called @command{gforth-fast}, which is faster, but gives less
  644: informative error messages (@pxref{Error messages}) and may catch some
  645: stack underflows later or not at all.  You should use it for debugged,
  646: performance-critical programs.
  647: 
  648: Moreover, there is an engine called @command{gforth-itc}, which is
  649: useful in some backwards-compatibility situations (@pxref{Direct or
  650: Indirect Threaded?}).
  651: 
  652: In general, the command line looks like this:
  653: 
  654: @example
  655: gforth[-fast] [engine options] [image options]
  656: @end example
  657: 
  658: The engine options must come before the rest of the command
  659: line. They are:
  660: 
  661: @table @code
  662: @cindex -i, command-line option
  663: @cindex --image-file, command-line option
  664: @item --image-file @i{file}
  665: @itemx -i @i{file}
  666: Loads the Forth image @i{file} instead of the default
  667: @file{gforth.fi} (@pxref{Image Files}).
  668: 
  669: @cindex --appl-image, command-line option
  670: @item --appl-image @i{file}
  671: Loads the image @i{file} and leaves all further command-line arguments
  672: to the image (instead of processing them as engine options).  This is
  673: useful for building executable application images on Unix, built with
  674: @code{gforthmi --application ...}.
  675: 
  676: @cindex --path, command-line option
  677: @cindex -p, command-line option
  678: @item --path @i{path}
  679: @itemx -p @i{path}
  680: Uses @i{path} for searching the image file and Forth source code files
  681: instead of the default in the environment variable @code{GFORTHPATH} or
  682: the path specified at installation time (e.g.,
  683: @file{/usr/local/share/gforth/0.2.0:.}). A path is given as a list of
  684: directories, separated by @samp{:} (on Unix) or @samp{;} (on other OSs).
  685: 
  686: @cindex --dictionary-size, command-line option
  687: @cindex -m, command-line option
  688: @cindex @i{size} parameters for command-line options
  689: @cindex size of the dictionary and the stacks
  690: @item --dictionary-size @i{size}
  691: @itemx -m @i{size}
  692: Allocate @i{size} space for the Forth dictionary space instead of
  693: using the default specified in the image (typically 256K). The
  694: @i{size} specification for this and subsequent options consists of
  695: an integer and a unit (e.g.,
  696: @code{4M}). The unit can be one of @code{b} (bytes), @code{e} (element
  697: size, in this case Cells), @code{k} (kilobytes), @code{M} (Megabytes),
  698: @code{G} (Gigabytes), and @code{T} (Terabytes). If no unit is specified,
  699: @code{e} is used.
  700: 
  701: @cindex --data-stack-size, command-line option
  702: @cindex -d, command-line option
  703: @item --data-stack-size @i{size}
  704: @itemx -d @i{size}
  705: Allocate @i{size} space for the data stack instead of using the
  706: default specified in the image (typically 16K).
  707: 
  708: @cindex --return-stack-size, command-line option
  709: @cindex -r, command-line option
  710: @item --return-stack-size @i{size}
  711: @itemx -r @i{size}
  712: Allocate @i{size} space for the return stack instead of using the
  713: default specified in the image (typically 15K).
  714: 
  715: @cindex --fp-stack-size, command-line option
  716: @cindex -f, command-line option
  717: @item --fp-stack-size @i{size}
  718: @itemx -f @i{size}
  719: Allocate @i{size} space for the floating point stack instead of
  720: using the default specified in the image (typically 15.5K). In this case
  721: the unit specifier @code{e} refers to floating point numbers.
  722: 
  723: @cindex --locals-stack-size, command-line option
  724: @cindex -l, command-line option
  725: @item --locals-stack-size @i{size}
  726: @itemx -l @i{size}
  727: Allocate @i{size} space for the locals stack instead of using the
  728: default specified in the image (typically 14.5K).
  729: 
  730: @cindex -h, command-line option
  731: @cindex --help, command-line option
  732: @item --help
  733: @itemx -h
  734: Print a message about the command-line options
  735: 
  736: @cindex -v, command-line option
  737: @cindex --version, command-line option
  738: @item --version
  739: @itemx -v
  740: Print version and exit
  741: 
  742: @cindex --debug, command-line option
  743: @item --debug
  744: Print some information useful for debugging on startup.
  745: 
  746: @cindex --offset-image, command-line option
  747: @item --offset-image
  748: Start the dictionary at a slightly different position than would be used
  749: otherwise (useful for creating data-relocatable images,
  750: @pxref{Data-Relocatable Image Files}).
  751: 
  752: @cindex --no-offset-im, command-line option
  753: @item --no-offset-im
  754: Start the dictionary at the normal position.
  755: 
  756: @cindex --clear-dictionary, command-line option
  757: @item --clear-dictionary
  758: Initialize all bytes in the dictionary to 0 before loading the image
  759: (@pxref{Data-Relocatable Image Files}).
  760: 
  761: @cindex --die-on-signal, command-line-option
  762: @item --die-on-signal
  763: Normally Gforth handles most signals (e.g., the user interrupt SIGINT,
  764: or the segmentation violation SIGSEGV) by translating it into a Forth
  765: @code{THROW}. With this option, Gforth exits if it receives such a
  766: signal. This option is useful when the engine and/or the image might be
  767: severely broken (such that it causes another signal before recovering
  768: from the first); this option avoids endless loops in such cases.
  769: 
  770: @cindex --no-dynamic, command-line option
  771: @cindex --dynamic, command-line option
  772: @item --no-dynamic
  773: @item --dynamic
  774: Disable or enable dynamic superinstructions with replication
  775: (@pxref{Dynamic Superinstructions}).
  776: 
  777: @cindex --no-super, command-line option
  778: @item --no-super
  779: Disable dynamic superinstructions, use just dynamic replication; this is
  780: useful if you want to patch threaded code (@pxref{Dynamic
  781: Superinstructions}).
  782: 
  783: @cindex --ss-number, command-line option
  784: @item --ss-number=@var{N}
  785: Use only the first @var{N} static superinstructions compiled into the
  786: engine (default: use them all; note that only @code{gforth-fast} has
  787: any).  This option is useful for measuring the performance impact of
  788: static superinstructions.
  789: 
  790: @cindex --ss-min-..., command-line options
  791: @item --ss-min-codesize
  792: @item --ss-min-ls
  793: @item --ss-min-lsu
  794: @item --ss-min-nexts
  795: Use specified metric for determining the cost of a primitive or static
  796: superinstruction for static superinstruction selection.  @code{Codesize}
  797: is the native code size of the primive or static superinstruction,
  798: @code{ls} is the number of loads and stores, @code{lsu} is the number of
  799: loads, stores, and updates, and @code{nexts} is the number of dispatches
  800: (not taking dynamic superinstructions into account), i.e. every
  801: primitive or static superinstruction has cost 1. Default:
  802: @code{codesize} if you use dynamic code generation, otherwise
  803: @code{nexts}.
  804: 
  805: @cindex --ss-greedy, command-line option
  806: @item --ss-greedy
  807: This option is useful for measuring the performance impact of static
  808: superinstructions.  By default, an optimal shortest-path algorithm is
  809: used for selecting static superinstructions.  With @option{--ss-greedy}
  810: this algorithm is modified to assume that anything after the static
  811: superinstruction currently under consideration is not combined into
  812: static superinstructions.  With @option{--ss-min-nexts} this produces
  813: the same result as a greedy algorithm that always selects the longest
  814: superinstruction available at the moment.  E.g., if there are
  815: superinstructions AB and BCD, then for the sequence A B C D the optimal
  816: algorithm will select A BCD and the greedy algorithm will select AB C D.
  817: 
  818: @cindex --print-metrics, command-line option
  819: @item --print-metrics
  820: Prints some metrics used during static superinstruction selection:
  821: @code{code size} is the actual size of the dynamically generated code.
  822: @code{Metric codesize} is the sum of the codesize metrics as seen by
  823: static superinstruction selection; there is a difference from @code{code
  824: size}, because not all primitives and static superinstructions are
  825: compiled into dynamically generated code, and because of markers.  The
  826: other metrics correspond to the @option{ss-min-...} options.  This
  827: option is useful for evaluating the effects of the @option{--ss-...}
  828: options.
  829: 
  830: @end table
  831: 
  832: @cindex loading files at startup
  833: @cindex executing code on startup
  834: @cindex batch processing with Gforth
  835: As explained above, the image-specific command-line arguments for the
  836: default image @file{gforth.fi} consist of a sequence of filenames and
  837: @code{-e @var{forth-code}} options that are interpreted in the sequence
  838: in which they are given. The @code{-e @var{forth-code}} or
  839: @code{--evaluate @var{forth-code}} option evaluates the Forth code. This
  840: option takes only one argument; if you want to evaluate more Forth
  841: words, you have to quote them or use @code{-e} several times. To exit
  842: after processing the command line (instead of entering interactive mode)
  843: append @code{-e bye} to the command line.  You can also process the
  844: command-line arguments with a Forth program (@pxref{OS command line
  845: arguments}).
  846: 
  847: @cindex versions, invoking other versions of Gforth
  848: If you have several versions of Gforth installed, @code{gforth} will
  849: invoke the version that was installed last. @code{gforth-@i{version}}
  850: invokes a specific version. If your environment contains the variable
  851: @code{GFORTHPATH}, you may want to override it by using the
  852: @code{--path} option.
  853: 
  854: Not yet implemented:
  855: On startup the system first executes the system initialization file
  856: (unless the option @code{--no-init-file} is given; note that the system
  857: resulting from using this option may not be ANS Forth conformant). Then
  858: the user initialization file @file{.gforth.fs} is executed, unless the
  859: option @code{--no-rc} is given; this file is searched for in @file{.},
  860: then in @file{~}, then in the normal path (see above).
  861: 
  862: 
  863: 
  864: @comment ----------------------------------------------
  865: @node Leaving Gforth, Command-line editing, Invoking Gforth, Gforth Environment
  866: @section Leaving Gforth
  867: @cindex Gforth - leaving
  868: @cindex leaving Gforth
  869: 
  870: You can leave Gforth by typing @code{bye} or @kbd{Ctrl-d} (at the start
  871: of a line) or (if you invoked Gforth with the @code{--die-on-signal}
  872: option) @kbd{Ctrl-c}. When you leave Gforth, all of your definitions and
  873: data are discarded.  For ways of saving the state of the system before
  874: leaving Gforth see @ref{Image Files}.
  875: 
  876: doc-bye
  877: 
  878: 
  879: @comment ----------------------------------------------
  880: @node Command-line editing, Environment variables, Leaving Gforth, Gforth Environment
  881: @section Command-line editing
  882: @cindex command-line editing
  883: 
  884: Gforth maintains a history file that records every line that you type to
  885: the text interpreter. This file is preserved between sessions, and is
  886: used to provide a command-line recall facility; if you type @kbd{Ctrl-P}
  887: repeatedly you can recall successively older commands from this (or
  888: previous) session(s). The full list of command-line editing facilities is:
  889: 
  890: @itemize @bullet
  891: @item
  892: @kbd{Ctrl-p} (``previous'') (or up-arrow) to recall successively older
  893: commands from the history buffer.
  894: @item
  895: @kbd{Ctrl-n} (``next'') (or down-arrow) to recall successively newer commands
  896: from the history buffer.
  897: @item
  898: @kbd{Ctrl-f} (or right-arrow) to move the cursor right, non-destructively.
  899: @item
  900: @kbd{Ctrl-b} (or left-arrow) to move the cursor left, non-destructively.
  901: @item
  902: @kbd{Ctrl-h} (backspace) to delete the character to the left of the cursor,
  903: closing up the line.
  904: @item
  905: @kbd{Ctrl-k} to delete (``kill'') from the cursor to the end of the line.
  906: @item
  907: @kbd{Ctrl-a} to move the cursor to the start of the line.
  908: @item
  909: @kbd{Ctrl-e} to move the cursor to the end of the line.
  910: @item
  911: @key{RET} (@kbd{Ctrl-m}) or @key{LFD} (@kbd{Ctrl-j}) to submit the current
  912: line.
  913: @item
  914: @key{TAB} to step through all possible full-word completions of the word
  915: currently being typed.
  916: @item
  917: @kbd{Ctrl-d} on an empty line line to terminate Gforth (gracefully,
  918: using @code{bye}). 
  919: @item
  920: @kbd{Ctrl-x} (or @code{Ctrl-d} on a non-empty line) to delete the
  921: character under the cursor.
  922: @end itemize
  923: 
  924: When editing, displayable characters are inserted to the left of the
  925: cursor position; the line is always in ``insert'' (as opposed to
  926: ``overstrike'') mode.
  927: 
  928: @cindex history file
  929: @cindex @file{.gforth-history}
  930: On Unix systems, the history file is @file{~/.gforth-history} by
  931: default@footnote{i.e. it is stored in the user's home directory.}. You
  932: can find out the name and location of your history file using:
  933: 
  934: @example 
  935: history-file type \ Unix-class systems
  936: 
  937: history-file type \ Other systems
  938: history-dir  type
  939: @end example
  940: 
  941: If you enter long definitions by hand, you can use a text editor to
  942: paste them out of the history file into a Forth source file for reuse at
  943: a later time.
  944: 
  945: Gforth never trims the size of the history file, so you should do this
  946: periodically, if necessary.
  947: 
  948: @comment this is all defined in history.fs
  949: @comment NAC TODO the ctrl-D behaviour can either do a bye or a beep.. how is that option
  950: @comment chosen?
  951: 
  952: 
  953: @comment ----------------------------------------------
  954: @node Environment variables, Gforth Files, Command-line editing, Gforth Environment
  955: @section Environment variables
  956: @cindex environment variables
  957: 
  958: Gforth uses these environment variables:
  959: 
  960: @itemize @bullet
  961: @item
  962: @cindex @code{GFORTHHIST} -- environment variable
  963: @code{GFORTHHIST} -- (Unix systems only) specifies the directory in which to
  964: open/create the history file, @file{.gforth-history}. Default:
  965: @code{$HOME}.
  966: 
  967: @item
  968: @cindex @code{GFORTHPATH} -- environment variable
  969: @code{GFORTHPATH} -- specifies the path used when searching for the gforth image file and
  970: for Forth source-code files.
  971: 
  972: @item
  973: @cindex @code{LANG} -- environment variable
  974: @code{LANG} -- see @code{LC_CTYPE}
  975: 
  976: @item
  977: @cindex @code{LC_ALL} -- environment variable
  978: @code{LC_ALL} -- see @code{LC_CTYPE}
  979: 
  980: @item
  981: @cindex @code{LC_CTYPE} -- environment variable
  982: @code{LC_CTYPE} -- If this variable contains ``UTF-8'' on Gforth
  983: startup, Gforth uses the UTF-8 encoding for strings internally and
  984: expects its input and produces its output in UTF-8 encoding, otherwise
  985: the encoding is 8bit (see @pxref{Xchars and Unicode}).  If this
  986: environment variable is unset, Gforth looks in @code{LC_ALL}, and if
  987: that is unset, in @code{LANG}.
  988: 
  989: @item
  990: @cindex @code{GFORTHSYSTEMPREFIX} -- environment variable
  991: 
  992: @code{GFORTHSYSTEMPREFIX} -- specifies what to prepend to the argument
  993: of @code{system} before passing it to C's @code{system()}.  Default:
  994: @code{"./$COMSPEC /c "} on Windows, @code{""} on other OSs.  The prefix
  995: and the command are directly concatenated, so if a space between them is
  996: necessary, append it to the prefix.
  997: 
  998: @item
  999: @cindex @code{GFORTH} -- environment variable
 1000: @code{GFORTH} -- used by @file{gforthmi}, @xref{gforthmi}.
 1001: 
 1002: @item
 1003: @cindex @code{GFORTHD} -- environment variable
 1004: @code{GFORTHD} -- used by @file{gforthmi}, @xref{gforthmi}.
 1005: 
 1006: @item
 1007: @cindex @code{TMP}, @code{TEMP} - environment variable
 1008: @code{TMP}, @code{TEMP} - (non-Unix systems only) used as a potential
 1009: location for the history file.
 1010: @end itemize
 1011: 
 1012: @comment also POSIXELY_CORRECT LINES COLUMNS HOME but no interest in
 1013: @comment mentioning these.
 1014: 
 1015: All the Gforth environment variables default to sensible values if they
 1016: are not set.
 1017: 
 1018: 
 1019: @comment ----------------------------------------------
 1020: @node Gforth Files, Gforth in pipes, Environment variables, Gforth Environment
 1021: @section Gforth files
 1022: @cindex Gforth files
 1023: 
 1024: When you install Gforth on a Unix system, it installs files in these
 1025: locations by default:
 1026: 
 1027: @itemize @bullet
 1028: @item
 1029: @file{/usr/local/bin/gforth}
 1030: @item
 1031: @file{/usr/local/bin/gforthmi}
 1032: @item
 1033: @file{/usr/local/man/man1/gforth.1} - man page.
 1034: @item
 1035: @file{/usr/local/info} - the Info version of this manual.
 1036: @item
 1037: @file{/usr/local/lib/gforth/<version>/...} - Gforth @file{.fi} files.
 1038: @item
 1039: @file{/usr/local/share/gforth/<version>/TAGS} - Emacs TAGS file.
 1040: @item
 1041: @file{/usr/local/share/gforth/<version>/...} - Gforth source files.
 1042: @item
 1043: @file{.../emacs/site-lisp/gforth.el} - Emacs gforth mode.
 1044: @end itemize
 1045: 
 1046: You can select different places for installation by using
 1047: @code{configure} options (listed with @code{configure --help}).
 1048: 
 1049: @comment ----------------------------------------------
 1050: @node Gforth in pipes, Startup speed, Gforth Files, Gforth Environment
 1051: @section Gforth in pipes
 1052: @cindex pipes, Gforth as part of
 1053: 
 1054: Gforth can be used in pipes created elsewhere (described here).  It can
 1055: also create pipes on its own (@pxref{Pipes}).
 1056: 
 1057: @cindex input from pipes
 1058: If you pipe into Gforth, your program should read with @code{read-file}
 1059: or @code{read-line} from @code{stdin} (@pxref{General files}).
 1060: @code{Key} does not recognize the end of input.  Words like
 1061: @code{accept} echo the input and are therefore usually not useful for
 1062: reading from a pipe.  You have to invoke the Forth program with an OS
 1063: command-line option, as you have no chance to use the Forth command line
 1064: (the text interpreter would try to interpret the pipe input).
 1065: 
 1066: @cindex output in pipes
 1067: You can output to a pipe with @code{type}, @code{emit}, @code{cr} etc.
 1068: 
 1069: @cindex silent exiting from Gforth
 1070: When you write to a pipe that has been closed at the other end, Gforth
 1071: receives a SIGPIPE signal (``pipe broken'').  Gforth translates this
 1072: into the exception @code{broken-pipe-error}.  If your application does
 1073: not catch that exception, the system catches it and exits, usually
 1074: silently (unless you were working on the Forth command line; then it
 1075: prints an error message and exits).  This is usually the desired
 1076: behaviour.
 1077: 
 1078: If you do not like this behaviour, you have to catch the exception
 1079: yourself, and react to it.
 1080: 
 1081: Here's an example of an invocation of Gforth that is usable in a pipe:
 1082: 
 1083: @example
 1084: gforth -e ": foo begin pad dup 10 stdin read-file throw dup while \
 1085:  type repeat ; foo bye"
 1086: @end example
 1087: 
 1088: This example just copies the input verbatim to the output.  A very
 1089: simple pipe containing this example looks like this:
 1090: 
 1091: @example
 1092: cat startup.fs |
 1093: gforth -e ": foo begin pad dup 80 stdin read-file throw dup while \
 1094:  type repeat ; foo bye"|
 1095: head
 1096: @end example
 1097: 
 1098: @cindex stderr and pipes
 1099: Pipes involving Gforth's @code{stderr} output do not work.
 1100: 
 1101: @comment ----------------------------------------------
 1102: @node Startup speed,  , Gforth in pipes, Gforth Environment
 1103: @section Startup speed
 1104: @cindex Startup speed
 1105: @cindex speed, startup
 1106: 
 1107: If Gforth is used for CGI scripts or in shell scripts, its startup
 1108: speed may become a problem.  On a 300MHz 21064a under Linux-2.2.13 with
 1109: glibc-2.0.7, @code{gforth -e bye} takes about 24.6ms user and 11.3ms
 1110: system time.
 1111: 
 1112: If startup speed is a problem, you may consider the following ways to
 1113: improve it; or you may consider ways to reduce the number of startups
 1114: (for example, by using Fast-CGI).
 1115: 
 1116: An easy step that influences Gforth startup speed is the use of the
 1117: @option{--no-dynamic} option; this decreases image loading speed, but
 1118: increases compile-time and run-time.
 1119: 
 1120: Another step to improve startup speed is to statically link Gforth, by
 1121: building it with @code{XLDFLAGS=-static}.  This requires more memory for
 1122: the code and will therefore slow down the first invocation, but
 1123: subsequent invocations avoid the dynamic linking overhead.  Another
 1124: disadvantage is that Gforth won't profit from library upgrades.  As a
 1125: result, @code{gforth-static -e bye} takes about 17.1ms user and
 1126: 8.2ms system time.
 1127: 
 1128: The next step to improve startup speed is to use a non-relocatable image
 1129: (@pxref{Non-Relocatable Image Files}).  You can create this image with
 1130: @code{gforth -e "savesystem gforthnr.fi bye"} and later use it with
 1131: @code{gforth -i gforthnr.fi ...}.  This avoids the relocation overhead
 1132: and a part of the copy-on-write overhead.  The disadvantage is that the
 1133: non-relocatable image does not work if the OS gives Gforth a different
 1134: address for the dictionary, for whatever reason; so you better provide a
 1135: fallback on a relocatable image.  @code{gforth-static -i gforthnr.fi -e
 1136: bye} takes about 15.3ms user and 7.5ms system time.
 1137: 
 1138: The final step is to disable dictionary hashing in Gforth.  Gforth
 1139: builds the hash table on startup, which takes much of the startup
 1140: overhead. You can do this by commenting out the @code{include hash.fs}
 1141: in @file{startup.fs} and everything that requires @file{hash.fs} (at the
 1142: moment @file{table.fs} and @file{ekey.fs}) and then doing @code{make}.
 1143: The disadvantages are that functionality like @code{table} and
 1144: @code{ekey} is missing and that text interpretation (e.g., compiling)
 1145: now takes much longer. So, you should only use this method if there is
 1146: no significant text interpretation to perform (the script should be
 1147: compiled into the image, amongst other things).  @code{gforth-static -i
 1148: gforthnrnh.fi -e bye} takes about 2.1ms user and 6.1ms system time.
 1149: 
 1150: @c ******************************************************************
 1151: @node Tutorial, Introduction, Gforth Environment, Top
 1152: @chapter Forth Tutorial
 1153: @cindex Tutorial
 1154: @cindex Forth Tutorial
 1155: 
 1156: @c Topics from nac's Introduction that could be mentioned:
 1157: @c press <ret> after each line
 1158: @c Prompt
 1159: @c numbers vs. words in dictionary on text interpretation
 1160: @c what happens on redefinition
 1161: @c parsing words (in particular, defining words)
 1162: 
 1163: The difference of this chapter from the Introduction
 1164: (@pxref{Introduction}) is that this tutorial is more fast-paced, should
 1165: be used while sitting in front of a computer, and covers much more
 1166: material, but does not explain how the Forth system works.
 1167: 
 1168: This tutorial can be used with any ANS-compliant Forth; any
 1169: Gforth-specific features are marked as such and you can skip them if you
 1170: work with another Forth.  This tutorial does not explain all features of
 1171: Forth, just enough to get you started and give you some ideas about the
 1172: facilities available in Forth.  Read the rest of the manual and the
 1173: standard when you are through this.
 1174: 
 1175: The intended way to use this tutorial is that you work through it while
 1176: sitting in front of the console, take a look at the examples and predict
 1177: what they will do, then try them out; if the outcome is not as expected,
 1178: find out why (e.g., by trying out variations of the example), so you
 1179: understand what's going on.  There are also some assignments that you
 1180: should solve.
 1181: 
 1182: This tutorial assumes that you have programmed before and know what,
 1183: e.g., a loop is.
 1184: 
 1185: @c !! explain compat library
 1186: 
 1187: @menu
 1188: * Starting Gforth Tutorial::    
 1189: * Syntax Tutorial::             
 1190: * Crash Course Tutorial::       
 1191: * Stack Tutorial::              
 1192: * Arithmetics Tutorial::        
 1193: * Stack Manipulation Tutorial::  
 1194: * Using files for Forth code Tutorial::  
 1195: * Comments Tutorial::           
 1196: * Colon Definitions Tutorial::  
 1197: * Decompilation Tutorial::      
 1198: * Stack-Effect Comments Tutorial::  
 1199: * Types Tutorial::              
 1200: * Factoring Tutorial::          
 1201: * Designing the stack effect Tutorial::  
 1202: * Local Variables Tutorial::    
 1203: * Conditional execution Tutorial::  
 1204: * Flags and Comparisons Tutorial::  
 1205: * General Loops Tutorial::      
 1206: * Counted loops Tutorial::      
 1207: * Recursion Tutorial::          
 1208: * Leaving definitions or loops Tutorial::  
 1209: * Return Stack Tutorial::       
 1210: * Memory Tutorial::             
 1211: * Characters and Strings Tutorial::  
 1212: * Alignment Tutorial::          
 1213: * Files Tutorial::              
 1214: * Interpretation and Compilation Semantics and Immediacy Tutorial::  
 1215: * Execution Tokens Tutorial::   
 1216: * Exceptions Tutorial::         
 1217: * Defining Words Tutorial::     
 1218: * Arrays and Records Tutorial::  
 1219: * POSTPONE Tutorial::           
 1220: * Literal Tutorial::            
 1221: * Advanced macros Tutorial::    
 1222: * Compilation Tokens Tutorial::  
 1223: * Wordlists and Search Order Tutorial::  
 1224: @end menu
 1225: 
 1226: @node Starting Gforth Tutorial, Syntax Tutorial, Tutorial, Tutorial
 1227: @section Starting Gforth
 1228: @cindex starting Gforth tutorial
 1229: You can start Gforth by typing its name:
 1230: 
 1231: @example
 1232: gforth
 1233: @end example
 1234: 
 1235: That puts you into interactive mode; you can leave Gforth by typing
 1236: @code{bye}.  While in Gforth, you can edit the command line and access
 1237: the command line history with cursor keys, similar to bash.
 1238: 
 1239: 
 1240: @node Syntax Tutorial, Crash Course Tutorial, Starting Gforth Tutorial, Tutorial
 1241: @section Syntax
 1242: @cindex syntax tutorial
 1243: 
 1244: A @dfn{word} is a sequence of arbitrary characters (expcept white
 1245: space).  Words are separated by white space.  E.g., each of the
 1246: following lines contains exactly one word:
 1247: 
 1248: @example
 1249: word
 1250: !@@#$%^&*()
 1251: 1234567890
 1252: 5!a
 1253: @end example
 1254: 
 1255: A frequent beginner's error is to leave away necessary white space,
 1256: resulting in an error like @samp{Undefined word}; so if you see such an
 1257: error, check if you have put spaces wherever necessary.
 1258: 
 1259: @example
 1260: ." hello, world" \ correct
 1261: ."hello, world"  \ gives an "Undefined word" error
 1262: @end example
 1263: 
 1264: Gforth and most other Forth systems ignore differences in case (they are
 1265: case-insensitive), i.e., @samp{word} is the same as @samp{Word}.  If
 1266: your system is case-sensitive, you may have to type all the examples
 1267: given here in upper case.
 1268: 
 1269: 
 1270: @node Crash Course Tutorial, Stack Tutorial, Syntax Tutorial, Tutorial
 1271: @section Crash Course
 1272: 
 1273: Type
 1274: 
 1275: @example
 1276: 0 0 !
 1277: here execute
 1278: ' catch >body 20 erase abort
 1279: ' (quit) >body 20 erase
 1280: @end example
 1281: 
 1282: The last two examples are guaranteed to destroy parts of Gforth (and
 1283: most other systems), so you better leave Gforth afterwards (if it has
 1284: not finished by itself).  On some systems you may have to kill gforth
 1285: from outside (e.g., in Unix with @code{kill}).
 1286: 
 1287: Now that you know how to produce crashes (and that there's not much to
 1288: them), let's learn how to produce meaningful programs.
 1289: 
 1290: 
 1291: @node Stack Tutorial, Arithmetics Tutorial, Crash Course Tutorial, Tutorial
 1292: @section Stack
 1293: @cindex stack tutorial
 1294: 
 1295: The most obvious feature of Forth is the stack.  When you type in a
 1296: number, it is pushed on the stack.  You can display the content of the
 1297: stack with @code{.s}.
 1298: 
 1299: @example
 1300: 1 2 .s
 1301: 3 .s
 1302: @end example
 1303: 
 1304: @code{.s} displays the top-of-stack to the right, i.e., the numbers
 1305: appear in @code{.s} output as they appeared in the input.
 1306: 
 1307: You can print the top of stack element with @code{.}.
 1308: 
 1309: @example
 1310: 1 2 3 . . .
 1311: @end example
 1312: 
 1313: In general, words consume their stack arguments (@code{.s} is an
 1314: exception).
 1315: 
 1316: @quotation Assignment
 1317: What does the stack contain after @code{5 6 7 .}?
 1318: @end quotation
 1319: 
 1320: 
 1321: @node Arithmetics Tutorial, Stack Manipulation Tutorial, Stack Tutorial, Tutorial
 1322: @section Arithmetics
 1323: @cindex arithmetics tutorial
 1324: 
 1325: The words @code{+}, @code{-}, @code{*}, @code{/}, and @code{mod} always
 1326: operate on the top two stack items:
 1327: 
 1328: @example
 1329: 2 2 .s
 1330: + .s
 1331: .
 1332: 2 1 - .
 1333: 7 3 mod .
 1334: @end example
 1335: 
 1336: The operands of @code{-}, @code{/}, and @code{mod} are in the same order
 1337: as in the corresponding infix expression (this is generally the case in
 1338: Forth).
 1339: 
 1340: Parentheses are superfluous (and not available), because the order of
 1341: the words unambiguously determines the order of evaluation and the
 1342: operands:
 1343: 
 1344: @example
 1345: 3 4 + 5 * .
 1346: 3 4 5 * + .
 1347: @end example
 1348: 
 1349: @quotation Assignment
 1350: What are the infix expressions corresponding to the Forth code above?
 1351: Write @code{6-7*8+9} in Forth notation@footnote{This notation is also
 1352: known as Postfix or RPN (Reverse Polish Notation).}.
 1353: @end quotation
 1354: 
 1355: To change the sign, use @code{negate}:
 1356: 
 1357: @example
 1358: 2 negate .
 1359: @end example
 1360: 
 1361: @quotation Assignment
 1362: Convert -(-3)*4-5 to Forth.
 1363: @end quotation
 1364: 
 1365: @code{/mod} performs both @code{/} and @code{mod}.
 1366: 
 1367: @example
 1368: 7 3 /mod . .
 1369: @end example
 1370: 
 1371: Reference: @ref{Arithmetic}.
 1372: 
 1373: 
 1374: @node Stack Manipulation Tutorial, Using files for Forth code Tutorial, Arithmetics Tutorial, Tutorial
 1375: @section Stack Manipulation
 1376: @cindex stack manipulation tutorial
 1377: 
 1378: Stack manipulation words rearrange the data on the stack.
 1379: 
 1380: @example
 1381: 1 .s drop .s
 1382: 1 .s dup .s drop drop .s
 1383: 1 2 .s over .s drop drop drop
 1384: 1 2 .s swap .s drop drop
 1385: 1 2 3 .s rot .s drop drop drop
 1386: @end example
 1387: 
 1388: These are the most important stack manipulation words.  There are also
 1389: variants that manipulate twice as many stack items:
 1390: 
 1391: @example
 1392: 1 2 3 4 .s 2swap .s 2drop 2drop
 1393: @end example
 1394: 
 1395: Two more stack manipulation words are:
 1396: 
 1397: @example
 1398: 1 2 .s nip .s drop
 1399: 1 2 .s tuck .s 2drop drop
 1400: @end example
 1401: 
 1402: @quotation Assignment
 1403: Replace @code{nip} and @code{tuck} with combinations of other stack
 1404: manipulation words.
 1405: 
 1406: @example
 1407: Given:          How do you get:
 1408: 1 2 3           3 2 1           
 1409: 1 2 3           1 2 3 2                 
 1410: 1 2 3           1 2 3 3                 
 1411: 1 2 3           1 3 3           
 1412: 1 2 3           2 1 3           
 1413: 1 2 3 4         4 3 2 1         
 1414: 1 2 3           1 2 3 1 2 3             
 1415: 1 2 3 4         1 2 3 4 1 2             
 1416: 1 2 3
 1417: 1 2 3           1 2 3 4                 
 1418: 1 2 3           1 3             
 1419: @end example
 1420: @end quotation
 1421: 
 1422: @example
 1423: 5 dup * .
 1424: @end example
 1425: 
 1426: @quotation Assignment
 1427: Write 17^3 and 17^4 in Forth, without writing @code{17} more than once.
 1428: Write a piece of Forth code that expects two numbers on the stack
 1429: (@var{a} and @var{b}, with @var{b} on top) and computes
 1430: @code{(a-b)(a+1)}.
 1431: @end quotation
 1432: 
 1433: Reference: @ref{Stack Manipulation}.
 1434: 
 1435: 
 1436: @node Using files for Forth code Tutorial, Comments Tutorial, Stack Manipulation Tutorial, Tutorial
 1437: @section Using files for Forth code
 1438: @cindex loading Forth code, tutorial
 1439: @cindex files containing Forth code, tutorial
 1440: 
 1441: While working at the Forth command line is convenient for one-line
 1442: examples and short one-off code, you probably want to store your source
 1443: code in files for convenient editing and persistence.  You can use your
 1444: favourite editor (Gforth includes Emacs support, @pxref{Emacs and
 1445: Gforth}) to create @var{file.fs} and use
 1446: 
 1447: @example
 1448: s" @var{file.fs}" included
 1449: @end example
 1450: 
 1451: to load it into your Forth system.  The file name extension I use for
 1452: Forth files is @samp{.fs}.
 1453: 
 1454: You can easily start Gforth with some files loaded like this:
 1455: 
 1456: @example
 1457: gforth @var{file1.fs} @var{file2.fs}
 1458: @end example
 1459: 
 1460: If an error occurs during loading these files, Gforth terminates,
 1461: whereas an error during @code{INCLUDED} within Gforth usually gives you
 1462: a Gforth command line.  Starting the Forth system every time gives you a
 1463: clean start every time, without interference from the results of earlier
 1464: tries.
 1465: 
 1466: I often put all the tests in a file, then load the code and run the
 1467: tests with
 1468: 
 1469: @example
 1470: gforth @var{code.fs} @var{tests.fs} -e bye
 1471: @end example
 1472: 
 1473: (often by performing this command with @kbd{C-x C-e} in Emacs).  The
 1474: @code{-e bye} ensures that Gforth terminates afterwards so that I can
 1475: restart this command without ado.
 1476: 
 1477: The advantage of this approach is that the tests can be repeated easily
 1478: every time the program ist changed, making it easy to catch bugs
 1479: introduced by the change.
 1480: 
 1481: Reference: @ref{Forth source files}.
 1482: 
 1483: 
 1484: @node Comments Tutorial, Colon Definitions Tutorial, Using files for Forth code Tutorial, Tutorial
 1485: @section Comments
 1486: @cindex comments tutorial
 1487: 
 1488: @example
 1489: \ That's a comment; it ends at the end of the line
 1490: ( Another comment; it ends here: )  .s
 1491: @end example
 1492: 
 1493: @code{\} and @code{(} are ordinary Forth words and therefore have to be
 1494: separated with white space from the following text.
 1495: 
 1496: @example
 1497: \This gives an "Undefined word" error
 1498: @end example
 1499: 
 1500: The first @code{)} ends a comment started with @code{(}, so you cannot
 1501: nest @code{(}-comments; and you cannot comment out text containing a
 1502: @code{)} with @code{( ... )}@footnote{therefore it's a good idea to
 1503: avoid @code{)} in word names.}.
 1504: 
 1505: I use @code{\}-comments for descriptive text and for commenting out code
 1506: of one or more line; I use @code{(}-comments for describing the stack
 1507: effect, the stack contents, or for commenting out sub-line pieces of
 1508: code.
 1509: 
 1510: The Emacs mode @file{gforth.el} (@pxref{Emacs and Gforth}) supports
 1511: these uses by commenting out a region with @kbd{C-x \}, uncommenting a
 1512: region with @kbd{C-u C-x \}, and filling a @code{\}-commented region
 1513: with @kbd{M-q}.
 1514: 
 1515: Reference: @ref{Comments}.
 1516: 
 1517: 
 1518: @node Colon Definitions Tutorial, Decompilation Tutorial, Comments Tutorial, Tutorial
 1519: @section Colon Definitions
 1520: @cindex colon definitions, tutorial
 1521: @cindex definitions, tutorial
 1522: @cindex procedures, tutorial
 1523: @cindex functions, tutorial
 1524: 
 1525: are similar to procedures and functions in other programming languages.
 1526: 
 1527: @example
 1528: : squared ( n -- n^2 )
 1529:    dup * ;
 1530: 5 squared .
 1531: 7 squared .
 1532: @end example
 1533: 
 1534: @code{:} starts the colon definition; its name is @code{squared}.  The
 1535: following comment describes its stack effect.  The words @code{dup *}
 1536: are not executed, but compiled into the definition.  @code{;} ends the
 1537: colon definition.
 1538: 
 1539: The newly-defined word can be used like any other word, including using
 1540: it in other definitions:
 1541: 
 1542: @example
 1543: : cubed ( n -- n^3 )
 1544:    dup squared * ;
 1545: -5 cubed .
 1546: : fourth-power ( n -- n^4 )
 1547:    squared squared ;
 1548: 3 fourth-power .
 1549: @end example
 1550: 
 1551: @quotation Assignment
 1552: Write colon definitions for @code{nip}, @code{tuck}, @code{negate}, and
 1553: @code{/mod} in terms of other Forth words, and check if they work (hint:
 1554: test your tests on the originals first).  Don't let the
 1555: @samp{redefined}-Messages spook you, they are just warnings.
 1556: @end quotation
 1557: 
 1558: Reference: @ref{Colon Definitions}.
 1559: 
 1560: 
 1561: @node Decompilation Tutorial, Stack-Effect Comments Tutorial, Colon Definitions Tutorial, Tutorial
 1562: @section Decompilation
 1563: @cindex decompilation tutorial
 1564: @cindex see tutorial
 1565: 
 1566: You can decompile colon definitions with @code{see}:
 1567: 
 1568: @example
 1569: see squared
 1570: see cubed
 1571: @end example
 1572: 
 1573: In Gforth @code{see} shows you a reconstruction of the source code from
 1574: the executable code.  Informations that were present in the source, but
 1575: not in the executable code, are lost (e.g., comments).
 1576: 
 1577: You can also decompile the predefined words:
 1578: 
 1579: @example
 1580: see .
 1581: see +
 1582: @end example
 1583: 
 1584: 
 1585: @node Stack-Effect Comments Tutorial, Types Tutorial, Decompilation Tutorial, Tutorial
 1586: @section Stack-Effect Comments
 1587: @cindex stack-effect comments, tutorial
 1588: @cindex --, tutorial
 1589: By convention the comment after the name of a definition describes the
 1590: stack effect: The part in from of the @samp{--} describes the state of
 1591: the stack before the execution of the definition, i.e., the parameters
 1592: that are passed into the colon definition; the part behind the @samp{--}
 1593: is the state of the stack after the execution of the definition, i.e.,
 1594: the results of the definition.  The stack comment only shows the top
 1595: stack items that the definition accesses and/or changes.
 1596: 
 1597: You should put a correct stack effect on every definition, even if it is
 1598: just @code{( -- )}.  You should also add some descriptive comment to
 1599: more complicated words (I usually do this in the lines following
 1600: @code{:}).  If you don't do this, your code becomes unreadable (because
 1601: you have to work through every definition before you can understand
 1602: any).
 1603: 
 1604: @quotation Assignment
 1605: The stack effect of @code{swap} can be written like this: @code{x1 x2 --
 1606: x2 x1}.  Describe the stack effect of @code{-}, @code{drop}, @code{dup},
 1607: @code{over}, @code{rot}, @code{nip}, and @code{tuck}.  Hint: When you
 1608: are done, you can compare your stack effects to those in this manual
 1609: (@pxref{Word Index}).
 1610: @end quotation
 1611: 
 1612: Sometimes programmers put comments at various places in colon
 1613: definitions that describe the contents of the stack at that place (stack
 1614: comments); i.e., they are like the first part of a stack-effect
 1615: comment. E.g.,
 1616: 
 1617: @example
 1618: : cubed ( n -- n^3 )
 1619:    dup squared  ( n n^2 ) * ;
 1620: @end example
 1621: 
 1622: In this case the stack comment is pretty superfluous, because the word
 1623: is simple enough.  If you think it would be a good idea to add such a
 1624: comment to increase readability, you should also consider factoring the
 1625: word into several simpler words (@pxref{Factoring Tutorial,,
 1626: Factoring}), which typically eliminates the need for the stack comment;
 1627: however, if you decide not to refactor it, then having such a comment is
 1628: better than not having it.
 1629: 
 1630: The names of the stack items in stack-effect and stack comments in the
 1631: standard, in this manual, and in many programs specify the type through
 1632: a type prefix, similar to Fortran and Hungarian notation.  The most
 1633: frequent prefixes are:
 1634: 
 1635: @table @code
 1636: @item n
 1637: signed integer
 1638: @item u
 1639: unsigned integer
 1640: @item c
 1641: character
 1642: @item f
 1643: Boolean flags, i.e. @code{false} or @code{true}.
 1644: @item a-addr,a-
 1645: Cell-aligned address
 1646: @item c-addr,c-
 1647: Char-aligned address (note that a Char may have two bytes in Windows NT)
 1648: @item xt
 1649: Execution token, same size as Cell
 1650: @item w,x
 1651: Cell, can contain an integer or an address.  It usually takes 32, 64 or
 1652: 16 bits (depending on your platform and Forth system). A cell is more
 1653: commonly known as machine word, but the term @emph{word} already means
 1654: something different in Forth.
 1655: @item d
 1656: signed double-cell integer
 1657: @item ud
 1658: unsigned double-cell integer
 1659: @item r
 1660: Float (on the FP stack)
 1661: @end table
 1662: 
 1663: You can find a more complete list in @ref{Notation}.
 1664: 
 1665: @quotation Assignment
 1666: Write stack-effect comments for all definitions you have written up to
 1667: now.
 1668: @end quotation
 1669: 
 1670: 
 1671: @node Types Tutorial, Factoring Tutorial, Stack-Effect Comments Tutorial, Tutorial
 1672: @section Types
 1673: @cindex types tutorial
 1674: 
 1675: In Forth the names of the operations are not overloaded; so similar
 1676: operations on different types need different names; e.g., @code{+} adds
 1677: integers, and you have to use @code{f+} to add floating-point numbers.
 1678: The following prefixes are often used for related operations on
 1679: different types:
 1680: 
 1681: @table @code
 1682: @item (none)
 1683: signed integer
 1684: @item u
 1685: unsigned integer
 1686: @item c
 1687: character
 1688: @item d
 1689: signed double-cell integer
 1690: @item ud, du
 1691: unsigned double-cell integer
 1692: @item 2
 1693: two cells (not-necessarily double-cell numbers)
 1694: @item m, um
 1695: mixed single-cell and double-cell operations
 1696: @item f
 1697: floating-point (note that in stack comments @samp{f} represents flags,
 1698: and @samp{r} represents FP numbers).
 1699: @end table
 1700: 
 1701: If there are no differences between the signed and the unsigned variant
 1702: (e.g., for @code{+}), there is only the prefix-less variant.
 1703: 
 1704: Forth does not perform type checking, neither at compile time, nor at
 1705: run time.  If you use the wrong oeration, the data are interpreted
 1706: incorrectly:
 1707: 
 1708: @example
 1709: -1 u.
 1710: @end example
 1711: 
 1712: If you have only experience with type-checked languages until now, and
 1713: have heard how important type-checking is, don't panic!  In my
 1714: experience (and that of other Forthers), type errors in Forth code are
 1715: usually easy to find (once you get used to it), the increased vigilance
 1716: of the programmer tends to catch some harder errors in addition to most
 1717: type errors, and you never have to work around the type system, so in
 1718: most situations the lack of type-checking seems to be a win (projects to
 1719: add type checking to Forth have not caught on).
 1720: 
 1721: 
 1722: @node Factoring Tutorial, Designing the stack effect Tutorial, Types Tutorial, Tutorial
 1723: @section Factoring
 1724: @cindex factoring tutorial
 1725: 
 1726: If you try to write longer definitions, you will soon find it hard to
 1727: keep track of the stack contents.  Therefore, good Forth programmers
 1728: tend to write only short definitions (e.g., three lines).  The art of
 1729: finding meaningful short definitions is known as factoring (as in
 1730: factoring polynomials).
 1731: 
 1732: Well-factored programs offer additional advantages: smaller, more
 1733: general words, are easier to test and debug and can be reused more and
 1734: better than larger, specialized words.
 1735: 
 1736: So, if you run into difficulties with stack management, when writing
 1737: code, try to define meaningful factors for the word, and define the word
 1738: in terms of those.  Even if a factor contains only two words, it is
 1739: often helpful.
 1740: 
 1741: Good factoring is not easy, and it takes some practice to get the knack
 1742: for it; but even experienced Forth programmers often don't find the
 1743: right solution right away, but only when rewriting the program.  So, if
 1744: you don't come up with a good solution immediately, keep trying, don't
 1745: despair.
 1746: 
 1747: @c example !!
 1748: 
 1749: 
 1750: @node Designing the stack effect Tutorial, Local Variables Tutorial, Factoring Tutorial, Tutorial
 1751: @section Designing the stack effect
 1752: @cindex Stack effect design, tutorial
 1753: @cindex design of stack effects, tutorial
 1754: 
 1755: In other languages you can use an arbitrary order of parameters for a
 1756: function; and since there is only one result, you don't have to deal with
 1757: the order of results, either.
 1758: 
 1759: In Forth (and other stack-based languages, e.g., PostScript) the
 1760: parameter and result order of a definition is important and should be
 1761: designed well.  The general guideline is to design the stack effect such
 1762: that the word is simple to use in most cases, even if that complicates
 1763: the implementation of the word.  Some concrete rules are:
 1764: 
 1765: @itemize @bullet
 1766: 
 1767: @item
 1768: Words consume all of their parameters (e.g., @code{.}).
 1769: 
 1770: @item
 1771: If there is a convention on the order of parameters (e.g., from
 1772: mathematics or another programming language), stick with it (e.g.,
 1773: @code{-}).
 1774: 
 1775: @item
 1776: If one parameter usually requires only a short computation (e.g., it is
 1777: a constant), pass it on the top of the stack.  Conversely, parameters
 1778: that usually require a long sequence of code to compute should be passed
 1779: as the bottom (i.e., first) parameter.  This makes the code easier to
 1780: read, because reader does not need to keep track of the bottom item
 1781: through a long sequence of code (or, alternatively, through stack
 1782: manipulations). E.g., @code{!} (store, @pxref{Memory}) expects the
 1783: address on top of the stack because it is usually simpler to compute
 1784: than the stored value (often the address is just a variable).
 1785: 
 1786: @item
 1787: Similarly, results that are usually consumed quickly should be returned
 1788: on the top of stack, whereas a result that is often used in long
 1789: computations should be passed as bottom result.  E.g., the file words
 1790: like @code{open-file} return the error code on the top of stack, because
 1791: it is usually consumed quickly by @code{throw}; moreover, the error code
 1792: has to be checked before doing anything with the other results.
 1793: 
 1794: @end itemize
 1795: 
 1796: These rules are just general guidelines, don't lose sight of the overall
 1797: goal to make the words easy to use.  E.g., if the convention rule
 1798: conflicts with the computation-length rule, you might decide in favour
 1799: of the convention if the word will be used rarely, and in favour of the
 1800: computation-length rule if the word will be used frequently (because
 1801: with frequent use the cost of breaking the computation-length rule would
 1802: be quite high, and frequent use makes it easier to remember an
 1803: unconventional order).
 1804: 
 1805: @c example !! structure package
 1806: 
 1807: 
 1808: @node Local Variables Tutorial, Conditional execution Tutorial, Designing the stack effect Tutorial, Tutorial
 1809: @section Local Variables
 1810: @cindex local variables, tutorial
 1811: 
 1812: You can define local variables (@emph{locals}) in a colon definition:
 1813: 
 1814: @example
 1815: : swap @{ a b -- b a @}
 1816:   b a ;
 1817: 1 2 swap .s 2drop
 1818: @end example
 1819: 
 1820: (If your Forth system does not support this syntax, include
 1821: @file{compat/anslocals.fs} first).
 1822: 
 1823: In this example @code{@{ a b -- b a @}} is the locals definition; it
 1824: takes two cells from the stack, puts the top of stack in @code{b} and
 1825: the next stack element in @code{a}.  @code{--} starts a comment ending
 1826: with @code{@}}.  After the locals definition, using the name of the
 1827: local will push its value on the stack.  You can leave the comment
 1828: part (@code{-- b a}) away:
 1829: 
 1830: @example
 1831: : swap ( x1 x2 -- x2 x1 )
 1832:   @{ a b @} b a ;
 1833: @end example
 1834: 
 1835: In Gforth you can have several locals definitions, anywhere in a colon
 1836: definition; in contrast, in a standard program you can have only one
 1837: locals definition per colon definition, and that locals definition must
 1838: be outside any controll structure.
 1839: 
 1840: With locals you can write slightly longer definitions without running
 1841: into stack trouble.  However, I recommend trying to write colon
 1842: definitions without locals for exercise purposes to help you gain the
 1843: essential factoring skills.
 1844: 
 1845: @quotation Assignment
 1846: Rewrite your definitions until now with locals
 1847: @end quotation
 1848: 
 1849: Reference: @ref{Locals}.
 1850: 
 1851: 
 1852: @node Conditional execution Tutorial, Flags and Comparisons Tutorial, Local Variables Tutorial, Tutorial
 1853: @section Conditional execution
 1854: @cindex conditionals, tutorial
 1855: @cindex if, tutorial
 1856: 
 1857: In Forth you can use control structures only inside colon definitions.
 1858: An @code{if}-structure looks like this:
 1859: 
 1860: @example
 1861: : abs ( n1 -- +n2 )
 1862:     dup 0 < if
 1863:         negate
 1864:     endif ;
 1865: 5 abs .
 1866: -5 abs .
 1867: @end example
 1868: 
 1869: @code{if} takes a flag from the stack.  If the flag is non-zero (true),
 1870: the following code is performed, otherwise execution continues after the
 1871: @code{endif} (or @code{else}).  @code{<} compares the top two stack
 1872: elements and prioduces a flag:
 1873: 
 1874: @example
 1875: 1 2 < .
 1876: 2 1 < .
 1877: 1 1 < .
 1878: @end example
 1879: 
 1880: Actually the standard name for @code{endif} is @code{then}.  This
 1881: tutorial presents the examples using @code{endif}, because this is often
 1882: less confusing for people familiar with other programming languages
 1883: where @code{then} has a different meaning.  If your system does not have
 1884: @code{endif}, define it with
 1885: 
 1886: @example
 1887: : endif postpone then ; immediate
 1888: @end example
 1889: 
 1890: You can optionally use an @code{else}-part:
 1891: 
 1892: @example
 1893: : min ( n1 n2 -- n )
 1894:   2dup < if
 1895:     drop
 1896:   else
 1897:     nip
 1898:   endif ;
 1899: 2 3 min .
 1900: 3 2 min .
 1901: @end example
 1902: 
 1903: @quotation Assignment
 1904: Write @code{min} without @code{else}-part (hint: what's the definition
 1905: of @code{nip}?).
 1906: @end quotation
 1907: 
 1908: Reference: @ref{Selection}.
 1909: 
 1910: 
 1911: @node Flags and Comparisons Tutorial, General Loops Tutorial, Conditional execution Tutorial, Tutorial
 1912: @section Flags and Comparisons
 1913: @cindex flags tutorial
 1914: @cindex comparison tutorial
 1915: 
 1916: In a false-flag all bits are clear (0 when interpreted as integer).  In
 1917: a canonical true-flag all bits are set (-1 as a twos-complement signed
 1918: integer); in many contexts (e.g., @code{if}) any non-zero value is
 1919: treated as true flag.
 1920: 
 1921: @example
 1922: false .
 1923: true .
 1924: true hex u. decimal
 1925: @end example
 1926: 
 1927: Comparison words produce canonical flags:
 1928: 
 1929: @example
 1930: 1 1 = .
 1931: 1 0= .
 1932: 0 1 < .
 1933: 0 0 < .
 1934: -1 1 u< . \ type error, u< interprets -1 as large unsigned number
 1935: -1 1 < .
 1936: @end example
 1937: 
 1938: Gforth supports all combinations of the prefixes @code{0 u d d0 du f f0}
 1939: (or none) and the comparisons @code{= <> < > <= >=}.  Only a part of
 1940: these combinations are standard (for details see the standard,
 1941: @ref{Numeric comparison}, @ref{Floating Point} or @ref{Word Index}).
 1942: 
 1943: You can use @code{and or xor invert} can be used as operations on
 1944: canonical flags.  Actually they are bitwise operations:
 1945: 
 1946: @example
 1947: 1 2 and .
 1948: 1 2 or .
 1949: 1 3 xor .
 1950: 1 invert .
 1951: @end example
 1952: 
 1953: You can convert a zero/non-zero flag into a canonical flag with
 1954: @code{0<>} (and complement it on the way with @code{0=}).
 1955: 
 1956: @example
 1957: 1 0= .
 1958: 1 0<> .
 1959: @end example
 1960: 
 1961: You can use the all-bits-set feature of canonical flags and the bitwise
 1962: operation of the Boolean operations to avoid @code{if}s:
 1963: 
 1964: @example
 1965: : foo ( n1 -- n2 )
 1966:   0= if
 1967:     14
 1968:   else
 1969:     0
 1970:   endif ;
 1971: 0 foo .
 1972: 1 foo .
 1973: 
 1974: : foo ( n1 -- n2 )
 1975:   0= 14 and ;
 1976: 0 foo .
 1977: 1 foo .
 1978: @end example
 1979: 
 1980: @quotation Assignment
 1981: Write @code{min} without @code{if}.
 1982: @end quotation
 1983: 
 1984: For reference, see @ref{Boolean Flags}, @ref{Numeric comparison}, and
 1985: @ref{Bitwise operations}.
 1986: 
 1987: 
 1988: @node General Loops Tutorial, Counted loops Tutorial, Flags and Comparisons Tutorial, Tutorial
 1989: @section General Loops
 1990: @cindex loops, indefinite, tutorial
 1991: 
 1992: The endless loop is the most simple one:
 1993: 
 1994: @example
 1995: : endless ( -- )
 1996:   0 begin
 1997:     dup . 1+
 1998:   again ;
 1999: endless
 2000: @end example
 2001: 
 2002: Terminate this loop by pressing @kbd{Ctrl-C} (in Gforth).  @code{begin}
 2003: does nothing at run-time, @code{again} jumps back to @code{begin}.
 2004: 
 2005: A loop with one exit at any place looks like this:
 2006: 
 2007: @example
 2008: : log2 ( +n1 -- n2 )
 2009: \ logarithmus dualis of n1>0, rounded down to the next integer
 2010:   assert( dup 0> )
 2011:   2/ 0 begin
 2012:     over 0> while
 2013:       1+ swap 2/ swap
 2014:   repeat
 2015:   nip ;
 2016: 7 log2 .
 2017: 8 log2 .
 2018: @end example
 2019: 
 2020: At run-time @code{while} consumes a flag; if it is 0, execution
 2021: continues behind the @code{repeat}; if the flag is non-zero, execution
 2022: continues behind the @code{while}.  @code{Repeat} jumps back to
 2023: @code{begin}, just like @code{again}.
 2024: 
 2025: In Forth there are many combinations/abbreviations, like @code{1+}.
 2026: However, @code{2/} is not one of them; it shifts its argument right by
 2027: one bit (arithmetic shift right):
 2028: 
 2029: @example
 2030: -5 2 / .
 2031: -5 2/ .
 2032: @end example
 2033: 
 2034: @code{assert(} is no standard word, but you can get it on systems other
 2035: then Gforth by including @file{compat/assert.fs}.  You can see what it
 2036: does by trying
 2037: 
 2038: @example
 2039: 0 log2 .
 2040: @end example
 2041: 
 2042: Here's a loop with an exit at the end:
 2043: 
 2044: @example
 2045: : log2 ( +n1 -- n2 )
 2046: \ logarithmus dualis of n1>0, rounded down to the next integer
 2047:   assert( dup 0 > )
 2048:   -1 begin
 2049:     1+ swap 2/ swap
 2050:     over 0 <=
 2051:   until
 2052:   nip ;
 2053: @end example
 2054: 
 2055: @code{Until} consumes a flag; if it is non-zero, execution continues at
 2056: the @code{begin}, otherwise after the @code{until}.
 2057: 
 2058: @quotation Assignment
 2059: Write a definition for computing the greatest common divisor.
 2060: @end quotation
 2061: 
 2062: Reference: @ref{Simple Loops}.
 2063: 
 2064: 
 2065: @node Counted loops Tutorial, Recursion Tutorial, General Loops Tutorial, Tutorial
 2066: @section Counted loops
 2067: @cindex loops, counted, tutorial
 2068: 
 2069: @example
 2070: : ^ ( n1 u -- n )
 2071: \ n = the uth power of u1
 2072:   1 swap 0 u+do
 2073:     over *
 2074:   loop
 2075:   nip ;
 2076: 3 2 ^ .
 2077: 4 3 ^ .
 2078: @end example
 2079: 
 2080: @code{U+do} (from @file{compat/loops.fs}, if your Forth system doesn't
 2081: have it) takes two numbers of the stack @code{( u3 u4 -- )}, and then
 2082: performs the code between @code{u+do} and @code{loop} for @code{u3-u4}
 2083: times (or not at all, if @code{u3-u4<0}).
 2084: 
 2085: You can see the stack effect design rules at work in the stack effect of
 2086: the loop start words: Since the start value of the loop is more
 2087: frequently constant than the end value, the start value is passed on
 2088: the top-of-stack.
 2089: 
 2090: You can access the counter of a counted loop with @code{i}:
 2091: 
 2092: @example
 2093: : fac ( u -- u! )
 2094:   1 swap 1+ 1 u+do
 2095:     i *
 2096:   loop ;
 2097: 5 fac .
 2098: 7 fac .
 2099: @end example
 2100: 
 2101: There is also @code{+do}, which expects signed numbers (important for
 2102: deciding whether to enter the loop).
 2103: 
 2104: @quotation Assignment
 2105: Write a definition for computing the nth Fibonacci number.
 2106: @end quotation
 2107: 
 2108: You can also use increments other than 1:
 2109: 
 2110: @example
 2111: : up2 ( n1 n2 -- )
 2112:   +do
 2113:     i .
 2114:   2 +loop ;
 2115: 10 0 up2
 2116: 
 2117: : down2 ( n1 n2 -- )
 2118:   -do
 2119:     i .
 2120:   2 -loop ;
 2121: 0 10 down2
 2122: @end example
 2123: 
 2124: Reference: @ref{Counted Loops}.
 2125: 
 2126: 
 2127: @node Recursion Tutorial, Leaving definitions or loops Tutorial, Counted loops Tutorial, Tutorial
 2128: @section Recursion
 2129: @cindex recursion tutorial
 2130: 
 2131: Usually the name of a definition is not visible in the definition; but
 2132: earlier definitions are usually visible:
 2133: 
 2134: @example
 2135: 1 0 / . \ "Floating-point unidentified fault" in Gforth on most platforms
 2136: : / ( n1 n2 -- n )
 2137:   dup 0= if
 2138:     -10 throw \ report division by zero
 2139:   endif
 2140:   /           \ old version
 2141: ;
 2142: 1 0 /
 2143: @end example
 2144: 
 2145: For recursive definitions you can use @code{recursive} (non-standard) or
 2146: @code{recurse}:
 2147: 
 2148: @example
 2149: : fac1 ( n -- n! ) recursive
 2150:  dup 0> if
 2151:    dup 1- fac1 *
 2152:  else
 2153:    drop 1
 2154:  endif ;
 2155: 7 fac1 .
 2156: 
 2157: : fac2 ( n -- n! )
 2158:  dup 0> if
 2159:    dup 1- recurse *
 2160:  else
 2161:    drop 1
 2162:  endif ;
 2163: 8 fac2 .
 2164: @end example
 2165: 
 2166: @quotation Assignment
 2167: Write a recursive definition for computing the nth Fibonacci number.
 2168: @end quotation
 2169: 
 2170: Reference (including indirect recursion): @xref{Calls and returns}.
 2171: 
 2172: 
 2173: @node Leaving definitions or loops Tutorial, Return Stack Tutorial, Recursion Tutorial, Tutorial
 2174: @section Leaving definitions or loops
 2175: @cindex leaving definitions, tutorial
 2176: @cindex leaving loops, tutorial
 2177: 
 2178: @code{EXIT} exits the current definition right away.  For every counted
 2179: loop that is left in this way, an @code{UNLOOP} has to be performed
 2180: before the @code{EXIT}:
 2181: 
 2182: @c !! real examples
 2183: @example
 2184: : ...
 2185:  ... u+do
 2186:    ... if
 2187:      ... unloop exit
 2188:    endif
 2189:    ...
 2190:  loop
 2191:  ... ;
 2192: @end example
 2193: 
 2194: @code{LEAVE} leaves the innermost counted loop right away:
 2195: 
 2196: @example
 2197: : ...
 2198:  ... u+do
 2199:    ... if
 2200:      ... leave
 2201:    endif
 2202:    ...
 2203:  loop
 2204:  ... ;
 2205: @end example
 2206: 
 2207: @c !! example
 2208: 
 2209: Reference: @ref{Calls and returns}, @ref{Counted Loops}.
 2210: 
 2211: 
 2212: @node Return Stack Tutorial, Memory Tutorial, Leaving definitions or loops Tutorial, Tutorial
 2213: @section Return Stack
 2214: @cindex return stack tutorial
 2215: 
 2216: In addition to the data stack Forth also has a second stack, the return
 2217: stack; most Forth systems store the return addresses of procedure calls
 2218: there (thus its name).  Programmers can also use this stack:
 2219: 
 2220: @example
 2221: : foo ( n1 n2 -- )
 2222:  .s
 2223:  >r .s
 2224:  r@@ .
 2225:  >r .s
 2226:  r@@ .
 2227:  r> .
 2228:  r@@ .
 2229:  r> . ;
 2230: 1 2 foo
 2231: @end example
 2232: 
 2233: @code{>r} takes an element from the data stack and pushes it onto the
 2234: return stack; conversely, @code{r>} moves an elementm from the return to
 2235: the data stack; @code{r@@} pushes a copy of the top of the return stack
 2236: on the data stack.
 2237: 
 2238: Forth programmers usually use the return stack for storing data
 2239: temporarily, if using the data stack alone would be too complex, and
 2240: factoring and locals are not an option:
 2241: 
 2242: @example
 2243: : 2swap ( x1 x2 x3 x4 -- x3 x4 x1 x2 )
 2244:  rot >r rot r> ;
 2245: @end example
 2246: 
 2247: The return address of the definition and the loop control parameters of
 2248: counted loops usually reside on the return stack, so you have to take
 2249: all items, that you have pushed on the return stack in a colon
 2250: definition or counted loop, from the return stack before the definition
 2251: or loop ends.  You cannot access items that you pushed on the return
 2252: stack outside some definition or loop within the definition of loop.
 2253: 
 2254: If you miscount the return stack items, this usually ends in a crash:
 2255: 
 2256: @example
 2257: : crash ( n -- )
 2258:   >r ;
 2259: 5 crash
 2260: @end example
 2261: 
 2262: You cannot mix using locals and using the return stack (according to the
 2263: standard; Gforth has no problem).  However, they solve the same
 2264: problems, so this shouldn't be an issue.
 2265: 
 2266: @quotation Assignment
 2267: Can you rewrite any of the definitions you wrote until now in a better
 2268: way using the return stack?
 2269: @end quotation
 2270: 
 2271: Reference: @ref{Return stack}.
 2272: 
 2273: 
 2274: @node Memory Tutorial, Characters and Strings Tutorial, Return Stack Tutorial, Tutorial
 2275: @section Memory
 2276: @cindex memory access/allocation tutorial
 2277: 
 2278: You can create a global variable @code{v} with
 2279: 
 2280: @example
 2281: variable v ( -- addr )
 2282: @end example
 2283: 
 2284: @code{v} pushes the address of a cell in memory on the stack.  This cell
 2285: was reserved by @code{variable}.  You can use @code{!} (store) to store
 2286: values into this cell and @code{@@} (fetch) to load the value from the
 2287: stack into memory:
 2288: 
 2289: @example
 2290: v .
 2291: 5 v ! .s
 2292: v @@ .
 2293: @end example
 2294: 
 2295: You can see a raw dump of memory with @code{dump}:
 2296: 
 2297: @example
 2298: v 1 cells .s dump
 2299: @end example
 2300: 
 2301: @code{Cells ( n1 -- n2 )} gives you the number of bytes (or, more
 2302: generally, address units (aus)) that @code{n1 cells} occupy.  You can
 2303: also reserve more memory:
 2304: 
 2305: @example
 2306: create v2 20 cells allot
 2307: v2 20 cells dump
 2308: @end example
 2309: 
 2310: creates a word @code{v2} and reserves 20 uninitialized cells; the
 2311: address pushed by @code{v2} points to the start of these 20 cells.  You
 2312: can use address arithmetic to access these cells:
 2313: 
 2314: @example
 2315: 3 v2 5 cells + !
 2316: v2 20 cells dump
 2317: @end example
 2318: 
 2319: You can reserve and initialize memory with @code{,}:
 2320: 
 2321: @example
 2322: create v3
 2323:   5 , 4 , 3 , 2 , 1 ,
 2324: v3 @@ .
 2325: v3 cell+ @@ .
 2326: v3 2 cells + @@ .
 2327: v3 5 cells dump
 2328: @end example
 2329: 
 2330: @quotation Assignment
 2331: Write a definition @code{vsum ( addr u -- n )} that computes the sum of
 2332: @code{u} cells, with the first of these cells at @code{addr}, the next
 2333: one at @code{addr cell+} etc.
 2334: @end quotation
 2335: 
 2336: You can also reserve memory without creating a new word:
 2337: 
 2338: @example
 2339: here 10 cells allot .
 2340: here .
 2341: @end example
 2342: 
 2343: @code{Here} pushes the start address of the memory area.  You should
 2344: store it somewhere, or you will have a hard time finding the memory area
 2345: again.
 2346: 
 2347: @code{Allot} manages dictionary memory.  The dictionary memory contains
 2348: the system's data structures for words etc. on Gforth and most other
 2349: Forth systems.  It is managed like a stack: You can free the memory that
 2350: you have just @code{allot}ed with
 2351: 
 2352: @example
 2353: -10 cells allot
 2354: here .
 2355: @end example
 2356: 
 2357: Note that you cannot do this if you have created a new word in the
 2358: meantime (because then your @code{allot}ed memory is no longer on the
 2359: top of the dictionary ``stack'').
 2360: 
 2361: Alternatively, you can use @code{allocate} and @code{free} which allow
 2362: freeing memory in any order:
 2363: 
 2364: @example
 2365: 10 cells allocate throw .s
 2366: 20 cells allocate throw .s
 2367: swap
 2368: free throw
 2369: free throw
 2370: @end example
 2371: 
 2372: The @code{throw}s deal with errors (e.g., out of memory).
 2373: 
 2374: And there is also a
 2375: @uref{http://www.complang.tuwien.ac.at/forth/garbage-collection.zip,
 2376: garbage collector}, which eliminates the need to @code{free} memory
 2377: explicitly.
 2378: 
 2379: Reference: @ref{Memory}.
 2380: 
 2381: 
 2382: @node Characters and Strings Tutorial, Alignment Tutorial, Memory Tutorial, Tutorial
 2383: @section Characters and Strings
 2384: @cindex strings tutorial
 2385: @cindex characters tutorial
 2386: 
 2387: On the stack characters take up a cell, like numbers.  In memory they
 2388: have their own size (one 8-bit byte on most systems), and therefore
 2389: require their own words for memory access:
 2390: 
 2391: @example
 2392: create v4 
 2393:   104 c, 97 c, 108 c, 108 c, 111 c,
 2394: v4 4 chars + c@@ .
 2395: v4 5 chars dump
 2396: @end example
 2397: 
 2398: The preferred representation of strings on the stack is @code{addr
 2399: u-count}, where @code{addr} is the address of the first character and
 2400: @code{u-count} is the number of characters in the string.
 2401: 
 2402: @example
 2403: v4 5 type
 2404: @end example
 2405: 
 2406: You get a string constant with
 2407: 
 2408: @example
 2409: s" hello, world" .s
 2410: type
 2411: @end example
 2412: 
 2413: Make sure you have a space between @code{s"} and the string; @code{s"}
 2414: is a normal Forth word and must be delimited with white space (try what
 2415: happens when you remove the space).
 2416: 
 2417: However, this interpretive use of @code{s"} is quite restricted: the
 2418: string exists only until the next call of @code{s"} (some Forth systems
 2419: keep more than one of these strings, but usually they still have a
 2420: limited lifetime).
 2421: 
 2422: @example
 2423: s" hello," s" world" .s
 2424: type
 2425: type
 2426: @end example
 2427: 
 2428: You can also use @code{s"} in a definition, and the resulting
 2429: strings then live forever (well, for as long as the definition):
 2430: 
 2431: @example
 2432: : foo s" hello," s" world" ;
 2433: foo .s
 2434: type
 2435: type
 2436: @end example
 2437: 
 2438: @quotation Assignment
 2439: @code{Emit ( c -- )} types @code{c} as character (not a number).
 2440: Implement @code{type ( addr u -- )}.
 2441: @end quotation
 2442: 
 2443: Reference: @ref{Memory Blocks}.
 2444: 
 2445: 
 2446: @node Alignment Tutorial, Files Tutorial, Characters and Strings Tutorial, Tutorial
 2447: @section Alignment
 2448: @cindex alignment tutorial
 2449: @cindex memory alignment tutorial
 2450: 
 2451: On many processors cells have to be aligned in memory, if you want to
 2452: access them with @code{@@} and @code{!} (and even if the processor does
 2453: not require alignment, access to aligned cells is faster).
 2454: 
 2455: @code{Create} aligns @code{here} (i.e., the place where the next
 2456: allocation will occur, and that the @code{create}d word points to).
 2457: Likewise, the memory produced by @code{allocate} starts at an aligned
 2458: address.  Adding a number of @code{cells} to an aligned address produces
 2459: another aligned address.
 2460: 
 2461: However, address arithmetic involving @code{char+} and @code{chars} can
 2462: create an address that is not cell-aligned.  @code{Aligned ( addr --
 2463: a-addr )} produces the next aligned address:
 2464: 
 2465: @example
 2466: v3 char+ aligned .s @@ .
 2467: v3 char+ .s @@ .
 2468: @end example
 2469: 
 2470: Similarly, @code{align} advances @code{here} to the next aligned
 2471: address:
 2472: 
 2473: @example
 2474: create v5 97 c,
 2475: here .
 2476: align here .
 2477: 1000 ,
 2478: @end example
 2479: 
 2480: Note that you should use aligned addresses even if your processor does
 2481: not require them, if you want your program to be portable.
 2482: 
 2483: Reference: @ref{Address arithmetic}.
 2484: 
 2485: 
 2486: @node Files Tutorial, Interpretation and Compilation Semantics and Immediacy Tutorial, Alignment Tutorial, Tutorial
 2487: @section Files
 2488: @cindex files tutorial
 2489: 
 2490: This section gives a short introduction into how to use files inside
 2491: Forth. It's broken up into five easy steps:
 2492: 
 2493: @enumerate 1
 2494: @item Opened an ASCII text file for input
 2495: @item Opened a file for output
 2496: @item Read input file until string matched (or some other condition matched)
 2497: @item Wrote some lines from input ( modified or not) to output
 2498: @item Closed the files.
 2499: @end enumerate
 2500: 
 2501: Reference: @ref{General files}.
 2502: 
 2503: @subsection Open file for input
 2504: 
 2505: @example
 2506: s" foo.in"  r/o open-file throw Value fd-in
 2507: @end example
 2508: 
 2509: @subsection Create file for output
 2510: 
 2511: @example
 2512: s" foo.out" w/o create-file throw Value fd-out
 2513: @end example
 2514: 
 2515: The available file modes are r/o for read-only access, r/w for
 2516: read-write access, and w/o for write-only access. You could open both
 2517: files with r/w, too, if you like. All file words return error codes; for
 2518: most applications, it's best to pass there error codes with @code{throw}
 2519: to the outer error handler.
 2520: 
 2521: If you want words for opening and assigning, define them as follows:
 2522: 
 2523: @example
 2524: 0 Value fd-in
 2525: 0 Value fd-out
 2526: : open-input ( addr u -- )  r/o open-file throw to fd-in ;
 2527: : open-output ( addr u -- )  w/o create-file throw to fd-out ;
 2528: @end example
 2529: 
 2530: Usage example:
 2531: 
 2532: @example
 2533: s" foo.in" open-input
 2534: s" foo.out" open-output
 2535: @end example
 2536: 
 2537: @subsection Scan file for a particular line
 2538: 
 2539: @example
 2540: 256 Constant max-line
 2541: Create line-buffer  max-line 2 + allot
 2542: 
 2543: : scan-file ( addr u -- )
 2544:   begin
 2545:       line-buffer max-line fd-in read-line throw
 2546:   while
 2547:          >r 2dup line-buffer r> compare 0=
 2548:      until
 2549:   else
 2550:      drop
 2551:   then
 2552:   2drop ;
 2553: @end example
 2554: 
 2555: @code{read-line ( addr u1 fd -- u2 flag ior )} reads up to u1 bytes into
 2556: the buffer at addr, and returns the number of bytes read, a flag that is
 2557: false when the end of file is reached, and an error code.
 2558: 
 2559: @code{compare ( addr1 u1 addr2 u2 -- n )} compares two strings and
 2560: returns zero if both strings are equal. It returns a positive number if
 2561: the first string is lexically greater, a negative if the second string
 2562: is lexically greater.
 2563: 
 2564: We haven't seen this loop here; it has two exits. Since the @code{while}
 2565: exits with the number of bytes read on the stack, we have to clean up
 2566: that separately; that's after the @code{else}.
 2567: 
 2568: Usage example:
 2569: 
 2570: @example
 2571: s" The text I search is here" scan-file
 2572: @end example
 2573: 
 2574: @subsection Copy input to output
 2575: 
 2576: @example
 2577: : copy-file ( -- )
 2578:   begin
 2579:       line-buffer max-line fd-in read-line throw
 2580:   while
 2581:       line-buffer swap fd-out write-file throw
 2582:   repeat ;
 2583: @end example
 2584: 
 2585: @subsection Close files
 2586: 
 2587: @example
 2588: fd-in close-file throw
 2589: fd-out close-file throw
 2590: @end example
 2591: 
 2592: Likewise, you can put that into definitions, too:
 2593: 
 2594: @example
 2595: : close-input ( -- )  fd-in close-file throw ;
 2596: : close-output ( -- )  fd-out close-file throw ;
 2597: @end example
 2598: 
 2599: @quotation Assignment
 2600: How could you modify @code{copy-file} so that it copies until a second line is
 2601: matched? Can you write a program that extracts a section of a text file,
 2602: given the line that starts and the line that terminates that section?
 2603: @end quotation
 2604: 
 2605: @node Interpretation and Compilation Semantics and Immediacy Tutorial, Execution Tokens Tutorial, Files Tutorial, Tutorial
 2606: @section Interpretation and Compilation Semantics and Immediacy
 2607: @cindex semantics tutorial
 2608: @cindex interpretation semantics tutorial
 2609: @cindex compilation semantics tutorial
 2610: @cindex immediate, tutorial
 2611: 
 2612: When a word is compiled, it behaves differently from being interpreted.
 2613: E.g., consider @code{+}:
 2614: 
 2615: @example
 2616: 1 2 + .
 2617: : foo + ;
 2618: @end example
 2619: 
 2620: These two behaviours are known as compilation and interpretation
 2621: semantics.  For normal words (e.g., @code{+}), the compilation semantics
 2622: is to append the interpretation semantics to the currently defined word
 2623: (@code{foo} in the example above).  I.e., when @code{foo} is executed
 2624: later, the interpretation semantics of @code{+} (i.e., adding two
 2625: numbers) will be performed.
 2626: 
 2627: However, there are words with non-default compilation semantics, e.g.,
 2628: the control-flow words like @code{if}.  You can use @code{immediate} to
 2629: change the compilation semantics of the last defined word to be equal to
 2630: the interpretation semantics:
 2631: 
 2632: @example
 2633: : [FOO] ( -- )
 2634:  5 . ; immediate
 2635: 
 2636: [FOO]
 2637: : bar ( -- )
 2638:   [FOO] ;
 2639: bar
 2640: see bar
 2641: @end example
 2642: 
 2643: Two conventions to mark words with non-default compilation semnatics are
 2644: names with brackets (more frequently used) and to write them all in
 2645: upper case (less frequently used).
 2646: 
 2647: In Gforth (and many other systems) you can also remove the
 2648: interpretation semantics with @code{compile-only} (the compilation
 2649: semantics is derived from the original interpretation semantics):
 2650: 
 2651: @example
 2652: : flip ( -- )
 2653:  6 . ; compile-only \ but not immediate
 2654: flip
 2655: 
 2656: : flop ( -- )
 2657:  flip ;
 2658: flop
 2659: @end example
 2660: 
 2661: In this example the interpretation semantics of @code{flop} is equal to
 2662: the original interpretation semantics of @code{flip}.
 2663: 
 2664: The text interpreter has two states: in interpret state, it performs the
 2665: interpretation semantics of words it encounters; in compile state, it
 2666: performs the compilation semantics of these words.
 2667: 
 2668: Among other things, @code{:} switches into compile state, and @code{;}
 2669: switches back to interpret state.  They contain the factors @code{]}
 2670: (switch to compile state) and @code{[} (switch to interpret state), that
 2671: do nothing but switch the state.
 2672: 
 2673: @example
 2674: : xxx ( -- )
 2675:   [ 5 . ]
 2676: ;
 2677: 
 2678: xxx
 2679: see xxx
 2680: @end example
 2681: 
 2682: These brackets are also the source of the naming convention mentioned
 2683: above.
 2684: 
 2685: Reference: @ref{Interpretation and Compilation Semantics}.
 2686: 
 2687: 
 2688: @node Execution Tokens Tutorial, Exceptions Tutorial, Interpretation and Compilation Semantics and Immediacy Tutorial, Tutorial
 2689: @section Execution Tokens
 2690: @cindex execution tokens tutorial
 2691: @cindex XT tutorial
 2692: 
 2693: @code{' word} gives you the execution token (XT) of a word.  The XT is a
 2694: cell representing the interpretation semantics of a word.  You can
 2695: execute this semantics with @code{execute}:
 2696: 
 2697: @example
 2698: ' + .s
 2699: 1 2 rot execute .
 2700: @end example
 2701: 
 2702: The XT is similar to a function pointer in C.  However, parameter
 2703: passing through the stack makes it a little more flexible:
 2704: 
 2705: @example
 2706: : map-array ( ... addr u xt -- ... )
 2707: \ executes xt ( ... x -- ... ) for every element of the array starting
 2708: \ at addr and containing u elements
 2709:   @{ xt @}
 2710:   cells over + swap ?do
 2711:     i @@ xt execute
 2712:   1 cells +loop ;
 2713: 
 2714: create a 3 , 4 , 2 , -1 , 4 ,
 2715: a 5 ' . map-array .s
 2716: 0 a 5 ' + map-array .
 2717: s" max-n" environment? drop .s
 2718: a 5 ' min map-array .
 2719: @end example
 2720: 
 2721: You can use map-array with the XTs of words that consume one element
 2722: more than they produce.  In theory you can also use it with other XTs,
 2723: but the stack effect then depends on the size of the array, which is
 2724: hard to understand.
 2725: 
 2726: Since XTs are cell-sized, you can store them in memory and manipulate
 2727: them on the stack like other cells.  You can also compile the XT into a
 2728: word with @code{compile,}:
 2729: 
 2730: @example
 2731: : foo1 ( n1 n2 -- n )
 2732:    [ ' + compile, ] ;
 2733: see foo
 2734: @end example
 2735: 
 2736: This is non-standard, because @code{compile,} has no compilation
 2737: semantics in the standard, but it works in good Forth systems.  For the
 2738: broken ones, use
 2739: 
 2740: @example
 2741: : [compile,] compile, ; immediate
 2742: 
 2743: : foo1 ( n1 n2 -- n )
 2744:    [ ' + ] [compile,] ;
 2745: see foo
 2746: @end example
 2747: 
 2748: @code{'} is a word with default compilation semantics; it parses the
 2749: next word when its interpretation semantics are executed, not during
 2750: compilation:
 2751: 
 2752: @example
 2753: : foo ( -- xt )
 2754:   ' ;
 2755: see foo
 2756: : bar ( ... "word" -- ... )
 2757:   ' execute ;
 2758: see bar
 2759: 1 2 bar + .
 2760: @end example
 2761: 
 2762: You often want to parse a word during compilation and compile its XT so
 2763: it will be pushed on the stack at run-time.  @code{[']} does this:
 2764: 
 2765: @example
 2766: : xt-+ ( -- xt )
 2767:   ['] + ;
 2768: see xt-+
 2769: 1 2 xt-+ execute .
 2770: @end example
 2771: 
 2772: Many programmers tend to see @code{'} and the word it parses as one
 2773: unit, and expect it to behave like @code{[']} when compiled, and are
 2774: confused by the actual behaviour.  If you are, just remember that the
 2775: Forth system just takes @code{'} as one unit and has no idea that it is
 2776: a parsing word (attempts to convenience programmers in this issue have
 2777: usually resulted in even worse pitfalls, see
 2778: @uref{http://www.complang.tuwien.ac.at/papers/ertl98.ps.gz,
 2779: @code{State}-smartness---Why it is evil and How to Exorcise it}).
 2780: 
 2781: Note that the state of the interpreter does not come into play when
 2782: creating and executing XTs.  I.e., even when you execute @code{'} in
 2783: compile state, it still gives you the interpretation semantics.  And
 2784: whatever that state is, @code{execute} performs the semantics
 2785: represented by the XT (i.e., for XTs produced with @code{'} the
 2786: interpretation semantics).
 2787: 
 2788: Reference: @ref{Tokens for Words}.
 2789: 
 2790: 
 2791: @node Exceptions Tutorial, Defining Words Tutorial, Execution Tokens Tutorial, Tutorial
 2792: @section Exceptions
 2793: @cindex exceptions tutorial
 2794: 
 2795: @code{throw ( n -- )} causes an exception unless n is zero.
 2796: 
 2797: @example
 2798: 100 throw .s
 2799: 0 throw .s
 2800: @end example
 2801: 
 2802: @code{catch ( ... xt -- ... n )} behaves similar to @code{execute}, but
 2803: it catches exceptions and pushes the number of the exception on the
 2804: stack (or 0, if the xt executed without exception).  If there was an
 2805: exception, the stacks have the same depth as when entering @code{catch}:
 2806: 
 2807: @example
 2808: .s
 2809: 3 0 ' / catch .s
 2810: 3 2 ' / catch .s
 2811: @end example
 2812: 
 2813: @quotation Assignment
 2814: Try the same with @code{execute} instead of @code{catch}.
 2815: @end quotation
 2816: 
 2817: @code{Throw} always jumps to the dynamically next enclosing
 2818: @code{catch}, even if it has to leave several call levels to achieve
 2819: this:
 2820: 
 2821: @example
 2822: : foo 100 throw ;
 2823: : foo1 foo ." after foo" ;
 2824: : bar ['] foo1 catch ;
 2825: bar .
 2826: @end example
 2827: 
 2828: It is often important to restore a value upon leaving a definition, even
 2829: if the definition is left through an exception.  You can ensure this
 2830: like this:
 2831: 
 2832: @example
 2833: : ...
 2834:    save-x
 2835:    ['] word-changing-x catch ( ... n )
 2836:    restore-x
 2837:    ( ... n ) throw ;
 2838: @end example
 2839: 
 2840: Gforth provides an alternative syntax in addition to @code{catch}:
 2841: @code{try ... recover ... endtry}.  If the code between @code{try} and
 2842: @code{recover} has an exception, the stack depths are restored, the
 2843: exception number is pushed on the stack, and the code between
 2844: @code{recover} and @code{endtry} is performed.  E.g., the definition for
 2845: @code{catch} is
 2846: 
 2847: @example
 2848: : catch ( x1 .. xn xt -- y1 .. ym 0 / z1 .. zn error ) \ exception
 2849:   try
 2850:     execute 0
 2851:   recover
 2852:     nip
 2853:   endtry ;
 2854: @end example
 2855: 
 2856: The equivalent to the restoration code above is
 2857: 
 2858: @example
 2859: : ...
 2860:   save-x
 2861:   try
 2862:     word-changing-x 0
 2863:   recover endtry
 2864:   restore-x
 2865:   throw ;
 2866: @end example
 2867: 
 2868: This works if @code{word-changing-x} does not change the stack depth,
 2869: otherwise you should add some code between @code{recover} and
 2870: @code{endtry} to balance the stack.
 2871: 
 2872: Reference: @ref{Exception Handling}.
 2873: 
 2874: 
 2875: @node Defining Words Tutorial, Arrays and Records Tutorial, Exceptions Tutorial, Tutorial
 2876: @section Defining Words
 2877: @cindex defining words tutorial
 2878: @cindex does> tutorial
 2879: @cindex create...does> tutorial
 2880: 
 2881: @c before semantics?
 2882: 
 2883: @code{:}, @code{create}, and @code{variable} are definition words: They
 2884: define other words.  @code{Constant} is another definition word:
 2885: 
 2886: @example
 2887: 5 constant foo
 2888: foo .
 2889: @end example
 2890: 
 2891: You can also use the prefixes @code{2} (double-cell) and @code{f}
 2892: (floating point) with @code{variable} and @code{constant}.
 2893: 
 2894: You can also define your own defining words.  E.g.:
 2895: 
 2896: @example
 2897: : variable ( "name" -- )
 2898:   create 0 , ;
 2899: @end example
 2900: 
 2901: You can also define defining words that create words that do something
 2902: other than just producing their address:
 2903: 
 2904: @example
 2905: : constant ( n "name" -- )
 2906:   create ,
 2907: does> ( -- n )
 2908:   ( addr ) @@ ;
 2909: 
 2910: 5 constant foo
 2911: foo .
 2912: @end example
 2913: 
 2914: The definition of @code{constant} above ends at the @code{does>}; i.e.,
 2915: @code{does>} replaces @code{;}, but it also does something else: It
 2916: changes the last defined word such that it pushes the address of the
 2917: body of the word and then performs the code after the @code{does>}
 2918: whenever it is called.
 2919: 
 2920: In the example above, @code{constant} uses @code{,} to store 5 into the
 2921: body of @code{foo}.  When @code{foo} executes, it pushes the address of
 2922: the body onto the stack, then (in the code after the @code{does>})
 2923: fetches the 5 from there.
 2924: 
 2925: The stack comment near the @code{does>} reflects the stack effect of the
 2926: defined word, not the stack effect of the code after the @code{does>}
 2927: (the difference is that the code expects the address of the body that
 2928: the stack comment does not show).
 2929: 
 2930: You can use these definition words to do factoring in cases that involve
 2931: (other) definition words.  E.g., a field offset is always added to an
 2932: address.  Instead of defining
 2933: 
 2934: @example
 2935: 2 cells constant offset-field1
 2936: @end example
 2937: 
 2938: and using this like
 2939: 
 2940: @example
 2941: ( addr ) offset-field1 +
 2942: @end example
 2943: 
 2944: you can define a definition word
 2945: 
 2946: @example
 2947: : simple-field ( n "name" -- )
 2948:   create ,
 2949: does> ( n1 -- n1+n )
 2950:   ( addr ) @@ + ;
 2951: @end example
 2952: 
 2953: Definition and use of field offsets now look like this:
 2954: 
 2955: @example
 2956: 2 cells simple-field field1
 2957: create mystruct 4 cells allot
 2958: mystruct .s field1 .s drop
 2959: @end example
 2960: 
 2961: If you want to do something with the word without performing the code
 2962: after the @code{does>}, you can access the body of a @code{create}d word
 2963: with @code{>body ( xt -- addr )}:
 2964: 
 2965: @example
 2966: : value ( n "name" -- )
 2967:   create ,
 2968: does> ( -- n1 )
 2969:   @@ ;
 2970: : to ( n "name" -- )
 2971:   ' >body ! ;
 2972: 
 2973: 5 value foo
 2974: foo .
 2975: 7 to foo
 2976: foo .
 2977: @end example
 2978: 
 2979: @quotation Assignment
 2980: Define @code{defer ( "name" -- )}, which creates a word that stores an
 2981: XT (at the start the XT of @code{abort}), and upon execution
 2982: @code{execute}s the XT.  Define @code{is ( xt "name" -- )} that stores
 2983: @code{xt} into @code{name}, a word defined with @code{defer}.  Indirect
 2984: recursion is one application of @code{defer}.
 2985: @end quotation
 2986: 
 2987: Reference: @ref{User-defined Defining Words}.
 2988: 
 2989: 
 2990: @node Arrays and Records Tutorial, POSTPONE Tutorial, Defining Words Tutorial, Tutorial
 2991: @section Arrays and Records
 2992: @cindex arrays tutorial
 2993: @cindex records tutorial
 2994: @cindex structs tutorial
 2995: 
 2996: Forth has no standard words for defining data structures such as arrays
 2997: and records (structs in C terminology), but you can build them yourself
 2998: based on address arithmetic.  You can also define words for defining
 2999: arrays and records (@pxref{Defining Words Tutorial,, Defining Words}).
 3000: 
 3001: One of the first projects a Forth newcomer sets out upon when learning
 3002: about defining words is an array defining word (possibly for
 3003: n-dimensional arrays).  Go ahead and do it, I did it, too; you will
 3004: learn something from it.  However, don't be disappointed when you later
 3005: learn that you have little use for these words (inappropriate use would
 3006: be even worse).  I have not yet found a set of useful array words yet;
 3007: the needs are just too diverse, and named, global arrays (the result of
 3008: naive use of defining words) are often not flexible enough (e.g.,
 3009: consider how to pass them as parameters).  Another such project is a set
 3010: of words to help dealing with strings.
 3011: 
 3012: On the other hand, there is a useful set of record words, and it has
 3013: been defined in @file{compat/struct.fs}; these words are predefined in
 3014: Gforth.  They are explained in depth elsewhere in this manual (see
 3015: @pxref{Structures}).  The @code{simple-field} example above is
 3016: simplified variant of fields in this package.
 3017: 
 3018: 
 3019: @node POSTPONE Tutorial, Literal Tutorial, Arrays and Records Tutorial, Tutorial
 3020: @section @code{POSTPONE}
 3021: @cindex postpone tutorial
 3022: 
 3023: You can compile the compilation semantics (instead of compiling the
 3024: interpretation semantics) of a word with @code{POSTPONE}:
 3025: 
 3026: @example
 3027: : MY-+ ( Compilation: -- ; Run-time of compiled code: n1 n2 -- n )
 3028:  POSTPONE + ; immediate
 3029: : foo ( n1 n2 -- n )
 3030:  MY-+ ;
 3031: 1 2 foo .
 3032: see foo
 3033: @end example
 3034: 
 3035: During the definition of @code{foo} the text interpreter performs the
 3036: compilation semantics of @code{MY-+}, which performs the compilation
 3037: semantics of @code{+}, i.e., it compiles @code{+} into @code{foo}.
 3038: 
 3039: This example also displays separate stack comments for the compilation
 3040: semantics and for the stack effect of the compiled code.  For words with
 3041: default compilation semantics these stack effects are usually not
 3042: displayed; the stack effect of the compilation semantics is always
 3043: @code{( -- )} for these words, the stack effect for the compiled code is
 3044: the stack effect of the interpretation semantics.
 3045: 
 3046: Note that the state of the interpreter does not come into play when
 3047: performing the compilation semantics in this way.  You can also perform
 3048: it interpretively, e.g.:
 3049: 
 3050: @example
 3051: : foo2 ( n1 n2 -- n )
 3052:  [ MY-+ ] ;
 3053: 1 2 foo .
 3054: see foo
 3055: @end example
 3056: 
 3057: However, there are some broken Forth systems where this does not always
 3058: work, and therefore this practice was been declared non-standard in
 3059: 1999.
 3060: @c !! repair.fs
 3061: 
 3062: Here is another example for using @code{POSTPONE}:
 3063: 
 3064: @example
 3065: : MY-- ( Compilation: -- ; Run-time of compiled code: n1 n2 -- n )
 3066:  POSTPONE negate POSTPONE + ; immediate compile-only
 3067: : bar ( n1 n2 -- n )
 3068:   MY-- ;
 3069: 2 1 bar .
 3070: see bar
 3071: @end example
 3072: 
 3073: You can define @code{ENDIF} in this way:
 3074: 
 3075: @example
 3076: : ENDIF ( Compilation: orig -- )
 3077:   POSTPONE then ; immediate
 3078: @end example
 3079: 
 3080: @quotation Assignment
 3081: Write @code{MY-2DUP} that has compilation semantics equivalent to
 3082: @code{2dup}, but compiles @code{over over}.
 3083: @end quotation
 3084: 
 3085: @c !! @xref{Macros} for reference
 3086: 
 3087: 
 3088: @node Literal Tutorial, Advanced macros Tutorial, POSTPONE Tutorial, Tutorial
 3089: @section @code{Literal}
 3090: @cindex literal tutorial
 3091: 
 3092: You cannot @code{POSTPONE} numbers:
 3093: 
 3094: @example
 3095: : [FOO] POSTPONE 500 ; immediate
 3096: @end example
 3097: 
 3098: Instead, you can use @code{LITERAL (compilation: n --; run-time: -- n )}:
 3099: 
 3100: @example
 3101: : [FOO] ( compilation: --; run-time: -- n )
 3102:   500 POSTPONE literal ; immediate
 3103: 
 3104: : flip [FOO] ;
 3105: flip .
 3106: see flip
 3107: @end example
 3108: 
 3109: @code{LITERAL} consumes a number at compile-time (when it's compilation
 3110: semantics are executed) and pushes it at run-time (when the code it
 3111: compiled is executed).  A frequent use of @code{LITERAL} is to compile a
 3112: number computed at compile time into the current word:
 3113: 
 3114: @example
 3115: : bar ( -- n )
 3116:   [ 2 2 + ] literal ;
 3117: see bar
 3118: @end example
 3119: 
 3120: @quotation Assignment
 3121: Write @code{]L} which allows writing the example above as @code{: bar (
 3122: -- n ) [ 2 2 + ]L ;}
 3123: @end quotation
 3124: 
 3125: @c !! @xref{Macros} for reference
 3126: 
 3127: 
 3128: @node Advanced macros Tutorial, Compilation Tokens Tutorial, Literal Tutorial, Tutorial
 3129: @section Advanced macros
 3130: @cindex macros, advanced tutorial
 3131: @cindex run-time code generation, tutorial
 3132: 
 3133: Reconsider @code{map-array} from @ref{Execution Tokens Tutorial,,
 3134: Execution Tokens}.  It frequently performs @code{execute}, a relatively
 3135: expensive operation in some Forth implementations.  You can use
 3136: @code{compile,} and @code{POSTPONE} to eliminate these @code{execute}s
 3137: and produce a word that contains the word to be performed directly:
 3138: 
 3139: @c use ]] ... [[
 3140: @example
 3141: : compile-map-array ( compilation: xt -- ; run-time: ... addr u -- ... )
 3142: \ at run-time, execute xt ( ... x -- ... ) for each element of the
 3143: \ array beginning at addr and containing u elements
 3144:   @{ xt @}
 3145:   POSTPONE cells POSTPONE over POSTPONE + POSTPONE swap POSTPONE ?do
 3146:     POSTPONE i POSTPONE @@ xt compile,
 3147:   1 cells POSTPONE literal POSTPONE +loop ;
 3148: 
 3149: : sum-array ( addr u -- n )
 3150:  0 rot rot [ ' + compile-map-array ] ;
 3151: see sum-array
 3152: a 5 sum-array .
 3153: @end example
 3154: 
 3155: You can use the full power of Forth for generating the code; here's an
 3156: example where the code is generated in a loop:
 3157: 
 3158: @example
 3159: : compile-vmul-step ( compilation: n --; run-time: n1 addr1 -- n2 addr2 )
 3160: \ n2=n1+(addr1)*n, addr2=addr1+cell
 3161:   POSTPONE tuck POSTPONE @@
 3162:   POSTPONE literal POSTPONE * POSTPONE +
 3163:   POSTPONE swap POSTPONE cell+ ;
 3164: 
 3165: : compile-vmul ( compilation: addr1 u -- ; run-time: addr2 -- n )
 3166: \ n=v1*v2 (inner product), where the v_i are represented as addr_i u
 3167:   0 postpone literal postpone swap
 3168:   [ ' compile-vmul-step compile-map-array ]
 3169:   postpone drop ;
 3170: see compile-vmul
 3171: 
 3172: : a-vmul ( addr -- n )
 3173: \ n=a*v, where v is a vector that's as long as a and starts at addr
 3174:  [ a 5 compile-vmul ] ;
 3175: see a-vmul
 3176: a a-vmul .
 3177: @end example
 3178: 
 3179: This example uses @code{compile-map-array} to show off, but you could
 3180: also use @code{map-array} instead (try it now!).
 3181: 
 3182: You can use this technique for efficient multiplication of large
 3183: matrices.  In matrix multiplication, you multiply every line of one
 3184: matrix with every column of the other matrix.  You can generate the code
 3185: for one line once, and use it for every column.  The only downside of
 3186: this technique is that it is cumbersome to recover the memory consumed
 3187: by the generated code when you are done (and in more complicated cases
 3188: it is not possible portably).
 3189: 
 3190: @c !! @xref{Macros} for reference
 3191: 
 3192: 
 3193: @node Compilation Tokens Tutorial, Wordlists and Search Order Tutorial, Advanced macros Tutorial, Tutorial
 3194: @section Compilation Tokens
 3195: @cindex compilation tokens, tutorial
 3196: @cindex CT, tutorial
 3197: 
 3198: This section is Gforth-specific.  You can skip it.
 3199: 
 3200: @code{' word compile,} compiles the interpretation semantics.  For words
 3201: with default compilation semantics this is the same as performing the
 3202: compilation semantics.  To represent the compilation semantics of other
 3203: words (e.g., words like @code{if} that have no interpretation
 3204: semantics), Gforth has the concept of a compilation token (CT,
 3205: consisting of two cells), and words @code{comp'} and @code{[comp']}.
 3206: You can perform the compilation semantics represented by a CT with
 3207: @code{execute}:
 3208: 
 3209: @example
 3210: : foo2 ( n1 n2 -- n )
 3211:    [ comp' + execute ] ;
 3212: see foo
 3213: @end example
 3214: 
 3215: You can compile the compilation semantics represented by a CT with
 3216: @code{postpone,}:
 3217: 
 3218: @example
 3219: : foo3 ( -- )
 3220:   [ comp' + postpone, ] ;
 3221: see foo3
 3222: @end example
 3223: 
 3224: @code{[ comp' word postpone, ]} is equivalent to @code{POSTPONE word}.
 3225: @code{comp'} is particularly useful for words that have no
 3226: interpretation semantics:
 3227: 
 3228: @example
 3229: ' if
 3230: comp' if .s 2drop
 3231: @end example
 3232: 
 3233: Reference: @ref{Tokens for Words}.
 3234: 
 3235: 
 3236: @node Wordlists and Search Order Tutorial,  , Compilation Tokens Tutorial, Tutorial
 3237: @section Wordlists and Search Order
 3238: @cindex wordlists tutorial
 3239: @cindex search order, tutorial
 3240: 
 3241: The dictionary is not just a memory area that allows you to allocate
 3242: memory with @code{allot}, it also contains the Forth words, arranged in
 3243: several wordlists.  When searching for a word in a wordlist,
 3244: conceptually you start searching at the youngest and proceed towards
 3245: older words (in reality most systems nowadays use hash-tables); i.e., if
 3246: you define a word with the same name as an older word, the new word
 3247: shadows the older word.
 3248: 
 3249: Which wordlists are searched in which order is determined by the search
 3250: order.  You can display the search order with @code{order}.  It displays
 3251: first the search order, starting with the wordlist searched first, then
 3252: it displays the wordlist that will contain newly defined words.
 3253: 
 3254: You can create a new, empty wordlist with @code{wordlist ( -- wid )}:
 3255: 
 3256: @example
 3257: wordlist constant mywords
 3258: @end example
 3259: 
 3260: @code{Set-current ( wid -- )} sets the wordlist that will contain newly
 3261: defined words (the @emph{current} wordlist):
 3262: 
 3263: @example
 3264: mywords set-current
 3265: order
 3266: @end example
 3267: 
 3268: Gforth does not display a name for the wordlist in @code{mywords}
 3269: because this wordlist was created anonymously with @code{wordlist}.
 3270: 
 3271: You can get the current wordlist with @code{get-current ( -- wid)}.  If
 3272: you want to put something into a specific wordlist without overall
 3273: effect on the current wordlist, this typically looks like this:
 3274: 
 3275: @example
 3276: get-current mywords set-current ( wid )
 3277: create someword
 3278: ( wid ) set-current
 3279: @end example
 3280: 
 3281: You can write the search order with @code{set-order ( wid1 .. widn n --
 3282: )} and read it with @code{get-order ( -- wid1 .. widn n )}.  The first
 3283: searched wordlist is topmost.
 3284: 
 3285: @example
 3286: get-order mywords swap 1+ set-order
 3287: order
 3288: @end example
 3289: 
 3290: Yes, the order of wordlists in the output of @code{order} is reversed
 3291: from stack comments and the output of @code{.s} and thus unintuitive.
 3292: 
 3293: @quotation Assignment
 3294: Define @code{>order ( wid -- )} with adds @code{wid} as first searched
 3295: wordlist to the search order.  Define @code{previous ( -- )}, which
 3296: removes the first searched wordlist from the search order.  Experiment
 3297: with boundary conditions (you will see some crashes or situations that
 3298: are hard or impossible to leave).
 3299: @end quotation
 3300: 
 3301: The search order is a powerful foundation for providing features similar
 3302: to Modula-2 modules and C++ namespaces.  However, trying to modularize
 3303: programs in this way has disadvantages for debugging and reuse/factoring
 3304: that overcome the advantages in my experience (I don't do huge projects,
 3305: though).  These disadvantages are not so clear in other
 3306: languages/programming environments, because these languages are not so
 3307: strong in debugging and reuse.
 3308: 
 3309: @c !! example
 3310: 
 3311: Reference: @ref{Word Lists}.
 3312: 
 3313: @c ******************************************************************
 3314: @node Introduction, Words, Tutorial, Top
 3315: @comment node-name,     next,           previous, up
 3316: @chapter An Introduction to ANS Forth
 3317: @cindex Forth - an introduction
 3318: 
 3319: The difference of this chapter from the Tutorial (@pxref{Tutorial}) is
 3320: that it is slower-paced in its examples, but uses them to dive deep into
 3321: explaining Forth internals (not covered by the Tutorial).  Apart from
 3322: that, this chapter covers far less material.  It is suitable for reading
 3323: without using a computer.
 3324: 
 3325: The primary purpose of this manual is to document Gforth. However, since
 3326: Forth is not a widely-known language and there is a lack of up-to-date
 3327: teaching material, it seems worthwhile to provide some introductory
 3328: material.  For other sources of Forth-related
 3329: information, see @ref{Forth-related information}.
 3330: 
 3331: The examples in this section should work on any ANS Forth; the
 3332: output shown was produced using Gforth. Each example attempts to
 3333: reproduce the exact output that Gforth produces. If you try out the
 3334: examples (and you should), what you should type is shown @kbd{like this}
 3335: and Gforth's response is shown @code{like this}. The single exception is
 3336: that, where the example shows @key{RET} it means that you should
 3337: press the ``carriage return'' key. Unfortunately, some output formats for
 3338: this manual cannot show the difference between @kbd{this} and
 3339: @code{this} which will make trying out the examples harder (but not
 3340: impossible).
 3341: 
 3342: Forth is an unusual language. It provides an interactive development
 3343: environment which includes both an interpreter and compiler. Forth
 3344: programming style encourages you to break a problem down into many
 3345: @cindex factoring
 3346: small fragments (@dfn{factoring}), and then to develop and test each
 3347: fragment interactively. Forth advocates assert that breaking the
 3348: edit-compile-test cycle used by conventional programming languages can
 3349: lead to great productivity improvements.
 3350: 
 3351: @menu
 3352: * Introducing the Text Interpreter::  
 3353: * Stacks and Postfix notation::  
 3354: * Your first definition::       
 3355: * How does that work?::         
 3356: * Forth is written in Forth::   
 3357: * Review - elements of a Forth system::  
 3358: * Where to go next::            
 3359: * Exercises::                   
 3360: @end menu
 3361: 
 3362: @comment ----------------------------------------------
 3363: @node Introducing the Text Interpreter, Stacks and Postfix notation, Introduction, Introduction
 3364: @section Introducing the Text Interpreter
 3365: @cindex text interpreter
 3366: @cindex outer interpreter
 3367: 
 3368: @c IMO this is too detailed and the pace is too slow for
 3369: @c an introduction.  If you know German, take a look at
 3370: @c http://www.complang.tuwien.ac.at/anton/lvas/skriptum-stack.html 
 3371: @c to see how I do it - anton 
 3372: 
 3373: @c nac-> Where I have accepted your comments 100% and modified the text
 3374: @c accordingly, I have deleted your comments. Elsewhere I have added a
 3375: @c response like this to attempt to rationalise what I have done. Of
 3376: @c course, this is a very clumsy mechanism for something that would be
 3377: @c done far more efficiently over a beer. Please delete any dialogue
 3378: @c you consider closed.
 3379: 
 3380: When you invoke the Forth image, you will see a startup banner printed
 3381: and nothing else (if you have Gforth installed on your system, try
 3382: invoking it now, by typing @kbd{gforth@key{RET}}). Forth is now running
 3383: its command line interpreter, which is called the @dfn{Text Interpreter}
 3384: (also known as the @dfn{Outer Interpreter}).  (You will learn a lot
 3385: about the text interpreter as you read through this chapter, for more
 3386: detail @pxref{The Text Interpreter}).
 3387: 
 3388: Although it's not obvious, Forth is actually waiting for your
 3389: input. Type a number and press the @key{RET} key:
 3390: 
 3391: @example
 3392: @kbd{45@key{RET}}  ok
 3393: @end example
 3394: 
 3395: Rather than give you a prompt to invite you to input something, the text
 3396: interpreter prints a status message @i{after} it has processed a line
 3397: of input. The status message in this case (``@code{ ok}'' followed by
 3398: carriage-return) indicates that the text interpreter was able to process
 3399: all of your input successfully. Now type something illegal:
 3400: 
 3401: @example
 3402: @kbd{qwer341@key{RET}}
 3403: *the terminal*:2: Undefined word
 3404: >>>qwer341<<<
 3405: Backtrace:
 3406: $2A95B42A20 throw 
 3407: $2A95B57FB8 no.extensions 
 3408: @end example
 3409: 
 3410: The exact text, other than the ``Undefined word'' may differ slightly
 3411: on your system, but the effect is the same; when the text interpreter
 3412: detects an error, it discards any remaining text on a line, resets
 3413: certain internal state and prints an error message. For a detailed
 3414: description of error messages see @ref{Error messages}.
 3415: 
 3416: The text interpreter waits for you to press carriage-return, and then
 3417: processes your input line. Starting at the beginning of the line, it
 3418: breaks the line into groups of characters separated by spaces. For each
 3419: group of characters in turn, it makes two attempts to do something:
 3420: 
 3421: @itemize @bullet
 3422: @item
 3423: @cindex name dictionary
 3424: It tries to treat it as a command. It does this by searching a @dfn{name
 3425: dictionary}. If the group of characters matches an entry in the name
 3426: dictionary, the name dictionary provides the text interpreter with
 3427: information that allows the text interpreter perform some actions. In
 3428: Forth jargon, we say that the group
 3429: @cindex word
 3430: @cindex definition
 3431: @cindex execution token
 3432: @cindex xt
 3433: of characters names a @dfn{word}, that the dictionary search returns an
 3434: @dfn{execution token (xt)} corresponding to the @dfn{definition} of the
 3435: word, and that the text interpreter executes the xt. Often, the terms
 3436: @dfn{word} and @dfn{definition} are used interchangeably.
 3437: @item
 3438: If the text interpreter fails to find a match in the name dictionary, it
 3439: tries to treat the group of characters as a number in the current number
 3440: base (when you start up Forth, the current number base is base 10). If
 3441: the group of characters legitimately represents a number, the text
 3442: interpreter pushes the number onto a stack (we'll learn more about that
 3443: in the next section).
 3444: @end itemize
 3445: 
 3446: If the text interpreter is unable to do either of these things with any
 3447: group of characters, it discards the group of characters and the rest of
 3448: the line, then prints an error message. If the text interpreter reaches
 3449: the end of the line without error, it prints the status message ``@code{ ok}''
 3450: followed by carriage-return.
 3451: 
 3452: This is the simplest command we can give to the text interpreter:
 3453: 
 3454: @example
 3455: @key{RET}  ok
 3456: @end example
 3457: 
 3458: The text interpreter did everything we asked it to do (nothing) without
 3459: an error, so it said that everything is ``@code{ ok}''. Try a slightly longer
 3460: command:
 3461: 
 3462: @example
 3463: @kbd{12 dup fred dup@key{RET}}
 3464: *the terminal*:3: Undefined word
 3465: 12 dup >>>fred<<< dup
 3466: Backtrace:
 3467: $2A95B42A20 throw 
 3468: $2A95B57FB8 no.extensions 
 3469: @end example
 3470: 
 3471: When you press the carriage-return key, the text interpreter starts to
 3472: work its way along the line:
 3473: 
 3474: @itemize @bullet
 3475: @item
 3476: When it gets to the space after the @code{2}, it takes the group of
 3477: characters @code{12} and looks them up in the name
 3478: dictionary@footnote{We can't tell if it found them or not, but assume
 3479: for now that it did not}. There is no match for this group of characters
 3480: in the name dictionary, so it tries to treat them as a number. It is
 3481: able to do this successfully, so it puts the number, 12, ``on the stack''
 3482: (whatever that means).
 3483: @item
 3484: The text interpreter resumes scanning the line and gets the next group
 3485: of characters, @code{dup}. It looks it up in the name dictionary and
 3486: (you'll have to take my word for this) finds it, and executes the word
 3487: @code{dup} (whatever that means).
 3488: @item
 3489: Once again, the text interpreter resumes scanning the line and gets the
 3490: group of characters @code{fred}. It looks them up in the name
 3491: dictionary, but can't find them. It tries to treat them as a number, but
 3492: they don't represent any legal number.
 3493: @end itemize
 3494: 
 3495: At this point, the text interpreter gives up and prints an error
 3496: message. The error message shows exactly how far the text interpreter
 3497: got in processing the line. In particular, it shows that the text
 3498: interpreter made no attempt to do anything with the final character
 3499: group, @code{dup}, even though we have good reason to believe that the
 3500: text interpreter would have no problem looking that word up and
 3501: executing it a second time.
 3502: 
 3503: 
 3504: @comment ----------------------------------------------
 3505: @node Stacks and Postfix notation, Your first definition, Introducing the Text Interpreter, Introduction
 3506: @section Stacks, postfix notation and parameter passing
 3507: @cindex text interpreter
 3508: @cindex outer interpreter
 3509: 
 3510: In procedural programming languages (like C and Pascal), the
 3511: building-block of programs is the @dfn{function} or @dfn{procedure}. These
 3512: functions or procedures are called with @dfn{explicit parameters}. For
 3513: example, in C we might write:
 3514: 
 3515: @example
 3516: total = total + new_volume(length,height,depth);
 3517: @end example
 3518: 
 3519: @noindent
 3520: where new_volume is a function-call to another piece of code, and total,
 3521: length, height and depth are all variables. length, height and depth are
 3522: parameters to the function-call.
 3523: 
 3524: In Forth, the equivalent of the function or procedure is the
 3525: @dfn{definition} and parameters are implicitly passed between
 3526: definitions using a shared stack that is visible to the
 3527: programmer. Although Forth does support variables, the existence of the
 3528: stack means that they are used far less often than in most other
 3529: programming languages. When the text interpreter encounters a number, it
 3530: will place (@dfn{push}) it on the stack. There are several stacks (the
 3531: actual number is implementation-dependent ...) and the particular stack
 3532: used for any operation is implied unambiguously by the operation being
 3533: performed. The stack used for all integer operations is called the @dfn{data
 3534: stack} and, since this is the stack used most commonly, references to
 3535: ``the data stack'' are often abbreviated to ``the stack''.
 3536: 
 3537: The stacks have a last-in, first-out (LIFO) organisation. If you type:
 3538: 
 3539: @example
 3540: @kbd{1 2 3@key{RET}}  ok
 3541: @end example
 3542: 
 3543: Then this instructs the text interpreter to placed three numbers on the
 3544: (data) stack. An analogy for the behaviour of the stack is to take a
 3545: pack of playing cards and deal out the ace (1), 2 and 3 into a pile on
 3546: the table. The 3 was the last card onto the pile (``last-in'') and if
 3547: you take a card off the pile then, unless you're prepared to fiddle a
 3548: bit, the card that you take off will be the 3 (``first-out''). The
 3549: number that will be first-out of the stack is called the @dfn{top of
 3550: stack}, which
 3551: @cindex TOS definition
 3552: is often abbreviated to @dfn{TOS}.
 3553: 
 3554: To understand how parameters are passed in Forth, consider the
 3555: behaviour of the definition @code{+} (pronounced ``plus''). You will not
 3556: be surprised to learn that this definition performs addition. More
 3557: precisely, it adds two number together and produces a result. Where does
 3558: it get the two numbers from? It takes the top two numbers off the
 3559: stack. Where does it place the result? On the stack. You can act-out the
 3560: behaviour of @code{+} with your playing cards like this:
 3561: 
 3562: @itemize @bullet
 3563: @item
 3564: Pick up two cards from the stack on the table
 3565: @item
 3566: Stare at them intently and ask yourself ``what @i{is} the sum of these two
 3567: numbers''
 3568: @item
 3569: Decide that the answer is 5
 3570: @item
 3571: Shuffle the two cards back into the pack and find a 5
 3572: @item
 3573: Put a 5 on the remaining ace that's on the table.
 3574: @end itemize
 3575: 
 3576: If you don't have a pack of cards handy but you do have Forth running,
 3577: you can use the definition @code{.s} to show the current state of the stack,
 3578: without affecting the stack. Type:
 3579: 
 3580: @example
 3581: @kbd{clearstacks 1 2 3@key{RET}} ok
 3582: @kbd{.s@key{RET}} <3> 1 2 3  ok
 3583: @end example
 3584: 
 3585: The text interpreter looks up the word @code{clearstacks} and executes
 3586: it; it tidies up the stacks and removes any entries that may have been
 3587: left on it by earlier examples. The text interpreter pushes each of the
 3588: three numbers in turn onto the stack. Finally, the text interpreter
 3589: looks up the word @code{.s} and executes it. The effect of executing
 3590: @code{.s} is to print the ``<3>'' (the total number of items on the stack)
 3591: followed by a list of all the items on the stack; the item on the far
 3592: right-hand side is the TOS.
 3593: 
 3594: You can now type:
 3595: 
 3596: @example
 3597: @kbd{+ .s@key{RET}} <2> 1 5  ok
 3598: @end example
 3599: 
 3600: @noindent
 3601: which is correct; there are now 2 items on the stack and the result of
 3602: the addition is 5.
 3603: 
 3604: If you're playing with cards, try doing a second addition: pick up the
 3605: two cards, work out that their sum is 6, shuffle them into the pack,
 3606: look for a 6 and place that on the table. You now have just one item on
 3607: the stack. What happens if you try to do a third addition? Pick up the
 3608: first card, pick up the second card -- ah! There is no second card. This
 3609: is called a @dfn{stack underflow} and consitutes an error. If you try to
 3610: do the same thing with Forth it often reports an error (probably a Stack
 3611: Underflow or an Invalid Memory Address error).
 3612: 
 3613: The opposite situation to a stack underflow is a @dfn{stack overflow},
 3614: which simply accepts that there is a finite amount of storage space
 3615: reserved for the stack. To stretch the playing card analogy, if you had
 3616: enough packs of cards and you piled the cards up on the table, you would
 3617: eventually be unable to add another card; you'd hit the ceiling. Gforth
 3618: allows you to set the maximum size of the stacks. In general, the only
 3619: time that you will get a stack overflow is because a definition has a
 3620: bug in it and is generating data on the stack uncontrollably.
 3621: 
 3622: There's one final use for the playing card analogy. If you model your
 3623: stack using a pack of playing cards, the maximum number of items on
 3624: your stack will be 52 (I assume you didn't use the Joker). The maximum
 3625: @i{value} of any item on the stack is 13 (the King). In fact, the only
 3626: possible numbers are positive integer numbers 1 through 13; you can't
 3627: have (for example) 0 or 27 or 3.52 or -2. If you change the way you
 3628: think about some of the cards, you can accommodate different
 3629: numbers. For example, you could think of the Jack as representing 0,
 3630: the Queen as representing -1 and the King as representing -2. Your
 3631: @i{range} remains unchanged (you can still only represent a total of 13
 3632: numbers) but the numbers that you can represent are -2 through 10.
 3633: 
 3634: In that analogy, the limit was the amount of information that a single
 3635: stack entry could hold, and Forth has a similar limit. In Forth, the
 3636: size of a stack entry is called a @dfn{cell}. The actual size of a cell is
 3637: implementation dependent and affects the maximum value that a stack
 3638: entry can hold. A Standard Forth provides a cell size of at least
 3639: 16-bits, and most desktop systems use a cell size of 32-bits.
 3640: 
 3641: Forth does not do any type checking for you, so you are free to
 3642: manipulate and combine stack items in any way you wish. A convenient way
 3643: of treating stack items is as 2's complement signed integers, and that
 3644: is what Standard words like @code{+} do. Therefore you can type:
 3645: 
 3646: @example
 3647: @kbd{-5 12 + .s@key{RET}} <1> 7  ok
 3648: @end example
 3649: 
 3650: If you use numbers and definitions like @code{+} in order to turn Forth
 3651: into a great big pocket calculator, you will realise that it's rather
 3652: different from a normal calculator. Rather than typing 2 + 3 = you had
 3653: to type 2 3 + (ignore the fact that you had to use @code{.s} to see the
 3654: result). The terminology used to describe this difference is to say that
 3655: your calculator uses @dfn{Infix Notation} (parameters and operators are
 3656: mixed) whilst Forth uses @dfn{Postfix Notation} (parameters and
 3657: operators are separate), also called @dfn{Reverse Polish Notation}.
 3658: 
 3659: Whilst postfix notation might look confusing to begin with, it has
 3660: several important advantages:
 3661: 
 3662: @itemize @bullet
 3663: @item
 3664: it is unambiguous
 3665: @item
 3666: it is more concise
 3667: @item
 3668: it fits naturally with a stack-based system
 3669: @end itemize
 3670: 
 3671: To examine these claims in more detail, consider these sums:
 3672: 
 3673: @example
 3674: 6 + 5 * 4 =
 3675: 4 * 5 + 6 =
 3676: @end example
 3677: 
 3678: If you're just learning maths or your maths is very rusty, you will
 3679: probably come up with the answer 44 for the first and 26 for the
 3680: second. If you are a bit of a whizz at maths you will remember the
 3681: @i{convention} that multiplication takes precendence over addition, and
 3682: you'd come up with the answer 26 both times. To explain the answer 26
 3683: to someone who got the answer 44, you'd probably rewrite the first sum
 3684: like this:
 3685: 
 3686: @example
 3687: 6 + (5 * 4) =
 3688: @end example
 3689: 
 3690: If what you really wanted was to perform the addition before the
 3691: multiplication, you would have to use parentheses to force it.
 3692: 
 3693: If you did the first two sums on a pocket calculator you would probably
 3694: get the right answers, unless you were very cautious and entered them using
 3695: these keystroke sequences:
 3696: 
 3697: 6 + 5 = * 4 =
 3698: 4 * 5 = + 6 =
 3699: 
 3700: Postfix notation is unambiguous because the order that the operators
 3701: are applied is always explicit; that also means that parentheses are
 3702: never required. The operators are @i{active} (the act of quoting the
 3703: operator makes the operation occur) which removes the need for ``=''.
 3704: 
 3705: The sum 6 + 5 * 4 can be written (in postfix notation) in two
 3706: equivalent ways:
 3707: 
 3708: @example
 3709: 6 5 4 * +      or:
 3710: 5 4 * 6 +
 3711: @end example
 3712: 
 3713: An important thing that you should notice about this notation is that
 3714: the @i{order} of the numbers does not change; if you want to subtract
 3715: 2 from 10 you type @code{10 2 -}.
 3716: 
 3717: The reason that Forth uses postfix notation is very simple to explain: it
 3718: makes the implementation extremely simple, and it follows naturally from
 3719: using the stack as a mechanism for passing parameters. Another way of
 3720: thinking about this is to realise that all Forth definitions are
 3721: @i{active}; they execute as they are encountered by the text
 3722: interpreter. The result of this is that the syntax of Forth is trivially
 3723: simple.
 3724: 
 3725: 
 3726: 
 3727: @comment ----------------------------------------------
 3728: @node Your first definition, How does that work?, Stacks and Postfix notation, Introduction
 3729: @section Your first Forth definition
 3730: @cindex first definition
 3731: 
 3732: Until now, the examples we've seen have been trivial; we've just been
 3733: using Forth as a bigger-than-pocket calculator. Also, each calculation
 3734: we've shown has been a ``one-off'' -- to repeat it we'd need to type it in
 3735: again@footnote{That's not quite true. If you press the up-arrow key on
 3736: your keyboard you should be able to scroll back to any earlier command,
 3737: edit it and re-enter it.} In this section we'll see how to add new
 3738: words to Forth's vocabulary.
 3739: 
 3740: The easiest way to create a new word is to use a @dfn{colon
 3741: definition}. We'll define a few and try them out before worrying too
 3742: much about how they work. Try typing in these examples; be careful to
 3743: copy the spaces accurately:
 3744: 
 3745: @example
 3746: : add-two 2 + . ;
 3747: : greet ." Hello and welcome" ;
 3748: : demo 5 add-two ;
 3749: @end example
 3750: 
 3751: @noindent
 3752: Now try them out:
 3753: 
 3754: @example
 3755: @kbd{greet@key{RET}} Hello and welcome  ok
 3756: @kbd{greet greet@key{RET}} Hello and welcomeHello and welcome  ok
 3757: @kbd{4 add-two@key{RET}} 6  ok
 3758: @kbd{demo@key{RET}} 7  ok
 3759: @kbd{9 greet demo add-two@key{RET}} Hello and welcome7 11  ok
 3760: @end example
 3761: 
 3762: The first new thing that we've introduced here is the pair of words
 3763: @code{:} and @code{;}. These are used to start and terminate a new
 3764: definition, respectively. The first word after the @code{:} is the name
 3765: for the new definition.
 3766: 
 3767: As you can see from the examples, a definition is built up of words that
 3768: have already been defined; Forth makes no distinction between
 3769: definitions that existed when you started the system up, and those that
 3770: you define yourself.
 3771: 
 3772: The examples also introduce the words @code{.} (dot), @code{."}
 3773: (dot-quote) and @code{dup} (dewp). Dot takes the value from the top of
 3774: the stack and displays it. It's like @code{.s} except that it only
 3775: displays the top item of the stack and it is destructive; after it has
 3776: executed, the number is no longer on the stack. There is always one
 3777: space printed after the number, and no spaces before it. Dot-quote
 3778: defines a string (a sequence of characters) that will be printed when
 3779: the word is executed. The string can contain any printable characters
 3780: except @code{"}. A @code{"} has a special function; it is not a Forth
 3781: word but it acts as a delimiter (the way that delimiters work is
 3782: described in the next section). Finally, @code{dup} duplicates the value
 3783: at the top of the stack. Try typing @code{5 dup .s} to see what it does.
 3784: 
 3785: We already know that the text interpreter searches through the
 3786: dictionary to locate names. If you've followed the examples earlier, you
 3787: will already have a definition called @code{add-two}. Lets try modifying
 3788: it by typing in a new definition:
 3789: 
 3790: @example
 3791: @kbd{: add-two dup . ." + 2 =" 2 + . ;@key{RET}} redefined add-two  ok
 3792: @end example
 3793: 
 3794: Forth recognised that we were defining a word that already exists, and
 3795: printed a message to warn us of that fact. Let's try out the new
 3796: definition:
 3797: 
 3798: @example
 3799: @kbd{9 add-two@key{RET}} 9 + 2 =11  ok
 3800: @end example
 3801: 
 3802: @noindent
 3803: All that we've actually done here, though, is to create a new
 3804: definition, with a particular name. The fact that there was already a
 3805: definition with the same name did not make any difference to the way
 3806: that the new definition was created (except that Forth printed a warning
 3807: message). The old definition of add-two still exists (try @code{demo}
 3808: again to see that this is true). Any new definition will use the new
 3809: definition of @code{add-two}, but old definitions continue to use the
 3810: version that already existed at the time that they were @code{compiled}.
 3811: 
 3812: Before you go on to the next section, try defining and redefining some
 3813: words of your own.
 3814: 
 3815: @comment ----------------------------------------------
 3816: @node How does that work?, Forth is written in Forth, Your first definition, Introduction
 3817: @section How does that work?
 3818: @cindex parsing words
 3819: 
 3820: @c That's pretty deep (IMO way too deep) for an introduction. - anton
 3821: 
 3822: @c Is it a good idea to talk about the interpretation semantics of a
 3823: @c number? We don't have an xt to go along with it. - anton
 3824: 
 3825: @c Now that I have eliminated execution semantics, I wonder if it would not
 3826: @c be better to keep them (or add run-time semantics), to make it easier to
 3827: @c explain what compilation semantics usually does. - anton
 3828: 
 3829: @c nac-> I removed the term ``default compilation sematics'' from the
 3830: @c introductory chapter. Removing ``execution semantics'' was making
 3831: @c everything simpler to explain, then I think the use of this term made
 3832: @c everything more complex again. I replaced it with ``default
 3833: @c semantics'' (which is used elsewhere in the manual) by which I mean
 3834: @c ``a definition that has neither the immediate nor the compile-only
 3835: @c flag set''.
 3836: 
 3837: @c anton: I have eliminated default semantics (except in one place where it
 3838: @c means "default interpretation and compilation semantics"), because it
 3839: @c makes no sense in the presence of combined words.  I reverted to
 3840: @c "execution semantics" where necessary.
 3841: 
 3842: @c nac-> I reworded big chunks of the ``how does that work''
 3843: @c section (and, unusually for me, I think I even made it shorter!).  See
 3844: @c what you think -- I know I have not addressed your primary concern
 3845: @c that it is too heavy-going for an introduction. From what I understood
 3846: @c of your course notes it looks as though they might be a good framework. 
 3847: @c Things that I've tried to capture here are some things that came as a
 3848: @c great revelation here when I first understood them. Also, I like the
 3849: @c fact that a very simple code example shows up almost all of the issues
 3850: @c that you need to understand to see how Forth works. That's unique and
 3851: @c worthwhile to emphasise.
 3852: 
 3853: @c anton: I think it's a good idea to present the details, especially those
 3854: @c that you found to be a revelation, and probably the tutorial tries to be
 3855: @c too superficial and does not get some of the things across that make
 3856: @c Forth special.  I do believe that most of the time these things should
 3857: @c be discussed at the end of a section or in separate sections instead of
 3858: @c in the middle of a section (e.g., the stuff you added in "User-defined
 3859: @c defining words" leads in a completely different direction from the rest
 3860: @c of the section).
 3861: 
 3862: Now we're going to take another look at the definition of @code{add-two}
 3863: from the previous section. From our knowledge of the way that the text
 3864: interpreter works, we would have expected this result when we tried to
 3865: define @code{add-two}:
 3866: 
 3867: @example
 3868: @kbd{: add-two 2 + . ;@key{RET}}
 3869: *the terminal*:4: Undefined word
 3870: : >>>add-two<<< 2 + . ;
 3871: @end example
 3872: 
 3873: The reason that this didn't happen is bound up in the way that @code{:}
 3874: works. The word @code{:} does two special things. The first special
 3875: thing that it does prevents the text interpreter from ever seeing the
 3876: characters @code{add-two}. The text interpreter uses a variable called
 3877: @cindex modifying >IN
 3878: @code{>IN} (pronounced ``to-in'') to keep track of where it is in the
 3879: input line. When it encounters the word @code{:} it behaves in exactly
 3880: the same way as it does for any other word; it looks it up in the name
 3881: dictionary, finds its xt and executes it. When @code{:} executes, it
 3882: looks at the input buffer, finds the word @code{add-two} and advances the
 3883: value of @code{>IN} to point past it. It then does some other stuff
 3884: associated with creating the new definition (including creating an entry
 3885: for @code{add-two} in the name dictionary). When the execution of @code{:}
 3886: completes, control returns to the text interpreter, which is oblivious
 3887: to the fact that it has been tricked into ignoring part of the input
 3888: line.
 3889: 
 3890: @cindex parsing words
 3891: Words like @code{:} -- words that advance the value of @code{>IN} and so
 3892: prevent the text interpreter from acting on the whole of the input line
 3893: -- are called @dfn{parsing words}.
 3894: 
 3895: @cindex @code{state} - effect on the text interpreter
 3896: @cindex text interpreter - effect of state
 3897: The second special thing that @code{:} does is change the value of a
 3898: variable called @code{state}, which affects the way that the text
 3899: interpreter behaves. When Gforth starts up, @code{state} has the value
 3900: 0, and the text interpreter is said to be @dfn{interpreting}. During a
 3901: colon definition (started with @code{:}), @code{state} is set to -1 and
 3902: the text interpreter is said to be @dfn{compiling}.
 3903: 
 3904: In this example, the text interpreter is compiling when it processes the
 3905: string ``@code{2 + . ;}''. It still breaks the string down into
 3906: character sequences in the same way. However, instead of pushing the
 3907: number @code{2} onto the stack, it lays down (@dfn{compiles}) some magic
 3908: into the definition of @code{add-two} that will make the number @code{2} get
 3909: pushed onto the stack when @code{add-two} is @dfn{executed}. Similarly,
 3910: the behaviours of @code{+} and @code{.} are also compiled into the
 3911: definition.
 3912: 
 3913: One category of words don't get compiled. These so-called @dfn{immediate
 3914: words} get executed (performed @i{now}) regardless of whether the text
 3915: interpreter is interpreting or compiling. The word @code{;} is an
 3916: immediate word. Rather than being compiled into the definition, it
 3917: executes. Its effect is to terminate the current definition, which
 3918: includes changing the value of @code{state} back to 0.
 3919: 
 3920: When you execute @code{add-two}, it has a @dfn{run-time effect} that is
 3921: exactly the same as if you had typed @code{2 + . @key{RET}} outside of a
 3922: definition.
 3923: 
 3924: In Forth, every word or number can be described in terms of two
 3925: properties:
 3926: 
 3927: @itemize @bullet
 3928: @item
 3929: @cindex interpretation semantics
 3930: Its @dfn{interpretation semantics} describe how it will behave when the
 3931: text interpreter encounters it in @dfn{interpret} state. The
 3932: interpretation semantics of a word are represented by an @dfn{execution
 3933: token}.
 3934: @item
 3935: @cindex compilation semantics
 3936: Its @dfn{compilation semantics} describe how it will behave when the
 3937: text interpreter encounters it in @dfn{compile} state. The compilation
 3938: semantics of a word are represented in an implementation-dependent way;
 3939: Gforth uses a @dfn{compilation token}.
 3940: @end itemize
 3941: 
 3942: @noindent
 3943: Numbers are always treated in a fixed way:
 3944: 
 3945: @itemize @bullet
 3946: @item
 3947: When the number is @dfn{interpreted}, its behaviour is to push the
 3948: number onto the stack.
 3949: @item
 3950: When the number is @dfn{compiled}, a piece of code is appended to the
 3951: current definition that pushes the number when it runs. (In other words,
 3952: the compilation semantics of a number are to postpone its interpretation
 3953: semantics until the run-time of the definition that it is being compiled
 3954: into.)
 3955: @end itemize
 3956: 
 3957: Words don't behave in such a regular way, but most have @i{default
 3958: semantics} which means that they behave like this:
 3959: 
 3960: @itemize @bullet
 3961: @item
 3962: The @dfn{interpretation semantics} of the word are to do something useful.
 3963: @item
 3964: The @dfn{compilation semantics} of the word are to append its
 3965: @dfn{interpretation semantics} to the current definition (so that its
 3966: run-time behaviour is to do something useful).
 3967: @end itemize
 3968: 
 3969: @cindex immediate words
 3970: The actual behaviour of any particular word can be controlled by using
 3971: the words @code{immediate} and @code{compile-only} when the word is
 3972: defined. These words set flags in the name dictionary entry of the most
 3973: recently defined word, and these flags are retrieved by the text
 3974: interpreter when it finds the word in the name dictionary.
 3975: 
 3976: A word that is marked as @dfn{immediate} has compilation semantics that
 3977: are identical to its interpretation semantics. In other words, it
 3978: behaves like this:
 3979: 
 3980: @itemize @bullet
 3981: @item
 3982: The @dfn{interpretation semantics} of the word are to do something useful.
 3983: @item
 3984: The @dfn{compilation semantics} of the word are to do something useful
 3985: (and actually the same thing); i.e., it is executed during compilation.
 3986: @end itemize
 3987: 
 3988: Marking a word as @dfn{compile-only} prohibits the text interpreter from
 3989: performing the interpretation semantics of the word directly; an attempt
 3990: to do so will generate an error. It is never necessary to use
 3991: @code{compile-only} (and it is not even part of ANS Forth, though it is
 3992: provided by many implementations) but it is good etiquette to apply it
 3993: to a word that will not behave correctly (and might have unexpected
 3994: side-effects) in interpret state. For example, it is only legal to use
 3995: the conditional word @code{IF} within a definition. If you forget this
 3996: and try to use it elsewhere, the fact that (in Gforth) it is marked as
 3997: @code{compile-only} allows the text interpreter to generate a helpful
 3998: error message rather than subjecting you to the consequences of your
 3999: folly.
 4000: 
 4001: This example shows the difference between an immediate and a
 4002: non-immediate word:
 4003: 
 4004: @example
 4005: : show-state state @@ . ;
 4006: : show-state-now show-state ; immediate
 4007: : word1 show-state ;
 4008: : word2 show-state-now ;
 4009: @end example
 4010: 
 4011: The word @code{immediate} after the definition of @code{show-state-now}
 4012: makes that word an immediate word. These definitions introduce a new
 4013: word: @code{@@} (pronounced ``fetch''). This word fetches the value of a
 4014: variable, and leaves it on the stack. Therefore, the behaviour of
 4015: @code{show-state} is to print a number that represents the current value
 4016: of @code{state}.
 4017: 
 4018: When you execute @code{word1}, it prints the number 0, indicating that
 4019: the system is interpreting. When the text interpreter compiled the
 4020: definition of @code{word1}, it encountered @code{show-state} whose
 4021: compilation semantics are to append its interpretation semantics to the
 4022: current definition. When you execute @code{word1}, it performs the
 4023: interpretation semantics of @code{show-state}.  At the time that @code{word1}
 4024: (and therefore @code{show-state}) are executed, the system is
 4025: interpreting.
 4026: 
 4027: When you pressed @key{RET} after entering the definition of @code{word2},
 4028: you should have seen the number -1 printed, followed by ``@code{
 4029: ok}''. When the text interpreter compiled the definition of
 4030: @code{word2}, it encountered @code{show-state-now}, an immediate word,
 4031: whose compilation semantics are therefore to perform its interpretation
 4032: semantics. It is executed straight away (even before the text
 4033: interpreter has moved on to process another group of characters; the
 4034: @code{;} in this example). The effect of executing it are to display the
 4035: value of @code{state} @i{at the time that the definition of}
 4036: @code{word2} @i{is being defined}. Printing -1 demonstrates that the
 4037: system is compiling at this time. If you execute @code{word2} it does
 4038: nothing at all.
 4039: 
 4040: @cindex @code{."}, how it works
 4041: Before leaving the subject of immediate words, consider the behaviour of
 4042: @code{."} in the definition of @code{greet}, in the previous
 4043: section. This word is both a parsing word and an immediate word. Notice
 4044: that there is a space between @code{."} and the start of the text
 4045: @code{Hello and welcome}, but that there is no space between the last
 4046: letter of @code{welcome} and the @code{"} character. The reason for this
 4047: is that @code{."} is a Forth word; it must have a space after it so that
 4048: the text interpreter can identify it. The @code{"} is not a Forth word;
 4049: it is a @dfn{delimiter}. The examples earlier show that, when the string
 4050: is displayed, there is neither a space before the @code{H} nor after the
 4051: @code{e}. Since @code{."} is an immediate word, it executes at the time
 4052: that @code{greet} is defined. When it executes, its behaviour is to
 4053: search forward in the input line looking for the delimiter. When it
 4054: finds the delimiter, it updates @code{>IN} to point past the
 4055: delimiter. It also compiles some magic code into the definition of
 4056: @code{greet}; the xt of a run-time routine that prints a text string. It
 4057: compiles the string @code{Hello and welcome} into memory so that it is
 4058: available to be printed later. When the text interpreter gains control,
 4059: the next word it finds in the input stream is @code{;} and so it
 4060: terminates the definition of @code{greet}.
 4061: 
 4062: 
 4063: @comment ----------------------------------------------
 4064: @node Forth is written in Forth, Review - elements of a Forth system, How does that work?, Introduction
 4065: @section Forth is written in Forth
 4066: @cindex structure of Forth programs
 4067: 
 4068: When you start up a Forth compiler, a large number of definitions
 4069: already exist. In Forth, you develop a new application using bottom-up
 4070: programming techniques to create new definitions that are defined in
 4071: terms of existing definitions. As you create each definition you can
 4072: test and debug it interactively.
 4073: 
 4074: If you have tried out the examples in this section, you will probably
 4075: have typed them in by hand; when you leave Gforth, your definitions will
 4076: be lost. You can avoid this by using a text editor to enter Forth source
 4077: code into a file, and then loading code from the file using
 4078: @code{include} (@pxref{Forth source files}). A Forth source file is
 4079: processed by the text interpreter, just as though you had typed it in by
 4080: hand@footnote{Actually, there are some subtle differences -- see
 4081: @ref{The Text Interpreter}.}.
 4082: 
 4083: Gforth also supports the traditional Forth alternative to using text
 4084: files for program entry (@pxref{Blocks}).
 4085: 
 4086: In common with many, if not most, Forth compilers, most of Gforth is
 4087: actually written in Forth. All of the @file{.fs} files in the
 4088: installation directory@footnote{For example,
 4089: @file{/usr/local/share/gforth...}} are Forth source files, which you can
 4090: study to see examples of Forth programming.
 4091: 
 4092: Gforth maintains a history file that records every line that you type to
 4093: the text interpreter. This file is preserved between sessions, and is
 4094: used to provide a command-line recall facility. If you enter long
 4095: definitions by hand, you can use a text editor to paste them out of the
 4096: history file into a Forth source file for reuse at a later time
 4097: (for more information @pxref{Command-line editing}).
 4098: 
 4099: 
 4100: @comment ----------------------------------------------
 4101: @node Review - elements of a Forth system, Where to go next, Forth is written in Forth, Introduction
 4102: @section Review - elements of a Forth system
 4103: @cindex elements of a Forth system
 4104: 
 4105: To summarise this chapter:
 4106: 
 4107: @itemize @bullet
 4108: @item
 4109: Forth programs use @dfn{factoring} to break a problem down into small
 4110: fragments called @dfn{words} or @dfn{definitions}.
 4111: @item
 4112: Forth program development is an interactive process.
 4113: @item
 4114: The main command loop that accepts input, and controls both
 4115: interpretation and compilation, is called the @dfn{text interpreter}
 4116: (also known as the @dfn{outer interpreter}).
 4117: @item
 4118: Forth has a very simple syntax, consisting of words and numbers
 4119: separated by spaces or carriage-return characters. Any additional syntax
 4120: is imposed by @dfn{parsing words}.
 4121: @item
 4122: Forth uses a stack to pass parameters between words. As a result, it
 4123: uses postfix notation.
 4124: @item
 4125: To use a word that has previously been defined, the text interpreter
 4126: searches for the word in the @dfn{name dictionary}.
 4127: @item
 4128: Words have @dfn{interpretation semantics} and @dfn{compilation semantics}.
 4129: @item
 4130: The text interpreter uses the value of @code{state} to select between
 4131: the use of the @dfn{interpretation semantics} and the  @dfn{compilation
 4132: semantics} of a word that it encounters.
 4133: @item
 4134: The relationship between the @dfn{interpretation semantics} and
 4135: @dfn{compilation semantics} for a word
 4136: depend upon the way in which the word was defined (for example, whether
 4137: it is an @dfn{immediate} word).
 4138: @item
 4139: Forth definitions can be implemented in Forth (called @dfn{high-level
 4140: definitions}) or in some other way (usually a lower-level language and
 4141: as a result often called @dfn{low-level definitions}, @dfn{code
 4142: definitions} or @dfn{primitives}).
 4143: @item
 4144: Many Forth systems are implemented mainly in Forth.
 4145: @end itemize
 4146: 
 4147: 
 4148: @comment ----------------------------------------------
 4149: @node Where to go next, Exercises, Review - elements of a Forth system, Introduction
 4150: @section Where To Go Next
 4151: @cindex where to go next
 4152: 
 4153: Amazing as it may seem, if you have read (and understood) this far, you
 4154: know almost all the fundamentals about the inner workings of a Forth
 4155: system. You certainly know enough to be able to read and understand the
 4156: rest of this manual and the ANS Forth document, to learn more about the
 4157: facilities that Forth in general and Gforth in particular provide. Even
 4158: scarier, you know almost enough to implement your own Forth system.
 4159: However, that's not a good idea just yet... better to try writing some
 4160: programs in Gforth.
 4161: 
 4162: Forth has such a rich vocabulary that it can be hard to know where to
 4163: start in learning it. This section suggests a few sets of words that are
 4164: enough to write small but useful programs. Use the word index in this
 4165: document to learn more about each word, then try it out and try to write
 4166: small definitions using it. Start by experimenting with these words:
 4167: 
 4168: @itemize @bullet
 4169: @item
 4170: Arithmetic: @code{+ - * / /MOD */ ABS INVERT}
 4171: @item
 4172: Comparison: @code{MIN MAX =}
 4173: @item
 4174: Logic: @code{AND OR XOR NOT}
 4175: @item
 4176: Stack manipulation: @code{DUP DROP SWAP OVER}
 4177: @item
 4178: Loops and decisions: @code{IF ELSE ENDIF ?DO I LOOP}
 4179: @item
 4180: Input/Output: @code{. ." EMIT CR KEY}
 4181: @item
 4182: Defining words: @code{: ; CREATE}
 4183: @item
 4184: Memory allocation words: @code{ALLOT ,}
 4185: @item
 4186: Tools: @code{SEE WORDS .S MARKER}
 4187: @end itemize
 4188: 
 4189: When you have mastered those, go on to:
 4190: 
 4191: @itemize @bullet
 4192: @item
 4193: More defining words: @code{VARIABLE CONSTANT VALUE TO CREATE DOES>}
 4194: @item
 4195: Memory access: @code{@@ !}
 4196: @end itemize
 4197: 
 4198: When you have mastered these, there's nothing for it but to read through
 4199: the whole of this manual and find out what you've missed.
 4200: 
 4201: @comment ----------------------------------------------
 4202: @node Exercises,  , Where to go next, Introduction
 4203: @section Exercises
 4204: @cindex exercises
 4205: 
 4206: TODO: provide a set of programming excercises linked into the stuff done
 4207: already and into other sections of the manual. Provide solutions to all
 4208: the exercises in a .fs file in the distribution.
 4209: 
 4210: @c Get some inspiration from Starting Forth and Kelly&Spies.
 4211: 
 4212: @c excercises:
 4213: @c 1. take inches and convert to feet and inches.
 4214: @c 2. take temperature and convert from fahrenheight to celcius;
 4215: @c    may need to care about symmetric vs floored??
 4216: @c 3. take input line and do character substitution
 4217: @c    to encipher or decipher
 4218: @c 4. as above but work on a file for in and out
 4219: @c 5. take input line and convert to pig-latin 
 4220: @c
 4221: @c thing of sets of things to exercise then come up with
 4222: @c problems that need those things.
 4223: 
 4224: 
 4225: @c ******************************************************************
 4226: @node Words, Error messages, Introduction, Top
 4227: @chapter Forth Words
 4228: @cindex words
 4229: 
 4230: @menu
 4231: * Notation::                    
 4232: * Case insensitivity::          
 4233: * Comments::                    
 4234: * Boolean Flags::               
 4235: * Arithmetic::                  
 4236: * Stack Manipulation::          
 4237: * Memory::                      
 4238: * Control Structures::          
 4239: * Defining Words::              
 4240: * Interpretation and Compilation Semantics::  
 4241: * Tokens for Words::            
 4242: * Compiling words::             
 4243: * The Text Interpreter::        
 4244: * The Input Stream::            
 4245: * Word Lists::                  
 4246: * Environmental Queries::       
 4247: * Files::                       
 4248: * Blocks::                      
 4249: * Other I/O::                   
 4250: * OS command line arguments::   
 4251: * Locals::                      
 4252: * Structures::                  
 4253: * Object-oriented Forth::       
 4254: * Programming Tools::           
 4255: * C Interface::                 
 4256: * Assembler and Code Words::    
 4257: * Threading Words::             
 4258: * Passing Commands to the OS::  
 4259: * Keeping track of Time::       
 4260: * Miscellaneous Words::         
 4261: @end menu
 4262: 
 4263: @node Notation, Case insensitivity, Words, Words
 4264: @section Notation
 4265: @cindex notation of glossary entries
 4266: @cindex format of glossary entries
 4267: @cindex glossary notation format
 4268: @cindex word glossary entry format
 4269: 
 4270: The Forth words are described in this section in the glossary notation
 4271: that has become a de-facto standard for Forth texts:
 4272: 
 4273: @format
 4274: @i{word}     @i{Stack effect}   @i{wordset}   @i{pronunciation}
 4275: @end format
 4276: @i{Description}
 4277: 
 4278: @table @var
 4279: @item word
 4280: The name of the word.
 4281: 
 4282: @item Stack effect
 4283: @cindex stack effect
 4284: The stack effect is written in the notation @code{@i{before} --
 4285: @i{after}}, where @i{before} and @i{after} describe the top of
 4286: stack entries before and after the execution of the word. The rest of
 4287: the stack is not touched by the word. The top of stack is rightmost,
 4288: i.e., a stack sequence is written as it is typed in. Note that Gforth
 4289: uses a separate floating point stack, but a unified stack
 4290: notation. Also, return stack effects are not shown in @i{stack
 4291: effect}, but in @i{Description}. The name of a stack item describes
 4292: the type and/or the function of the item. See below for a discussion of
 4293: the types.
 4294: 
 4295: All words have two stack effects: A compile-time stack effect and a
 4296: run-time stack effect. The compile-time stack-effect of most words is
 4297: @i{ -- }. If the compile-time stack-effect of a word deviates from
 4298: this standard behaviour, or the word does other unusual things at
 4299: compile time, both stack effects are shown; otherwise only the run-time
 4300: stack effect is shown.
 4301: 
 4302: @cindex pronounciation of words
 4303: @item pronunciation
 4304: How the word is pronounced.
 4305: 
 4306: @cindex wordset
 4307: @cindex environment wordset
 4308: @item wordset
 4309: The ANS Forth standard is divided into several word sets. A standard
 4310: system need not support all of them. Therefore, in theory, the fewer
 4311: word sets your program uses the more portable it will be. However, we
 4312: suspect that most ANS Forth systems on personal machines will feature
 4313: all word sets. Words that are not defined in ANS Forth have
 4314: @code{gforth} or @code{gforth-internal} as word set. @code{gforth}
 4315: describes words that will work in future releases of Gforth;
 4316: @code{gforth-internal} words are more volatile. Environmental query
 4317: strings are also displayed like words; you can recognize them by the
 4318: @code{environment} in the word set field.
 4319: 
 4320: @item Description
 4321: A description of the behaviour of the word.
 4322: @end table
 4323: 
 4324: @cindex types of stack items
 4325: @cindex stack item types
 4326: The type of a stack item is specified by the character(s) the name
 4327: starts with:
 4328: 
 4329: @table @code
 4330: @item f
 4331: @cindex @code{f}, stack item type
 4332: Boolean flags, i.e. @code{false} or @code{true}.
 4333: @item c
 4334: @cindex @code{c}, stack item type
 4335: Char
 4336: @item w
 4337: @cindex @code{w}, stack item type
 4338: Cell, can contain an integer or an address
 4339: @item n
 4340: @cindex @code{n}, stack item type
 4341: signed integer
 4342: @item u
 4343: @cindex @code{u}, stack item type
 4344: unsigned integer
 4345: @item d
 4346: @cindex @code{d}, stack item type
 4347: double sized signed integer
 4348: @item ud
 4349: @cindex @code{ud}, stack item type
 4350: double sized unsigned integer
 4351: @item r
 4352: @cindex @code{r}, stack item type
 4353: Float (on the FP stack)
 4354: @item a-
 4355: @cindex @code{a_}, stack item type
 4356: Cell-aligned address
 4357: @item c-
 4358: @cindex @code{c_}, stack item type
 4359: Char-aligned address (note that a Char may have two bytes in Windows NT)
 4360: @item f-
 4361: @cindex @code{f_}, stack item type
 4362: Float-aligned address
 4363: @item df-
 4364: @cindex @code{df_}, stack item type
 4365: Address aligned for IEEE double precision float
 4366: @item sf-
 4367: @cindex @code{sf_}, stack item type
 4368: Address aligned for IEEE single precision float
 4369: @item xt
 4370: @cindex @code{xt}, stack item type
 4371: Execution token, same size as Cell
 4372: @item wid
 4373: @cindex @code{wid}, stack item type
 4374: Word list ID, same size as Cell
 4375: @item ior, wior
 4376: @cindex ior type description
 4377: @cindex wior type description
 4378: I/O result code, cell-sized.  In Gforth, you can @code{throw} iors.
 4379: @item f83name
 4380: @cindex @code{f83name}, stack item type
 4381: Pointer to a name structure
 4382: @item "
 4383: @cindex @code{"}, stack item type
 4384: string in the input stream (not on the stack). The terminating character
 4385: is a blank by default. If it is not a blank, it is shown in @code{<>}
 4386: quotes.
 4387: @end table
 4388: 
 4389: @comment ----------------------------------------------
 4390: @node Case insensitivity, Comments, Notation, Words
 4391: @section Case insensitivity
 4392: @cindex case sensitivity
 4393: @cindex upper and lower case
 4394: 
 4395: Gforth is case-insensitive; you can enter definitions and invoke
 4396: Standard words using upper, lower or mixed case (however,
 4397: @pxref{core-idef, Implementation-defined options, Implementation-defined
 4398: options}).
 4399: 
 4400: ANS Forth only @i{requires} implementations to recognise Standard words
 4401: when they are typed entirely in upper case. Therefore, a Standard
 4402: program must use upper case for all Standard words. You can use whatever
 4403: case you like for words that you define, but in a Standard program you
 4404: have to use the words in the same case that you defined them.
 4405: 
 4406: Gforth supports case sensitivity through @code{table}s (case-sensitive
 4407: wordlists, @pxref{Word Lists}).
 4408: 
 4409: Two people have asked how to convert Gforth to be case-sensitive; while
 4410: we think this is a bad idea, you can change all wordlists into tables
 4411: like this:
 4412: 
 4413: @example
 4414: ' table-find forth-wordlist wordlist-map @ !
 4415: @end example
 4416: 
 4417: Note that you now have to type the predefined words in the same case
 4418: that we defined them, which are varying.  You may want to convert them
 4419: to your favourite case before doing this operation (I won't explain how,
 4420: because if you are even contemplating doing this, you'd better have
 4421: enough knowledge of Forth systems to know this already).
 4422: 
 4423: @node Comments, Boolean Flags, Case insensitivity, Words
 4424: @section Comments
 4425: @cindex comments
 4426: 
 4427: Forth supports two styles of comment; the traditional @i{in-line} comment,
 4428: @code{(} and its modern cousin, the @i{comment to end of line}; @code{\}.
 4429: 
 4430: 
 4431: doc-(
 4432: doc-\
 4433: doc-\G
 4434: 
 4435: 
 4436: @node Boolean Flags, Arithmetic, Comments, Words
 4437: @section Boolean Flags
 4438: @cindex Boolean flags
 4439: 
 4440: A Boolean flag is cell-sized. A cell with all bits clear represents the
 4441: flag @code{false} and a flag with all bits set represents the flag
 4442: @code{true}. Words that check a flag (for example, @code{IF}) will treat
 4443: a cell that has @i{any} bit set as @code{true}.
 4444: @c on and off to Memory? 
 4445: @c true and false to "Bitwise operations" or "Numeric comparison"?
 4446: 
 4447: doc-true
 4448: doc-false
 4449: doc-on
 4450: doc-off
 4451: 
 4452: 
 4453: @node Arithmetic, Stack Manipulation, Boolean Flags, Words
 4454: @section Arithmetic
 4455: @cindex arithmetic words
 4456: 
 4457: @cindex division with potentially negative operands
 4458: Forth arithmetic is not checked, i.e., you will not hear about integer
 4459: overflow on addition or multiplication, you may hear about division by
 4460: zero if you are lucky. The operator is written after the operands, but
 4461: the operands are still in the original order. I.e., the infix @code{2-1}
 4462: corresponds to @code{2 1 -}. Forth offers a variety of division
 4463: operators. If you perform division with potentially negative operands,
 4464: you do not want to use @code{/} or @code{/mod} with its undefined
 4465: behaviour, but rather @code{fm/mod} or @code{sm/mod} (probably the
 4466: former, @pxref{Mixed precision}).
 4467: @comment TODO discuss the different division forms and the std approach
 4468: 
 4469: @menu
 4470: * Single precision::            
 4471: * Double precision::            Double-cell integer arithmetic
 4472: * Bitwise operations::          
 4473: * Numeric comparison::          
 4474: * Mixed precision::             Operations with single and double-cell integers
 4475: * Floating Point::              
 4476: @end menu
 4477: 
 4478: @node Single precision, Double precision, Arithmetic, Arithmetic
 4479: @subsection Single precision
 4480: @cindex single precision arithmetic words
 4481: 
 4482: @c !! cell undefined
 4483: 
 4484: By default, numbers in Forth are single-precision integers that are one
 4485: cell in size. They can be signed or unsigned, depending upon how you
 4486: treat them. For the rules used by the text interpreter for recognising
 4487: single-precision integers see @ref{Number Conversion}.
 4488: 
 4489: These words are all defined for signed operands, but some of them also
 4490: work for unsigned numbers: @code{+}, @code{1+}, @code{-}, @code{1-},
 4491: @code{*}.
 4492: 
 4493: doc-+
 4494: doc-1+
 4495: doc-under+
 4496: doc--
 4497: doc-1-
 4498: doc-*
 4499: doc-/
 4500: doc-mod
 4501: doc-/mod
 4502: doc-negate
 4503: doc-abs
 4504: doc-min
 4505: doc-max
 4506: doc-floored
 4507: 
 4508: 
 4509: @node Double precision, Bitwise operations, Single precision, Arithmetic
 4510: @subsection Double precision
 4511: @cindex double precision arithmetic words
 4512: 
 4513: For the rules used by the text interpreter for
 4514: recognising double-precision integers, see @ref{Number Conversion}.
 4515: 
 4516: A double precision number is represented by a cell pair, with the most
 4517: significant cell at the TOS. It is trivial to convert an unsigned single
 4518: to a double: simply push a @code{0} onto the TOS. Since numbers are
 4519: represented by Gforth using 2's complement arithmetic, converting a
 4520: signed single to a (signed) double requires sign-extension across the
 4521: most significant cell. This can be achieved using @code{s>d}. The moral
 4522: of the story is that you cannot convert a number without knowing whether
 4523: it represents an unsigned or a signed number.
 4524: 
 4525: These words are all defined for signed operands, but some of them also
 4526: work for unsigned numbers: @code{d+}, @code{d-}.
 4527: 
 4528: doc-s>d
 4529: doc-d>s
 4530: doc-d+
 4531: doc-d-
 4532: doc-dnegate
 4533: doc-dabs
 4534: doc-dmin
 4535: doc-dmax
 4536: 
 4537: 
 4538: @node Bitwise operations, Numeric comparison, Double precision, Arithmetic
 4539: @subsection Bitwise operations
 4540: @cindex bitwise operation words
 4541: 
 4542: 
 4543: doc-and
 4544: doc-or
 4545: doc-xor
 4546: doc-invert
 4547: doc-lshift
 4548: doc-rshift
 4549: doc-2*
 4550: doc-d2*
 4551: doc-2/
 4552: doc-d2/
 4553: 
 4554: 
 4555: @node Numeric comparison, Mixed precision, Bitwise operations, Arithmetic
 4556: @subsection Numeric comparison
 4557: @cindex numeric comparison words
 4558: 
 4559: Note that the words that compare for equality (@code{= <> 0= 0<> d= d<>
 4560: d0= d0<>}) work for for both signed and unsigned numbers.
 4561: 
 4562: doc-<
 4563: doc-<=
 4564: doc-<>
 4565: doc-=
 4566: doc->
 4567: doc->=
 4568: 
 4569: doc-0<
 4570: doc-0<=
 4571: doc-0<>
 4572: doc-0=
 4573: doc-0>
 4574: doc-0>=
 4575: 
 4576: doc-u<
 4577: doc-u<=
 4578: @c u<> and u= exist but are the same as <> and =
 4579: @c doc-u<>
 4580: @c doc-u=
 4581: doc-u>
 4582: doc-u>=
 4583: 
 4584: doc-within
 4585: 
 4586: doc-d<
 4587: doc-d<=
 4588: doc-d<>
 4589: doc-d=
 4590: doc-d>
 4591: doc-d>=
 4592: 
 4593: doc-d0<
 4594: doc-d0<=
 4595: doc-d0<>
 4596: doc-d0=
 4597: doc-d0>
 4598: doc-d0>=
 4599: 
 4600: doc-du<
 4601: doc-du<=
 4602: @c du<> and du= exist but are the same as d<> and d=
 4603: @c doc-du<>
 4604: @c doc-du=
 4605: doc-du>
 4606: doc-du>=
 4607: 
 4608: 
 4609: @node Mixed precision, Floating Point, Numeric comparison, Arithmetic
 4610: @subsection Mixed precision
 4611: @cindex mixed precision arithmetic words
 4612: 
 4613: 
 4614: doc-m+
 4615: doc-*/
 4616: doc-*/mod
 4617: doc-m*
 4618: doc-um*
 4619: doc-m*/
 4620: doc-um/mod
 4621: doc-fm/mod
 4622: doc-sm/rem
 4623: 
 4624: 
 4625: @node Floating Point,  , Mixed precision, Arithmetic
 4626: @subsection Floating Point
 4627: @cindex floating point arithmetic words
 4628: 
 4629: For the rules used by the text interpreter for
 4630: recognising floating-point numbers see @ref{Number Conversion}.
 4631: 
 4632: Gforth has a separate floating point stack, but the documentation uses
 4633: the unified notation.@footnote{It's easy to generate the separate
 4634: notation from that by just separating the floating-point numbers out:
 4635: e.g. @code{( n r1 u r2 -- r3 )} becomes @code{( n u -- ) ( F: r1 r2 --
 4636: r3 )}.}
 4637: 
 4638: @cindex floating-point arithmetic, pitfalls
 4639: Floating point numbers have a number of unpleasant surprises for the
 4640: unwary (e.g., floating point addition is not associative) and even a few
 4641: for the wary. You should not use them unless you know what you are doing
 4642: or you don't care that the results you get are totally bogus. If you
 4643: want to learn about the problems of floating point numbers (and how to
 4644: avoid them), you might start with @cite{David Goldberg,
 4645: @uref{http://www.validgh.com/goldberg/paper.ps,What Every Computer
 4646: Scientist Should Know About Floating-Point Arithmetic}, ACM Computing
 4647: Surveys 23(1):5@minus{}48, March 1991}.
 4648: 
 4649: 
 4650: doc-d>f
 4651: doc-f>d
 4652: doc-f+
 4653: doc-f-
 4654: doc-f*
 4655: doc-f/
 4656: doc-fnegate
 4657: doc-fabs
 4658: doc-fmax
 4659: doc-fmin
 4660: doc-floor
 4661: doc-fround
 4662: doc-f**
 4663: doc-fsqrt
 4664: doc-fexp
 4665: doc-fexpm1
 4666: doc-fln
 4667: doc-flnp1
 4668: doc-flog
 4669: doc-falog
 4670: doc-f2*
 4671: doc-f2/
 4672: doc-1/f
 4673: doc-precision
 4674: doc-set-precision
 4675: 
 4676: @cindex angles in trigonometric operations
 4677: @cindex trigonometric operations
 4678: Angles in floating point operations are given in radians (a full circle
 4679: has 2 pi radians).
 4680: 
 4681: doc-fsin
 4682: doc-fcos
 4683: doc-fsincos
 4684: doc-ftan
 4685: doc-fasin
 4686: doc-facos
 4687: doc-fatan
 4688: doc-fatan2
 4689: doc-fsinh
 4690: doc-fcosh
 4691: doc-ftanh
 4692: doc-fasinh
 4693: doc-facosh
 4694: doc-fatanh
 4695: doc-pi
 4696: 
 4697: @cindex equality of floats
 4698: @cindex floating-point comparisons
 4699: One particular problem with floating-point arithmetic is that comparison
 4700: for equality often fails when you would expect it to succeed.  For this
 4701: reason approximate equality is often preferred (but you still have to
 4702: know what you are doing).  Also note that IEEE NaNs may compare
 4703: differently from what you might expect.  The comparison words are:
 4704: 
 4705: doc-f~rel
 4706: doc-f~abs
 4707: doc-f~
 4708: doc-f=
 4709: doc-f<>
 4710: 
 4711: doc-f<
 4712: doc-f<=
 4713: doc-f>
 4714: doc-f>=
 4715: 
 4716: doc-f0<
 4717: doc-f0<=
 4718: doc-f0<>
 4719: doc-f0=
 4720: doc-f0>
 4721: doc-f0>=
 4722: 
 4723: 
 4724: @node Stack Manipulation, Memory, Arithmetic, Words
 4725: @section Stack Manipulation
 4726: @cindex stack manipulation words
 4727: 
 4728: @cindex floating-point stack in the standard
 4729: Gforth maintains a number of separate stacks:
 4730: 
 4731: @cindex data stack
 4732: @cindex parameter stack
 4733: @itemize @bullet
 4734: @item
 4735: A data stack (also known as the @dfn{parameter stack}) -- for
 4736: characters, cells, addresses, and double cells.
 4737: 
 4738: @cindex floating-point stack
 4739: @item
 4740: A floating point stack -- for holding floating point (FP) numbers.
 4741: 
 4742: @cindex return stack
 4743: @item
 4744: A return stack -- for holding the return addresses of colon
 4745: definitions and other (non-FP) data.
 4746: 
 4747: @cindex locals stack
 4748: @item
 4749: A locals stack -- for holding local variables.
 4750: @end itemize
 4751: 
 4752: @menu
 4753: * Data stack::                  
 4754: * Floating point stack::        
 4755: * Return stack::                
 4756: * Locals stack::                
 4757: * Stack pointer manipulation::  
 4758: @end menu
 4759: 
 4760: @node Data stack, Floating point stack, Stack Manipulation, Stack Manipulation
 4761: @subsection Data stack
 4762: @cindex data stack manipulation words
 4763: @cindex stack manipulations words, data stack
 4764: 
 4765: 
 4766: doc-drop
 4767: doc-nip
 4768: doc-dup
 4769: doc-over
 4770: doc-tuck
 4771: doc-swap
 4772: doc-pick
 4773: doc-rot
 4774: doc--rot
 4775: doc-?dup
 4776: doc-roll
 4777: doc-2drop
 4778: doc-2nip
 4779: doc-2dup
 4780: doc-2over
 4781: doc-2tuck
 4782: doc-2swap
 4783: doc-2rot
 4784: 
 4785: 
 4786: @node Floating point stack, Return stack, Data stack, Stack Manipulation
 4787: @subsection Floating point stack
 4788: @cindex floating-point stack manipulation words
 4789: @cindex stack manipulation words, floating-point stack
 4790: 
 4791: Whilst every sane Forth has a separate floating-point stack, it is not
 4792: strictly required; an ANS Forth system could theoretically keep
 4793: floating-point numbers on the data stack. As an additional difficulty,
 4794: you don't know how many cells a floating-point number takes. It is
 4795: reportedly possible to write words in a way that they work also for a
 4796: unified stack model, but we do not recommend trying it. Instead, just
 4797: say that your program has an environmental dependency on a separate
 4798: floating-point stack.
 4799: 
 4800: doc-floating-stack
 4801: 
 4802: doc-fdrop
 4803: doc-fnip
 4804: doc-fdup
 4805: doc-fover
 4806: doc-ftuck
 4807: doc-fswap
 4808: doc-fpick
 4809: doc-frot
 4810: 
 4811: 
 4812: @node Return stack, Locals stack, Floating point stack, Stack Manipulation
 4813: @subsection Return stack
 4814: @cindex return stack manipulation words
 4815: @cindex stack manipulation words, return stack
 4816: 
 4817: @cindex return stack and locals
 4818: @cindex locals and return stack
 4819: A Forth system is allowed to keep local variables on the
 4820: return stack. This is reasonable, as local variables usually eliminate
 4821: the need to use the return stack explicitly. So, if you want to produce
 4822: a standard compliant program and you are using local variables in a
 4823: word, forget about return stack manipulations in that word (refer to the
 4824: standard document for the exact rules).
 4825: 
 4826: doc->r
 4827: doc-r>
 4828: doc-r@
 4829: doc-rdrop
 4830: doc-2>r
 4831: doc-2r>
 4832: doc-2r@
 4833: doc-2rdrop
 4834: 
 4835: 
 4836: @node Locals stack, Stack pointer manipulation, Return stack, Stack Manipulation
 4837: @subsection Locals stack
 4838: 
 4839: Gforth uses an extra locals stack.  It is described, along with the
 4840: reasons for its existence, in @ref{Locals implementation}.
 4841: 
 4842: @node Stack pointer manipulation,  , Locals stack, Stack Manipulation
 4843: @subsection Stack pointer manipulation
 4844: @cindex stack pointer manipulation words
 4845: 
 4846: @c removed s0 r0 l0 -- they are obsolete aliases for sp0 rp0 lp0
 4847: doc-sp0
 4848: doc-sp@
 4849: doc-sp!
 4850: doc-fp0
 4851: doc-fp@
 4852: doc-fp!
 4853: doc-rp0
 4854: doc-rp@
 4855: doc-rp!
 4856: doc-lp0
 4857: doc-lp@
 4858: doc-lp!
 4859: 
 4860: 
 4861: @node Memory, Control Structures, Stack Manipulation, Words
 4862: @section Memory
 4863: @cindex memory words
 4864: 
 4865: @menu
 4866: * Memory model::                
 4867: * Dictionary allocation::       
 4868: * Heap Allocation::             
 4869: * Memory Access::               
 4870: * Address arithmetic::          
 4871: * Memory Blocks::               
 4872: @end menu
 4873: 
 4874: In addition to the standard Forth memory allocation words, there is also
 4875: a @uref{http://www.complang.tuwien.ac.at/forth/garbage-collection.zip,
 4876: garbage collector}.
 4877: 
 4878: @node Memory model, Dictionary allocation, Memory, Memory
 4879: @subsection ANS Forth and Gforth memory models
 4880: 
 4881: @c The ANS Forth description is a mess (e.g., is the heap part of
 4882: @c the dictionary?), so let's not stick to closely with it.
 4883: 
 4884: ANS Forth considers a Forth system as consisting of several address
 4885: spaces, of which only @dfn{data space} is managed and accessible with
 4886: the memory words.  Memory not necessarily in data space includes the
 4887: stacks, the code (called code space) and the headers (called name
 4888: space). In Gforth everything is in data space, but the code for the
 4889: primitives is usually read-only.
 4890: 
 4891: Data space is divided into a number of areas: The (data space portion of
 4892: the) dictionary@footnote{Sometimes, the term @dfn{dictionary} is used to
 4893: refer to the search data structure embodied in word lists and headers,
 4894: because it is used for looking up names, just as you would in a
 4895: conventional dictionary.}, the heap, and a number of system-allocated
 4896: buffers.
 4897: 
 4898: @cindex address arithmetic restrictions, ANS vs. Gforth
 4899: @cindex contiguous regions, ANS vs. Gforth
 4900: In ANS Forth data space is also divided into contiguous regions.  You
 4901: can only use address arithmetic within a contiguous region, not between
 4902: them.  Usually each allocation gives you one contiguous region, but the
 4903: dictionary allocation words have additional rules (@pxref{Dictionary
 4904: allocation}).
 4905: 
 4906: Gforth provides one big address space, and address arithmetic can be
 4907: performed between any addresses. However, in the dictionary headers or
 4908: code are interleaved with data, so almost the only contiguous data space
 4909: regions there are those described by ANS Forth as contiguous; but you
 4910: can be sure that the dictionary is allocated towards increasing
 4911: addresses even between contiguous regions.  The memory order of
 4912: allocations in the heap is platform-dependent (and possibly different
 4913: from one run to the next).
 4914: 
 4915: 
 4916: @node Dictionary allocation, Heap Allocation, Memory model, Memory
 4917: @subsection Dictionary allocation
 4918: @cindex reserving data space
 4919: @cindex data space - reserving some
 4920: 
 4921: Dictionary allocation is a stack-oriented allocation scheme, i.e., if
 4922: you want to deallocate X, you also deallocate everything
 4923: allocated after X.
 4924: 
 4925: @cindex contiguous regions in dictionary allocation
 4926: The allocations using the words below are contiguous and grow the region
 4927: towards increasing addresses.  Other words that allocate dictionary
 4928: memory of any kind (i.e., defining words including @code{:noname}) end
 4929: the contiguous region and start a new one.
 4930: 
 4931: In ANS Forth only @code{create}d words are guaranteed to produce an
 4932: address that is the start of the following contiguous region.  In
 4933: particular, the cell allocated by @code{variable} is not guaranteed to
 4934: be contiguous with following @code{allot}ed memory.
 4935: 
 4936: You can deallocate memory by using @code{allot} with a negative argument
 4937: (with some restrictions, see @code{allot}). For larger deallocations use
 4938: @code{marker}.
 4939: 
 4940: 
 4941: doc-here
 4942: doc-unused
 4943: doc-allot
 4944: doc-c,
 4945: doc-f,
 4946: doc-,
 4947: doc-2,
 4948: 
 4949: Memory accesses have to be aligned (@pxref{Address arithmetic}). So of
 4950: course you should allocate memory in an aligned way, too. I.e., before
 4951: allocating allocating a cell, @code{here} must be cell-aligned, etc.
 4952: The words below align @code{here} if it is not already.  Basically it is
 4953: only already aligned for a type, if the last allocation was a multiple
 4954: of the size of this type and if @code{here} was aligned for this type
 4955: before.
 4956: 
 4957: After freshly @code{create}ing a word, @code{here} is @code{align}ed in
 4958: ANS Forth (@code{maxalign}ed in Gforth).
 4959: 
 4960: doc-align
 4961: doc-falign
 4962: doc-sfalign
 4963: doc-dfalign
 4964: doc-maxalign
 4965: doc-cfalign
 4966: 
 4967: 
 4968: @node Heap Allocation, Memory Access, Dictionary allocation, Memory
 4969: @subsection Heap allocation
 4970: @cindex heap allocation
 4971: @cindex dynamic allocation of memory
 4972: @cindex memory-allocation word set
 4973: 
 4974: @cindex contiguous regions and heap allocation
 4975: Heap allocation supports deallocation of allocated memory in any
 4976: order. Dictionary allocation is not affected by it (i.e., it does not
 4977: end a contiguous region). In Gforth, these words are implemented using
 4978: the standard C library calls malloc(), free() and resize().
 4979: 
 4980: The memory region produced by one invocation of @code{allocate} or
 4981: @code{resize} is internally contiguous.  There is no contiguity between
 4982: such a region and any other region (including others allocated from the
 4983: heap).
 4984: 
 4985: doc-allocate
 4986: doc-free
 4987: doc-resize
 4988: 
 4989: 
 4990: @node Memory Access, Address arithmetic, Heap Allocation, Memory
 4991: @subsection Memory Access
 4992: @cindex memory access words
 4993: 
 4994: doc-@
 4995: doc-!
 4996: doc-+!
 4997: doc-c@
 4998: doc-c!
 4999: doc-2@
 5000: doc-2!
 5001: doc-f@
 5002: doc-f!
 5003: doc-sf@
 5004: doc-sf!
 5005: doc-df@
 5006: doc-df!
 5007: doc-sw@
 5008: doc-uw@
 5009: doc-w!
 5010: doc-sl@
 5011: doc-ul@
 5012: doc-l!
 5013: 
 5014: @node Address arithmetic, Memory Blocks, Memory Access, Memory
 5015: @subsection Address arithmetic
 5016: @cindex address arithmetic words
 5017: 
 5018: Address arithmetic is the foundation on which you can build data
 5019: structures like arrays, records (@pxref{Structures}) and objects
 5020: (@pxref{Object-oriented Forth}).
 5021: 
 5022: @cindex address unit
 5023: @cindex au (address unit)
 5024: ANS Forth does not specify the sizes of the data types. Instead, it
 5025: offers a number of words for computing sizes and doing address
 5026: arithmetic. Address arithmetic is performed in terms of address units
 5027: (aus); on most systems the address unit is one byte. Note that a
 5028: character may have more than one au, so @code{chars} is no noop (on
 5029: platforms where it is a noop, it compiles to nothing).
 5030: 
 5031: The basic address arithmetic words are @code{+} and @code{-}.  E.g., if
 5032: you have the address of a cell, perform @code{1 cells +}, and you will
 5033: have the address of the next cell.
 5034: 
 5035: @cindex contiguous regions and address arithmetic
 5036: In ANS Forth you can perform address arithmetic only within a contiguous
 5037: region, i.e., if you have an address into one region, you can only add
 5038: and subtract such that the result is still within the region; you can
 5039: only subtract or compare addresses from within the same contiguous
 5040: region.  Reasons: several contiguous regions can be arranged in memory
 5041: in any way; on segmented systems addresses may have unusual
 5042: representations, such that address arithmetic only works within a
 5043: region.  Gforth provides a few more guarantees (linear address space,
 5044: dictionary grows upwards), but in general I have found it easy to stay
 5045: within contiguous regions (exception: computing and comparing to the
 5046: address just beyond the end of an array).
 5047: 
 5048: @cindex alignment of addresses for types
 5049: ANS Forth also defines words for aligning addresses for specific
 5050: types. Many computers require that accesses to specific data types
 5051: must only occur at specific addresses; e.g., that cells may only be
 5052: accessed at addresses divisible by 4. Even if a machine allows unaligned
 5053: accesses, it can usually perform aligned accesses faster. 
 5054: 
 5055: For the performance-conscious: alignment operations are usually only
 5056: necessary during the definition of a data structure, not during the
 5057: (more frequent) accesses to it.
 5058: 
 5059: ANS Forth defines no words for character-aligning addresses. This is not
 5060: an oversight, but reflects the fact that addresses that are not
 5061: char-aligned have no use in the standard and therefore will not be
 5062: created.
 5063: 
 5064: @cindex @code{CREATE} and alignment
 5065: ANS Forth guarantees that addresses returned by @code{CREATE}d words
 5066: are cell-aligned; in addition, Gforth guarantees that these addresses
 5067: are aligned for all purposes.
 5068: 
 5069: Note that the ANS Forth word @code{char} has nothing to do with address
 5070: arithmetic.
 5071: 
 5072: 
 5073: doc-chars
 5074: doc-char+
 5075: doc-cells
 5076: doc-cell+
 5077: doc-cell
 5078: doc-aligned
 5079: doc-floats
 5080: doc-float+
 5081: doc-float
 5082: doc-faligned
 5083: doc-sfloats
 5084: doc-sfloat+
 5085: doc-sfaligned
 5086: doc-dfloats
 5087: doc-dfloat+
 5088: doc-dfaligned
 5089: doc-maxaligned
 5090: doc-cfaligned
 5091: doc-address-unit-bits
 5092: doc-/w
 5093: doc-/l
 5094: 
 5095: @node Memory Blocks,  , Address arithmetic, Memory
 5096: @subsection Memory Blocks
 5097: @cindex memory block words
 5098: @cindex character strings - moving and copying
 5099: 
 5100: Memory blocks often represent character strings; For ways of storing
 5101: character strings in memory see @ref{String Formats}.  For other
 5102: string-processing words see @ref{Displaying characters and strings}.
 5103: 
 5104: A few of these words work on address unit blocks.  In that case, you
 5105: usually have to insert @code{CHARS} before the word when working on
 5106: character strings.  Most words work on character blocks, and expect a
 5107: char-aligned address.
 5108: 
 5109: When copying characters between overlapping memory regions, use
 5110: @code{chars move} or choose carefully between @code{cmove} and
 5111: @code{cmove>}.
 5112: 
 5113: doc-move
 5114: doc-erase
 5115: doc-cmove
 5116: doc-cmove>
 5117: doc-fill
 5118: doc-blank
 5119: doc-compare
 5120: doc-str=
 5121: doc-str<
 5122: doc-string-prefix?
 5123: doc-search
 5124: doc--trailing
 5125: doc-/string
 5126: doc-bounds
 5127: doc-pad
 5128: 
 5129: @comment TODO examples
 5130: 
 5131: 
 5132: @node Control Structures, Defining Words, Memory, Words
 5133: @section Control Structures
 5134: @cindex control structures
 5135: 
 5136: Control structures in Forth cannot be used interpretively, only in a
 5137: colon definition@footnote{To be precise, they have no interpretation
 5138: semantics (@pxref{Interpretation and Compilation Semantics}).}. We do
 5139: not like this limitation, but have not seen a satisfying way around it
 5140: yet, although many schemes have been proposed.
 5141: 
 5142: @menu
 5143: * Selection::                   IF ... ELSE ... ENDIF
 5144: * Simple Loops::                BEGIN ...
 5145: * Counted Loops::               DO
 5146: * Arbitrary control structures::  
 5147: * Calls and returns::           
 5148: * Exception Handling::          
 5149: @end menu
 5150: 
 5151: @node Selection, Simple Loops, Control Structures, Control Structures
 5152: @subsection Selection
 5153: @cindex selection control structures
 5154: @cindex control structures for selection
 5155: 
 5156: @cindex @code{IF} control structure
 5157: @example
 5158: @i{flag}
 5159: IF
 5160:   @i{code}
 5161: ENDIF
 5162: @end example
 5163: @noindent
 5164: 
 5165: If @i{flag} is non-zero (as far as @code{IF} etc. are concerned, a cell
 5166: with any bit set represents truth) @i{code} is executed.
 5167: 
 5168: @example
 5169: @i{flag}
 5170: IF
 5171:   @i{code1}
 5172: ELSE
 5173:   @i{code2}
 5174: ENDIF
 5175: @end example
 5176: 
 5177: If @var{flag} is true, @i{code1} is executed, otherwise @i{code2} is
 5178: executed.
 5179: 
 5180: You can use @code{THEN} instead of @code{ENDIF}. Indeed, @code{THEN} is
 5181: standard, and @code{ENDIF} is not, although it is quite popular. We
 5182: recommend using @code{ENDIF}, because it is less confusing for people
 5183: who also know other languages (and is not prone to reinforcing negative
 5184: prejudices against Forth in these people). Adding @code{ENDIF} to a
 5185: system that only supplies @code{THEN} is simple:
 5186: @example
 5187: : ENDIF   POSTPONE then ; immediate
 5188: @end example
 5189: 
 5190: [According to @cite{Webster's New Encyclopedic Dictionary}, @dfn{then
 5191: (adv.)}  has the following meanings:
 5192: @quotation
 5193: ... 2b: following next after in order ... 3d: as a necessary consequence
 5194: (if you were there, then you saw them).
 5195: @end quotation
 5196: Forth's @code{THEN} has the meaning 2b, whereas @code{THEN} in Pascal
 5197: and many other programming languages has the meaning 3d.]
 5198: 
 5199: Gforth also provides the words @code{?DUP-IF} and @code{?DUP-0=-IF}, so
 5200: you can avoid using @code{?dup}. Using these alternatives is also more
 5201: efficient than using @code{?dup}. Definitions in ANS Forth
 5202: for @code{ENDIF}, @code{?DUP-IF} and @code{?DUP-0=-IF} are provided in
 5203: @file{compat/control.fs}.
 5204: 
 5205: @cindex @code{CASE} control structure
 5206: @example
 5207: @i{n}
 5208: CASE
 5209:   @i{n1} OF @i{code1} ENDOF
 5210:   @i{n2} OF @i{code2} ENDOF
 5211:   @dots{}
 5212:   ( n ) @i{default-code} ( n )
 5213: ENDCASE ( )
 5214: @end example
 5215: 
 5216: Executes the first @i{codei}, where the @i{ni} is equal to @i{n}.  If
 5217: no @i{ni} matches, the optional @i{default-code} is executed. The
 5218: optional default case can be added by simply writing the code after
 5219: the last @code{ENDOF}. It may use @i{n}, which is on top of the stack,
 5220: but must not consume it.  The value @i{n} is consumed by this
 5221: construction (either by a OF that matches, or by the ENDCASE, if no OF
 5222: matches).
 5223: 
 5224: @progstyle
 5225: To keep the code understandable, you should ensure that you change the
 5226: stack in the same way (wrt. number and types of stack items consumed
 5227: and pushed) on all paths through a selection construct.
 5228: 
 5229: @node Simple Loops, Counted Loops, Selection, Control Structures
 5230: @subsection Simple Loops
 5231: @cindex simple loops
 5232: @cindex loops without count 
 5233: 
 5234: @cindex @code{WHILE} loop
 5235: @example
 5236: BEGIN
 5237:   @i{code1}
 5238:   @i{flag}
 5239: WHILE
 5240:   @i{code2}
 5241: REPEAT
 5242: @end example
 5243: 
 5244: @i{code1} is executed and @i{flag} is computed. If it is true,
 5245: @i{code2} is executed and the loop is restarted; If @i{flag} is
 5246: false, execution continues after the @code{REPEAT}.
 5247: 
 5248: @cindex @code{UNTIL} loop
 5249: @example
 5250: BEGIN
 5251:   @i{code}
 5252:   @i{flag}
 5253: UNTIL
 5254: @end example
 5255: 
 5256: @i{code} is executed. The loop is restarted if @code{flag} is false.
 5257: 
 5258: @progstyle
 5259: To keep the code understandable, a complete iteration of the loop should
 5260: not change the number and types of the items on the stacks.
 5261: 
 5262: @cindex endless loop
 5263: @cindex loops, endless
 5264: @example
 5265: BEGIN
 5266:   @i{code}
 5267: AGAIN
 5268: @end example
 5269: 
 5270: This is an endless loop.
 5271: 
 5272: @node Counted Loops, Arbitrary control structures, Simple Loops, Control Structures
 5273: @subsection Counted Loops
 5274: @cindex counted loops
 5275: @cindex loops, counted
 5276: @cindex @code{DO} loops
 5277: 
 5278: The basic counted loop is:
 5279: @example
 5280: @i{limit} @i{start}
 5281: ?DO
 5282:   @i{body}
 5283: LOOP
 5284: @end example
 5285: 
 5286: This performs one iteration for every integer, starting from @i{start}
 5287: and up to, but excluding @i{limit}. The counter, or @i{index}, can be
 5288: accessed with @code{i}. For example, the loop:
 5289: @example
 5290: 10 0 ?DO
 5291:   i .
 5292: LOOP
 5293: @end example
 5294: @noindent
 5295: prints @code{0 1 2 3 4 5 6 7 8 9}
 5296: 
 5297: The index of the innermost loop can be accessed with @code{i}, the index
 5298: of the next loop with @code{j}, and the index of the third loop with
 5299: @code{k}.
 5300: 
 5301: 
 5302: doc-i
 5303: doc-j
 5304: doc-k
 5305: 
 5306: 
 5307: The loop control data are kept on the return stack, so there are some
 5308: restrictions on mixing return stack accesses and counted loop words. In
 5309: particuler, if you put values on the return stack outside the loop, you
 5310: cannot read them inside the loop@footnote{well, not in a way that is
 5311: portable.}. If you put values on the return stack within a loop, you
 5312: have to remove them before the end of the loop and before accessing the
 5313: index of the loop.
 5314: 
 5315: There are several variations on the counted loop:
 5316: 
 5317: @itemize @bullet
 5318: @item
 5319: @code{LEAVE} leaves the innermost counted loop immediately; execution
 5320: continues after the associated @code{LOOP} or @code{NEXT}. For example:
 5321: 
 5322: @example
 5323: 10 0 ?DO  i DUP . 3 = IF LEAVE THEN LOOP
 5324: @end example
 5325: prints @code{0 1 2 3}
 5326: 
 5327: 
 5328: @item
 5329: @code{UNLOOP} prepares for an abnormal loop exit, e.g., via
 5330: @code{EXIT}. @code{UNLOOP} removes the loop control parameters from the
 5331: return stack so @code{EXIT} can get to its return address. For example:
 5332: 
 5333: @example
 5334: : demo 10 0 ?DO i DUP . 3 = IF UNLOOP EXIT THEN LOOP ." Done" ;
 5335: @end example
 5336: prints @code{0 1 2 3}
 5337: 
 5338: 
 5339: @item
 5340: If @i{start} is greater than @i{limit}, a @code{?DO} loop is entered
 5341: (and @code{LOOP} iterates until they become equal by wrap-around
 5342: arithmetic). This behaviour is usually not what you want. Therefore,
 5343: Gforth offers @code{+DO} and @code{U+DO} (as replacements for
 5344: @code{?DO}), which do not enter the loop if @i{start} is greater than
 5345: @i{limit}; @code{+DO} is for signed loop parameters, @code{U+DO} for
 5346: unsigned loop parameters.
 5347: 
 5348: @item
 5349: @code{?DO} can be replaced by @code{DO}. @code{DO} always enters
 5350: the loop, independent of the loop parameters. Do not use @code{DO}, even
 5351: if you know that the loop is entered in any case. Such knowledge tends
 5352: to become invalid during maintenance of a program, and then the
 5353: @code{DO} will make trouble.
 5354: 
 5355: @item
 5356: @code{LOOP} can be replaced with @code{@i{n} +LOOP}; this updates the
 5357: index by @i{n} instead of by 1. The loop is terminated when the border
 5358: between @i{limit-1} and @i{limit} is crossed. E.g.:
 5359: 
 5360: @example
 5361: 4 0 +DO  i .  2 +LOOP
 5362: @end example
 5363: @noindent
 5364: prints @code{0 2}
 5365: 
 5366: @example
 5367: 4 1 +DO  i .  2 +LOOP
 5368: @end example
 5369: @noindent
 5370: prints @code{1 3}
 5371: 
 5372: @item
 5373: @cindex negative increment for counted loops
 5374: @cindex counted loops with negative increment
 5375: The behaviour of @code{@i{n} +LOOP} is peculiar when @i{n} is negative:
 5376: 
 5377: @example
 5378: -1 0 ?DO  i .  -1 +LOOP
 5379: @end example
 5380: @noindent
 5381: prints @code{0 -1}
 5382: 
 5383: @example
 5384: 0 0 ?DO  i .  -1 +LOOP
 5385: @end example
 5386: prints nothing.
 5387: 
 5388: Therefore we recommend avoiding @code{@i{n} +LOOP} with negative
 5389: @i{n}. One alternative is @code{@i{u} -LOOP}, which reduces the
 5390: index by @i{u} each iteration. The loop is terminated when the border
 5391: between @i{limit+1} and @i{limit} is crossed. Gforth also provides
 5392: @code{-DO} and @code{U-DO} for down-counting loops. E.g.:
 5393: 
 5394: @example
 5395: -2 0 -DO  i .  1 -LOOP
 5396: @end example
 5397: @noindent
 5398: prints @code{0 -1}
 5399: 
 5400: @example
 5401: -1 0 -DO  i .  1 -LOOP
 5402: @end example
 5403: @noindent
 5404: prints @code{0}
 5405: 
 5406: @example
 5407: 0 0 -DO  i .  1 -LOOP
 5408: @end example
 5409: @noindent
 5410: prints nothing.
 5411: 
 5412: @end itemize
 5413: 
 5414: Unfortunately, @code{+DO}, @code{U+DO}, @code{-DO}, @code{U-DO} and
 5415: @code{-LOOP} are not defined in ANS Forth. However, an implementation
 5416: for these words that uses only standard words is provided in
 5417: @file{compat/loops.fs}.
 5418: 
 5419: 
 5420: @cindex @code{FOR} loops
 5421: Another counted loop is:
 5422: @example
 5423: @i{n}
 5424: FOR
 5425:   @i{body}
 5426: NEXT
 5427: @end example
 5428: This is the preferred loop of native code compiler writers who are too
 5429: lazy to optimize @code{?DO} loops properly. This loop structure is not
 5430: defined in ANS Forth. In Gforth, this loop iterates @i{n+1} times;
 5431: @code{i} produces values starting with @i{n} and ending with 0. Other
 5432: Forth systems may behave differently, even if they support @code{FOR}
 5433: loops. To avoid problems, don't use @code{FOR} loops.
 5434: 
 5435: @node Arbitrary control structures, Calls and returns, Counted Loops, Control Structures
 5436: @subsection Arbitrary control structures
 5437: @cindex control structures, user-defined
 5438: 
 5439: @cindex control-flow stack
 5440: ANS Forth permits and supports using control structures in a non-nested
 5441: way. Information about incomplete control structures is stored on the
 5442: control-flow stack. This stack may be implemented on the Forth data
 5443: stack, and this is what we have done in Gforth.
 5444: 
 5445: @cindex @code{orig}, control-flow stack item
 5446: @cindex @code{dest}, control-flow stack item
 5447: An @i{orig} entry represents an unresolved forward branch, a @i{dest}
 5448: entry represents a backward branch target. A few words are the basis for
 5449: building any control structure possible (except control structures that
 5450: need storage, like calls, coroutines, and backtracking).
 5451: 
 5452: 
 5453: doc-if
 5454: doc-ahead
 5455: doc-then
 5456: doc-begin
 5457: doc-until
 5458: doc-again
 5459: doc-cs-pick
 5460: doc-cs-roll
 5461: 
 5462: 
 5463: The Standard words @code{CS-PICK} and @code{CS-ROLL} allow you to
 5464: manipulate the control-flow stack in a portable way. Without them, you
 5465: would need to know how many stack items are occupied by a control-flow
 5466: entry (many systems use one cell. In Gforth they currently take three,
 5467: but this may change in the future).
 5468: 
 5469: Some standard control structure words are built from these words:
 5470: 
 5471: 
 5472: doc-else
 5473: doc-while
 5474: doc-repeat
 5475: 
 5476: 
 5477: @noindent
 5478: Gforth adds some more control-structure words:
 5479: 
 5480: 
 5481: doc-endif
 5482: doc-?dup-if
 5483: doc-?dup-0=-if
 5484: 
 5485: 
 5486: @noindent
 5487: Counted loop words constitute a separate group of words:
 5488: 
 5489: 
 5490: doc-?do
 5491: doc-+do
 5492: doc-u+do
 5493: doc--do
 5494: doc-u-do
 5495: doc-do
 5496: doc-for
 5497: doc-loop
 5498: doc-+loop
 5499: doc--loop
 5500: doc-next
 5501: doc-leave
 5502: doc-?leave
 5503: doc-unloop
 5504: doc-done
 5505: 
 5506: 
 5507: The standard does not allow using @code{CS-PICK} and @code{CS-ROLL} on
 5508: @i{do-sys}. Gforth allows it, but it's your job to ensure that for
 5509: every @code{?DO} etc. there is exactly one @code{UNLOOP} on any path
 5510: through the definition (@code{LOOP} etc. compile an @code{UNLOOP} on the
 5511: fall-through path). Also, you have to ensure that all @code{LEAVE}s are
 5512: resolved (by using one of the loop-ending words or @code{DONE}).
 5513: 
 5514: @noindent
 5515: Another group of control structure words are:
 5516: 
 5517: 
 5518: doc-case
 5519: doc-endcase
 5520: doc-of
 5521: doc-endof
 5522: 
 5523: 
 5524: @i{case-sys} and @i{of-sys} cannot be processed using @code{CS-PICK} and
 5525: @code{CS-ROLL}.
 5526: 
 5527: @subsubsection Programming Style
 5528: @cindex control structures programming style
 5529: @cindex programming style, arbitrary control structures
 5530: 
 5531: In order to ensure readability we recommend that you do not create
 5532: arbitrary control structures directly, but define new control structure
 5533: words for the control structure you want and use these words in your
 5534: program. For example, instead of writing:
 5535: 
 5536: @example
 5537: BEGIN
 5538:   ...
 5539: IF [ 1 CS-ROLL ]
 5540:   ...
 5541: AGAIN THEN
 5542: @end example
 5543: 
 5544: @noindent
 5545: we recommend defining control structure words, e.g.,
 5546: 
 5547: @example
 5548: : WHILE ( DEST -- ORIG DEST )
 5549:  POSTPONE IF
 5550:  1 CS-ROLL ; immediate
 5551: 
 5552: : REPEAT ( orig dest -- )
 5553:  POSTPONE AGAIN
 5554:  POSTPONE THEN ; immediate
 5555: @end example
 5556: 
 5557: @noindent
 5558: and then using these to create the control structure:
 5559: 
 5560: @example
 5561: BEGIN
 5562:   ...
 5563: WHILE
 5564:   ...
 5565: REPEAT
 5566: @end example
 5567: 
 5568: That's much easier to read, isn't it? Of course, @code{REPEAT} and
 5569: @code{WHILE} are predefined, so in this example it would not be
 5570: necessary to define them.
 5571: 
 5572: @node Calls and returns, Exception Handling, Arbitrary control structures, Control Structures
 5573: @subsection Calls and returns
 5574: @cindex calling a definition
 5575: @cindex returning from a definition
 5576: 
 5577: @cindex recursive definitions
 5578: A definition can be called simply be writing the name of the definition
 5579: to be called. Normally a definition is invisible during its own
 5580: definition. If you want to write a directly recursive definition, you
 5581: can use @code{recursive} to make the current definition visible, or
 5582: @code{recurse} to call the current definition directly.
 5583: 
 5584: 
 5585: doc-recursive
 5586: doc-recurse
 5587: 
 5588: 
 5589: @comment TODO add example of the two recursion methods
 5590: @quotation
 5591: @progstyle
 5592: I prefer using @code{recursive} to @code{recurse}, because calling the
 5593: definition by name is more descriptive (if the name is well-chosen) than
 5594: the somewhat cryptic @code{recurse}.  E.g., in a quicksort
 5595: implementation, it is much better to read (and think) ``now sort the
 5596: partitions'' than to read ``now do a recursive call''.
 5597: @end quotation
 5598: 
 5599: For mutual recursion, use @code{Defer}red words, like this:
 5600: 
 5601: @example
 5602: Defer foo
 5603: 
 5604: : bar ( ... -- ... )
 5605:  ... foo ... ;
 5606: 
 5607: :noname ( ... -- ... )
 5608:  ... bar ... ;
 5609: IS foo
 5610: @end example
 5611: 
 5612: Deferred words are discussed in more detail in @ref{Deferred words}.
 5613: 
 5614: The current definition returns control to the calling definition when
 5615: the end of the definition is reached or @code{EXIT} is encountered.
 5616: 
 5617: doc-exit
 5618: doc-;s
 5619: 
 5620: 
 5621: @node Exception Handling,  , Calls and returns, Control Structures
 5622: @subsection Exception Handling
 5623: @cindex exceptions
 5624: 
 5625: @c quit is a very bad idea for error handling, 
 5626: @c because it does not translate into a THROW
 5627: @c it also does not belong into this chapter
 5628: 
 5629: If a word detects an error condition that it cannot handle, it can
 5630: @code{throw} an exception.  In the simplest case, this will terminate
 5631: your program, and report an appropriate error.
 5632: 
 5633: doc-throw
 5634: 
 5635: @code{Throw} consumes a cell-sized error number on the stack. There are
 5636: some predefined error numbers in ANS Forth (see @file{errors.fs}).  In
 5637: Gforth (and most other systems) you can use the iors produced by various
 5638: words as error numbers (e.g., a typical use of @code{allocate} is
 5639: @code{allocate throw}).  Gforth also provides the word @code{exception}
 5640: to define your own error numbers (with decent error reporting); an ANS
 5641: Forth version of this word (but without the error messages) is available
 5642: in @code{compat/except.fs}.  And finally, you can use your own error
 5643: numbers (anything outside the range -4095..0), but won't get nice error
 5644: messages, only numbers.  For example, try:
 5645: 
 5646: @example
 5647: -10 throw                    \ ANS defined
 5648: -267 throw                   \ system defined
 5649: s" my error" exception throw \ user defined
 5650: 7 throw                      \ arbitrary number
 5651: @end example
 5652: 
 5653: doc---exception-exception
 5654: 
 5655: A common idiom to @code{THROW} a specific error if a flag is true is
 5656: this:
 5657: 
 5658: @example
 5659: @code{( flag ) 0<> @i{errno} and throw}
 5660: @end example
 5661: 
 5662: Your program can provide exception handlers to catch exceptions.  An
 5663: exception handler can be used to correct the problem, or to clean up
 5664: some data structures and just throw the exception to the next exception
 5665: handler.  Note that @code{throw} jumps to the dynamically innermost
 5666: exception handler.  The system's exception handler is outermost, and just
 5667: prints an error and restarts command-line interpretation (or, in batch
 5668: mode (i.e., while processing the shell command line), leaves Gforth).
 5669: 
 5670: The ANS Forth way to catch exceptions is @code{catch}:
 5671: 
 5672: doc-catch
 5673: 
 5674: The most common use of exception handlers is to clean up the state when
 5675: an error happens.  E.g.,
 5676: 
 5677: @example
 5678: base @ >r hex \ actually the hex should be inside foo, or we h
 5679: ['] foo catch ( nerror|0 )
 5680: r> base !
 5681: ( nerror|0 ) throw \ pass it on
 5682: @end example
 5683: 
 5684: A use of @code{catch} for handling the error @code{myerror} might look
 5685: like this:
 5686: 
 5687: @example
 5688: ['] foo catch
 5689: CASE
 5690:   myerror OF ... ( do something about it ) ENDOF
 5691:   dup throw \ default: pass other errors on, do nothing on non-errors
 5692: ENDCASE
 5693: @end example
 5694: 
 5695: Having to wrap the code into a separate word is often cumbersome,
 5696: therefore Gforth provides an alternative syntax:
 5697: 
 5698: @example
 5699: TRY
 5700:   @i{code1}
 5701: RECOVER     \ optional
 5702:   @i{code2} \ optional
 5703: ENDTRY
 5704: @end example
 5705: 
 5706: This performs @i{Code1}.  If @i{code1} completes normally, execution
 5707: continues after the @code{endtry}.  If @i{Code1} throws, the stacks are
 5708: reset to the state during @code{try}, the throw value is pushed on the
 5709: data stack, and execution constinues at @i{code2}, and finally falls
 5710: through the @code{endtry} into the following code.
 5711: 
 5712: doc-try
 5713: doc-recover
 5714: doc-endtry
 5715: 
 5716: The cleanup example from above in this syntax:
 5717: 
 5718: @example
 5719: base @ >r TRY
 5720:   hex foo \ now the hex is placed correctly
 5721:   0       \ value for throw
 5722: RECOVER ENDTRY
 5723: r> base ! throw
 5724: @end example
 5725: 
 5726: And here's the error handling example:
 5727: 
 5728: @example
 5729: TRY
 5730:   foo
 5731: RECOVER
 5732:   CASE
 5733:     myerror OF ... ( do something about it ) ENDOF
 5734:     throw \ pass other errors on
 5735:   ENDCASE
 5736: ENDTRY
 5737: @end example
 5738: 
 5739: @progstyle
 5740: As usual, you should ensure that the stack depth is statically known at
 5741: the end: either after the @code{throw} for passing on errors, or after
 5742: the @code{ENDTRY} (or, if you use @code{catch}, after the end of the
 5743: selection construct for handling the error).
 5744: 
 5745: There are two alternatives to @code{throw}: @code{Abort"} is conditional
 5746: and you can provide an error message.  @code{Abort} just produces an
 5747: ``Aborted'' error.
 5748: 
 5749: The problem with these words is that exception handlers cannot
 5750: differentiate between different @code{abort"}s; they just look like
 5751: @code{-2 throw} to them (the error message cannot be accessed by
 5752: standard programs).  Similar @code{abort} looks like @code{-1 throw} to
 5753: exception handlers.
 5754: 
 5755: doc-abort"
 5756: doc-abort
 5757: 
 5758: 
 5759: 
 5760: @c -------------------------------------------------------------
 5761: @node Defining Words, Interpretation and Compilation Semantics, Control Structures, Words
 5762: @section Defining Words
 5763: @cindex defining words
 5764: 
 5765: Defining words are used to extend Forth by creating new entries in the dictionary.
 5766: 
 5767: @menu
 5768: * CREATE::                      
 5769: * Variables::                   Variables and user variables
 5770: * Constants::                   
 5771: * Values::                      Initialised variables
 5772: * Colon Definitions::           
 5773: * Anonymous Definitions::       Definitions without names
 5774: * Supplying names::             Passing definition names as strings
 5775: * User-defined Defining Words::  
 5776: * Deferred words::              Allow forward references
 5777: * Aliases::                     
 5778: @end menu
 5779: 
 5780: @node CREATE, Variables, Defining Words, Defining Words
 5781: @subsection @code{CREATE}
 5782: @cindex simple defining words
 5783: @cindex defining words, simple
 5784: 
 5785: Defining words are used to create new entries in the dictionary. The
 5786: simplest defining word is @code{CREATE}. @code{CREATE} is used like
 5787: this:
 5788: 
 5789: @example
 5790: CREATE new-word1
 5791: @end example
 5792: 
 5793: @code{CREATE} is a parsing word, i.e., it takes an argument from the
 5794: input stream (@code{new-word1} in our example).  It generates a
 5795: dictionary entry for @code{new-word1}. When @code{new-word1} is
 5796: executed, all that it does is leave an address on the stack. The address
 5797: represents the value of the data space pointer (@code{HERE}) at the time
 5798: that @code{new-word1} was defined. Therefore, @code{CREATE} is a way of
 5799: associating a name with the address of a region of memory.
 5800: 
 5801: doc-create
 5802: 
 5803: Note that in ANS Forth guarantees only for @code{create} that its body
 5804: is in dictionary data space (i.e., where @code{here}, @code{allot}
 5805: etc. work, @pxref{Dictionary allocation}).  Also, in ANS Forth only
 5806: @code{create}d words can be modified with @code{does>}
 5807: (@pxref{User-defined Defining Words}).  And in ANS Forth @code{>body}
 5808: can only be applied to @code{create}d words.
 5809: 
 5810: By extending this example to reserve some memory in data space, we end
 5811: up with something like a @i{variable}. Here are two different ways to do
 5812: it:
 5813: 
 5814: @example
 5815: CREATE new-word2 1 cells allot  \ reserve 1 cell - initial value undefined
 5816: CREATE new-word3 4 ,            \ reserve 1 cell and initialise it (to 4)
 5817: @end example
 5818: 
 5819: The variable can be examined and modified using @code{@@} (``fetch'') and
 5820: @code{!} (``store'') like this:
 5821: 
 5822: @example
 5823: new-word2 @@ .      \ get address, fetch from it and display
 5824: 1234 new-word2 !   \ new value, get address, store to it
 5825: @end example
 5826: 
 5827: @cindex arrays
 5828: A similar mechanism can be used to create arrays. For example, an
 5829: 80-character text input buffer:
 5830: 
 5831: @example
 5832: CREATE text-buf 80 chars allot
 5833: 
 5834: text-buf 0 chars c@@ \ the 1st character (offset 0)
 5835: text-buf 3 chars c@@ \ the 4th character (offset 3)
 5836: @end example
 5837: 
 5838: You can build arbitrarily complex data structures by allocating
 5839: appropriate areas of memory. For further discussions of this, and to
 5840: learn about some Gforth tools that make it easier,
 5841: @xref{Structures}.
 5842: 
 5843: 
 5844: @node Variables, Constants, CREATE, Defining Words
 5845: @subsection Variables
 5846: @cindex variables
 5847: 
 5848: The previous section showed how a sequence of commands could be used to
 5849: generate a variable.  As a final refinement, the whole code sequence can
 5850: be wrapped up in a defining word (pre-empting the subject of the next
 5851: section), making it easier to create new variables:
 5852: 
 5853: @example
 5854: : myvariableX ( "name" -- a-addr ) CREATE 1 cells allot ;
 5855: : myvariable0 ( "name" -- a-addr ) CREATE 0 , ;
 5856: 
 5857: myvariableX foo \ variable foo starts off with an unknown value
 5858: myvariable0 joe \ whilst joe is initialised to 0
 5859: 
 5860: 45 3 * foo !   \ set foo to 135
 5861: 1234 joe !     \ set joe to 1234
 5862: 3 joe +!       \ increment joe by 3.. to 1237
 5863: @end example
 5864: 
 5865: Not surprisingly, there is no need to define @code{myvariable}, since
 5866: Forth already has a definition @code{Variable}. ANS Forth does not
 5867: guarantee that a @code{Variable} is initialised when it is created
 5868: (i.e., it may behave like @code{myvariableX}). In contrast, Gforth's
 5869: @code{Variable} initialises the variable to 0 (i.e., it behaves exactly
 5870: like @code{myvariable0}). Forth also provides @code{2Variable} and
 5871: @code{fvariable} for double and floating-point variables, respectively
 5872: -- they are initialised to 0. and 0e in Gforth. If you use a @code{Variable} to
 5873: store a boolean, you can use @code{on} and @code{off} to toggle its
 5874: state.
 5875: 
 5876: doc-variable
 5877: doc-2variable
 5878: doc-fvariable
 5879: 
 5880: @cindex user variables
 5881: @cindex user space
 5882: The defining word @code{User} behaves in the same way as @code{Variable}.
 5883: The difference is that it reserves space in @i{user (data) space} rather
 5884: than normal data space. In a Forth system that has a multi-tasker, each
 5885: task has its own set of user variables.
 5886: 
 5887: doc-user
 5888: @c doc-udp
 5889: @c doc-uallot
 5890: 
 5891: @comment TODO is that stuff about user variables strictly correct? Is it
 5892: @comment just terminal tasks that have user variables?
 5893: @comment should document tasker.fs (with some examples) elsewhere
 5894: @comment in this manual, then expand on user space and user variables.
 5895: 
 5896: @node Constants, Values, Variables, Defining Words
 5897: @subsection Constants
 5898: @cindex constants
 5899: 
 5900: @code{Constant} allows you to declare a fixed value and refer to it by
 5901: name. For example:
 5902: 
 5903: @example
 5904: 12 Constant INCHES-PER-FOOT
 5905: 3E+08 fconstant SPEED-O-LIGHT
 5906: @end example
 5907: 
 5908: A @code{Variable} can be both read and written, so its run-time
 5909: behaviour is to supply an address through which its current value can be
 5910: manipulated. In contrast, the value of a @code{Constant} cannot be
 5911: changed once it has been declared@footnote{Well, often it can be -- but
 5912: not in a Standard, portable way. It's safer to use a @code{Value} (read
 5913: on).} so it's not necessary to supply the address -- it is more
 5914: efficient to return the value of the constant directly. That's exactly
 5915: what happens; the run-time effect of a constant is to put its value on
 5916: the top of the stack (You can find one
 5917: way of implementing @code{Constant} in @ref{User-defined Defining Words}).
 5918: 
 5919: Forth also provides @code{2Constant} and @code{fconstant} for defining
 5920: double and floating-point constants, respectively.
 5921: 
 5922: doc-constant
 5923: doc-2constant
 5924: doc-fconstant
 5925: 
 5926: @c that's too deep, and it's not necessarily true for all ANS Forths. - anton
 5927: @c nac-> How could that not be true in an ANS Forth? You can't define a
 5928: @c constant, use it and then delete the definition of the constant..
 5929: 
 5930: @c anton->An ANS Forth system can compile a constant to a literal; On
 5931: @c decompilation you would see only the number, just as if it had been used
 5932: @c in the first place.  The word will stay, of course, but it will only be
 5933: @c used by the text interpreter (no run-time duties, except when it is 
 5934: @c POSTPONEd or somesuch).
 5935: 
 5936: @c nac:
 5937: @c I agree that it's rather deep, but IMO it is an important difference
 5938: @c relative to other programming languages.. often it's annoying: it
 5939: @c certainly changes my programming style relative to C.
 5940: 
 5941: @c anton: In what way?
 5942: 
 5943: Constants in Forth behave differently from their equivalents in other
 5944: programming languages. In other languages, a constant (such as an EQU in
 5945: assembler or a #define in C) only exists at compile-time; in the
 5946: executable program the constant has been translated into an absolute
 5947: number and, unless you are using a symbolic debugger, it's impossible to
 5948: know what abstract thing that number represents. In Forth a constant has
 5949: an entry in the header space and remains there after the code that uses
 5950: it has been defined. In fact, it must remain in the dictionary since it
 5951: has run-time duties to perform. For example:
 5952: 
 5953: @example
 5954: 12 Constant INCHES-PER-FOOT
 5955: : FEET-TO-INCHES ( n1 -- n2 ) INCHES-PER-FOOT * ;
 5956: @end example
 5957: 
 5958: @cindex in-lining of constants
 5959: When @code{FEET-TO-INCHES} is executed, it will in turn execute the xt
 5960: associated with the constant @code{INCHES-PER-FOOT}. If you use
 5961: @code{see} to decompile the definition of @code{FEET-TO-INCHES}, you can
 5962: see that it makes a call to @code{INCHES-PER-FOOT}. Some Forth compilers
 5963: attempt to optimise constants by in-lining them where they are used. You
 5964: can force Gforth to in-line a constant like this:
 5965: 
 5966: @example
 5967: : FEET-TO-INCHES ( n1 -- n2 ) [ INCHES-PER-FOOT ] LITERAL * ;
 5968: @end example
 5969: 
 5970: If you use @code{see} to decompile @i{this} version of
 5971: @code{FEET-TO-INCHES}, you can see that @code{INCHES-PER-FOOT} is no
 5972: longer present. To understand how this works, read
 5973: @ref{Interpret/Compile states}, and @ref{Literals}.
 5974: 
 5975: In-lining constants in this way might improve execution time
 5976: fractionally, and can ensure that a constant is now only referenced at
 5977: compile-time. However, the definition of the constant still remains in
 5978: the dictionary. Some Forth compilers provide a mechanism for controlling
 5979: a second dictionary for holding transient words such that this second
 5980: dictionary can be deleted later in order to recover memory
 5981: space. However, there is no standard way of doing this.
 5982: 
 5983: 
 5984: @node Values, Colon Definitions, Constants, Defining Words
 5985: @subsection Values
 5986: @cindex values
 5987: 
 5988: A @code{Value} behaves like a @code{Constant}, but it can be changed.
 5989: @code{TO} is a parsing word that changes a @code{Values}.  In Gforth
 5990: (not in ANS Forth) you can access (and change) a @code{value} also with
 5991: @code{>body}.
 5992: 
 5993: Here are some
 5994: examples:
 5995: 
 5996: @example
 5997: 12 Value APPLES     \ Define APPLES with an initial value of 12
 5998: 34 TO APPLES        \ Change the value of APPLES. TO is a parsing word
 5999: 1 ' APPLES >body +! \ Increment APPLES.  Non-standard usage.
 6000: APPLES              \ puts 35 on the top of the stack.
 6001: @end example
 6002: 
 6003: doc-value
 6004: doc-to
 6005: 
 6006: 
 6007: 
 6008: @node Colon Definitions, Anonymous Definitions, Values, Defining Words
 6009: @subsection Colon Definitions
 6010: @cindex colon definitions
 6011: 
 6012: @example
 6013: : name ( ... -- ... )
 6014:     word1 word2 word3 ;
 6015: @end example
 6016: 
 6017: @noindent
 6018: Creates a word called @code{name} that, upon execution, executes
 6019: @code{word1 word2 word3}. @code{name} is a @dfn{(colon) definition}.
 6020: 
 6021: The explanation above is somewhat superficial. For simple examples of
 6022: colon definitions see @ref{Your first definition}.  For an in-depth
 6023: discussion of some of the issues involved, @xref{Interpretation and
 6024: Compilation Semantics}.
 6025: 
 6026: doc-:
 6027: doc-;
 6028: 
 6029: 
 6030: @node Anonymous Definitions, Supplying names, Colon Definitions, Defining Words
 6031: @subsection Anonymous Definitions
 6032: @cindex colon definitions
 6033: @cindex defining words without name
 6034: 
 6035: Sometimes you want to define an @dfn{anonymous word}; a word without a
 6036: name. You can do this with:
 6037: 
 6038: doc-:noname
 6039: 
 6040: This leaves the execution token for the word on the stack after the
 6041: closing @code{;}. Here's an example in which a deferred word is
 6042: initialised with an @code{xt} from an anonymous colon definition:
 6043: 
 6044: @example
 6045: Defer deferred
 6046: :noname ( ... -- ... )
 6047:   ... ;
 6048: IS deferred
 6049: @end example
 6050: 
 6051: @noindent
 6052: Gforth provides an alternative way of doing this, using two separate
 6053: words:
 6054: 
 6055: doc-noname
 6056: @cindex execution token of last defined word
 6057: doc-latestxt
 6058: 
 6059: @noindent
 6060: The previous example can be rewritten using @code{noname} and
 6061: @code{latestxt}:
 6062: 
 6063: @example
 6064: Defer deferred
 6065: noname : ( ... -- ... )
 6066:   ... ;
 6067: latestxt IS deferred
 6068: @end example
 6069: 
 6070: @noindent
 6071: @code{noname} works with any defining word, not just @code{:}.
 6072: 
 6073: @code{latestxt} also works when the last word was not defined as
 6074: @code{noname}.  It does not work for combined words, though.  It also has
 6075: the useful property that is is valid as soon as the header for a
 6076: definition has been built. Thus:
 6077: 
 6078: @example
 6079: latestxt . : foo [ latestxt . ] ; ' foo .
 6080: @end example
 6081: 
 6082: @noindent
 6083: prints 3 numbers; the last two are the same.
 6084: 
 6085: @node Supplying names, User-defined Defining Words, Anonymous Definitions, Defining Words
 6086: @subsection Supplying the name of a defined word
 6087: @cindex names for defined words
 6088: @cindex defining words, name given in a string
 6089: 
 6090: By default, a defining word takes the name for the defined word from the
 6091: input stream. Sometimes you want to supply the name from a string. You
 6092: can do this with:
 6093: 
 6094: doc-nextname
 6095: 
 6096: For example:
 6097: 
 6098: @example
 6099: s" foo" nextname create
 6100: @end example
 6101: 
 6102: @noindent
 6103: is equivalent to:
 6104: 
 6105: @example
 6106: create foo
 6107: @end example
 6108: 
 6109: @noindent
 6110: @code{nextname} works with any defining word.
 6111: 
 6112: 
 6113: @node User-defined Defining Words, Deferred words, Supplying names, Defining Words
 6114: @subsection User-defined Defining Words
 6115: @cindex user-defined defining words
 6116: @cindex defining words, user-defined
 6117: 
 6118: You can create a new defining word by wrapping defining-time code around
 6119: an existing defining word and putting the sequence in a colon
 6120: definition. 
 6121: 
 6122: @c anton: This example is very complex and leads in a quite different
 6123: @c direction from the CREATE-DOES> stuff that follows.  It should probably
 6124: @c be done elsewhere, or as a subsubsection of this subsection (or as a
 6125: @c subsection of Defining Words)
 6126: 
 6127: For example, suppose that you have a word @code{stats} that
 6128: gathers statistics about colon definitions given the @i{xt} of the
 6129: definition, and you want every colon definition in your application to
 6130: make a call to @code{stats}. You can define and use a new version of
 6131: @code{:} like this:
 6132: 
 6133: @example
 6134: : stats ( xt -- ) DUP ." (Gathering statistics for " . ." )"
 6135:   ... ;  \ other code
 6136: 
 6137: : my: : latestxt postpone literal ['] stats compile, ;
 6138: 
 6139: my: foo + - ;
 6140: @end example
 6141: 
 6142: When @code{foo} is defined using @code{my:} these steps occur:
 6143: 
 6144: @itemize @bullet
 6145: @item
 6146: @code{my:} is executed.
 6147: @item
 6148: The @code{:} within the definition (the one between @code{my:} and
 6149: @code{latestxt}) is executed, and does just what it always does; it parses
 6150: the input stream for a name, builds a dictionary header for the name
 6151: @code{foo} and switches @code{state} from interpret to compile.
 6152: @item
 6153: The word @code{latestxt} is executed. It puts the @i{xt} for the word that is
 6154: being defined -- @code{foo} -- onto the stack.
 6155: @item
 6156: The code that was produced by @code{postpone literal} is executed; this
 6157: causes the value on the stack to be compiled as a literal in the code
 6158: area of @code{foo}.
 6159: @item
 6160: The code @code{['] stats} compiles a literal into the definition of
 6161: @code{my:}. When @code{compile,} is executed, that literal -- the
 6162: execution token for @code{stats} -- is layed down in the code area of
 6163: @code{foo} , following the literal@footnote{Strictly speaking, the
 6164: mechanism that @code{compile,} uses to convert an @i{xt} into something
 6165: in the code area is implementation-dependent. A threaded implementation
 6166: might spit out the execution token directly whilst another
 6167: implementation might spit out a native code sequence.}.
 6168: @item
 6169: At this point, the execution of @code{my:} is complete, and control
 6170: returns to the text interpreter. The text interpreter is in compile
 6171: state, so subsequent text @code{+ -} is compiled into the definition of
 6172: @code{foo} and the @code{;} terminates the definition as always.
 6173: @end itemize
 6174: 
 6175: You can use @code{see} to decompile a word that was defined using
 6176: @code{my:} and see how it is different from a normal @code{:}
 6177: definition. For example:
 6178: 
 6179: @example
 6180: : bar + - ;  \ like foo but using : rather than my:
 6181: see bar
 6182: : bar
 6183:   + - ;
 6184: see foo
 6185: : foo
 6186:   107645672 stats + - ;
 6187: 
 6188: \ use ' foo . to show that 107645672 is the xt for foo
 6189: @end example
 6190: 
 6191: You can use techniques like this to make new defining words in terms of
 6192: @i{any} existing defining word.
 6193: 
 6194: 
 6195: @cindex defining defining words
 6196: @cindex @code{CREATE} ... @code{DOES>}
 6197: If you want the words defined with your defining words to behave
 6198: differently from words defined with standard defining words, you can
 6199: write your defining word like this:
 6200: 
 6201: @example
 6202: : def-word ( "name" -- )
 6203:     CREATE @i{code1}
 6204: DOES> ( ... -- ... )
 6205:     @i{code2} ;
 6206: 
 6207: def-word name
 6208: @end example
 6209: 
 6210: @cindex child words
 6211: This fragment defines a @dfn{defining word} @code{def-word} and then
 6212: executes it.  When @code{def-word} executes, it @code{CREATE}s a new
 6213: word, @code{name}, and executes the code @i{code1}. The code @i{code2}
 6214: is not executed at this time. The word @code{name} is sometimes called a
 6215: @dfn{child} of @code{def-word}.
 6216: 
 6217: When you execute @code{name}, the address of the body of @code{name} is
 6218: put on the data stack and @i{code2} is executed (the address of the body
 6219: of @code{name} is the address @code{HERE} returns immediately after the
 6220: @code{CREATE}, i.e., the address a @code{create}d word returns by
 6221: default).
 6222: 
 6223: @c anton:
 6224: @c www.dictionary.com says:
 6225: @c at·a·vism: 1.The reappearance of a characteristic in an organism after
 6226: @c several generations of absence, usually caused by the chance
 6227: @c recombination of genes.  2.An individual or a part that exhibits
 6228: @c atavism. Also called throwback.  3.The return of a trait or recurrence
 6229: @c of previous behavior after a period of absence.
 6230: @c
 6231: @c Doesn't seem to fit.
 6232: 
 6233: @c @cindex atavism in child words
 6234: You can use @code{def-word} to define a set of child words that behave
 6235: similarly; they all have a common run-time behaviour determined by
 6236: @i{code2}. Typically, the @i{code1} sequence builds a data area in the
 6237: body of the child word. The structure of the data is common to all
 6238: children of @code{def-word}, but the data values are specific -- and
 6239: private -- to each child word. When a child word is executed, the
 6240: address of its private data area is passed as a parameter on TOS to be
 6241: used and manipulated@footnote{It is legitimate both to read and write to
 6242: this data area.} by @i{code2}.
 6243: 
 6244: The two fragments of code that make up the defining words act (are
 6245: executed) at two completely separate times:
 6246: 
 6247: @itemize @bullet
 6248: @item
 6249: At @i{define time}, the defining word executes @i{code1} to generate a
 6250: child word
 6251: @item
 6252: At @i{child execution time}, when a child word is invoked, @i{code2}
 6253: is executed, using parameters (data) that are private and specific to
 6254: the child word.
 6255: @end itemize
 6256: 
 6257: Another way of understanding the behaviour of @code{def-word} and
 6258: @code{name} is to say that, if you make the following definitions:
 6259: @example
 6260: : def-word1 ( "name" -- )
 6261:     CREATE @i{code1} ;
 6262: 
 6263: : action1 ( ... -- ... )
 6264:     @i{code2} ;
 6265: 
 6266: def-word1 name1
 6267: @end example
 6268: 
 6269: @noindent
 6270: Then using @code{name1 action1} is equivalent to using @code{name}.
 6271: 
 6272: The classic example is that you can define @code{CONSTANT} in this way:
 6273: 
 6274: @example
 6275: : CONSTANT ( w "name" -- )
 6276:     CREATE ,
 6277: DOES> ( -- w )
 6278:     @@ ;
 6279: @end example
 6280: 
 6281: @comment There is a beautiful description of how this works and what
 6282: @comment it does in the Forthwrite 100th edition.. as well as an elegant
 6283: @comment commentary on the Counting Fruits problem.
 6284: 
 6285: When you create a constant with @code{5 CONSTANT five}, a set of
 6286: define-time actions take place; first a new word @code{five} is created,
 6287: then the value 5 is laid down in the body of @code{five} with
 6288: @code{,}. When @code{five} is executed, the address of the body is put on
 6289: the stack, and @code{@@} retrieves the value 5. The word @code{five} has
 6290: no code of its own; it simply contains a data field and a pointer to the
 6291: code that follows @code{DOES>} in its defining word. That makes words
 6292: created in this way very compact.
 6293: 
 6294: The final example in this section is intended to remind you that space
 6295: reserved in @code{CREATE}d words is @i{data} space and therefore can be
 6296: both read and written by a Standard program@footnote{Exercise: use this
 6297: example as a starting point for your own implementation of @code{Value}
 6298: and @code{TO} -- if you get stuck, investigate the behaviour of @code{'} and
 6299: @code{[']}.}:
 6300: 
 6301: @example
 6302: : foo ( "name" -- )
 6303:     CREATE -1 ,
 6304: DOES> ( -- )
 6305:     @@ . ;
 6306: 
 6307: foo first-word
 6308: foo second-word
 6309: 
 6310: 123 ' first-word >BODY !
 6311: @end example
 6312: 
 6313: If @code{first-word} had been a @code{CREATE}d word, we could simply
 6314: have executed it to get the address of its data field. However, since it
 6315: was defined to have @code{DOES>} actions, its execution semantics are to
 6316: perform those @code{DOES>} actions. To get the address of its data field
 6317: it's necessary to use @code{'} to get its xt, then @code{>BODY} to
 6318: translate the xt into the address of the data field.  When you execute
 6319: @code{first-word}, it will display @code{123}. When you execute
 6320: @code{second-word} it will display @code{-1}.
 6321: 
 6322: @cindex stack effect of @code{DOES>}-parts
 6323: @cindex @code{DOES>}-parts, stack effect
 6324: In the examples above the stack comment after the @code{DOES>} specifies
 6325: the stack effect of the defined words, not the stack effect of the
 6326: following code (the following code expects the address of the body on
 6327: the top of stack, which is not reflected in the stack comment). This is
 6328: the convention that I use and recommend (it clashes a bit with using
 6329: locals declarations for stack effect specification, though).
 6330: 
 6331: @menu
 6332: * CREATE..DOES> applications::  
 6333: * CREATE..DOES> details::       
 6334: * Advanced does> usage example::  
 6335: * Const-does>::          
 6336: @end menu
 6337: 
 6338: @node CREATE..DOES> applications, CREATE..DOES> details, User-defined Defining Words, User-defined Defining Words
 6339: @subsubsection Applications of @code{CREATE..DOES>}
 6340: @cindex @code{CREATE} ... @code{DOES>}, applications
 6341: 
 6342: You may wonder how to use this feature. Here are some usage patterns:
 6343: 
 6344: @cindex factoring similar colon definitions
 6345: When you see a sequence of code occurring several times, and you can
 6346: identify a meaning, you will factor it out as a colon definition. When
 6347: you see similar colon definitions, you can factor them using
 6348: @code{CREATE..DOES>}. E.g., an assembler usually defines several words
 6349: that look very similar:
 6350: @example
 6351: : ori, ( reg-target reg-source n -- )
 6352:     0 asm-reg-reg-imm ;
 6353: : andi, ( reg-target reg-source n -- )
 6354:     1 asm-reg-reg-imm ;
 6355: @end example
 6356: 
 6357: @noindent
 6358: This could be factored with:
 6359: @example
 6360: : reg-reg-imm ( op-code -- )
 6361:     CREATE ,
 6362: DOES> ( reg-target reg-source n -- )
 6363:     @@ asm-reg-reg-imm ;
 6364: 
 6365: 0 reg-reg-imm ori,
 6366: 1 reg-reg-imm andi,
 6367: @end example
 6368: 
 6369: @cindex currying
 6370: Another view of @code{CREATE..DOES>} is to consider it as a crude way to
 6371: supply a part of the parameters for a word (known as @dfn{currying} in
 6372: the functional language community). E.g., @code{+} needs two
 6373: parameters. Creating versions of @code{+} with one parameter fixed can
 6374: be done like this:
 6375: 
 6376: @example
 6377: : curry+ ( n1 "name" -- )
 6378:     CREATE ,
 6379: DOES> ( n2 -- n1+n2 )
 6380:     @@ + ;
 6381: 
 6382:  3 curry+ 3+
 6383: -2 curry+ 2-
 6384: @end example
 6385: 
 6386: 
 6387: @node CREATE..DOES> details, Advanced does> usage example, CREATE..DOES> applications, User-defined Defining Words
 6388: @subsubsection The gory details of @code{CREATE..DOES>}
 6389: @cindex @code{CREATE} ... @code{DOES>}, details
 6390: 
 6391: doc-does>
 6392: 
 6393: @cindex @code{DOES>} in a separate definition
 6394: This means that you need not use @code{CREATE} and @code{DOES>} in the
 6395: same definition; you can put the @code{DOES>}-part in a separate
 6396: definition. This allows us to, e.g., select among different @code{DOES>}-parts:
 6397: @example
 6398: : does1 
 6399: DOES> ( ... -- ... )
 6400:     ... ;
 6401: 
 6402: : does2
 6403: DOES> ( ... -- ... )
 6404:     ... ;
 6405: 
 6406: : def-word ( ... -- ... )
 6407:     create ...
 6408:     IF
 6409:        does1
 6410:     ELSE
 6411:        does2
 6412:     ENDIF ;
 6413: @end example
 6414: 
 6415: In this example, the selection of whether to use @code{does1} or
 6416: @code{does2} is made at definition-time; at the time that the child word is
 6417: @code{CREATE}d.
 6418: 
 6419: @cindex @code{DOES>} in interpretation state
 6420: In a standard program you can apply a @code{DOES>}-part only if the last
 6421: word was defined with @code{CREATE}. In Gforth, the @code{DOES>}-part
 6422: will override the behaviour of the last word defined in any case. In a
 6423: standard program, you can use @code{DOES>} only in a colon
 6424: definition. In Gforth, you can also use it in interpretation state, in a
 6425: kind of one-shot mode; for example:
 6426: @example
 6427: CREATE name ( ... -- ... )
 6428:   @i{initialization}
 6429: DOES>
 6430:   @i{code} ;
 6431: @end example
 6432: 
 6433: @noindent
 6434: is equivalent to the standard:
 6435: @example
 6436: :noname
 6437: DOES>
 6438:     @i{code} ;
 6439: CREATE name EXECUTE ( ... -- ... )
 6440:     @i{initialization}
 6441: @end example
 6442: 
 6443: doc->body
 6444: 
 6445: @node Advanced does> usage example, Const-does>, CREATE..DOES> details, User-defined Defining Words
 6446: @subsubsection Advanced does> usage example
 6447: 
 6448: The MIPS disassembler (@file{arch/mips/disasm.fs}) contains many words
 6449: for disassembling instructions, that follow a very repetetive scheme:
 6450: 
 6451: @example
 6452: :noname @var{disasm-operands} s" @var{inst-name}" type ;
 6453: @var{entry-num} cells @var{table} + !
 6454: @end example
 6455: 
 6456: Of course, this inspires the idea to factor out the commonalities to
 6457: allow a definition like
 6458: 
 6459: @example
 6460: @var{disasm-operands} @var{entry-num} @var{table} define-inst @var{inst-name}
 6461: @end example
 6462: 
 6463: The parameters @var{disasm-operands} and @var{table} are usually
 6464: correlated.  Moreover, before I wrote the disassembler, there already
 6465: existed code that defines instructions like this:
 6466: 
 6467: @example
 6468: @var{entry-num} @var{inst-format} @var{inst-name}
 6469: @end example
 6470: 
 6471: This code comes from the assembler and resides in
 6472: @file{arch/mips/insts.fs}.
 6473: 
 6474: So I had to define the @var{inst-format} words that performed the scheme
 6475: above when executed.  At first I chose to use run-time code-generation:
 6476: 
 6477: @example
 6478: : @var{inst-format} ( entry-num "name" -- ; compiled code: addr w -- )
 6479:   :noname Postpone @var{disasm-operands}
 6480:   name Postpone sliteral Postpone type Postpone ;
 6481:   swap cells @var{table} + ! ;
 6482: @end example
 6483: 
 6484: Note that this supplies the other two parameters of the scheme above.
 6485: 
 6486: An alternative would have been to write this using
 6487: @code{create}/@code{does>}:
 6488: 
 6489: @example
 6490: : @var{inst-format} ( entry-num "name" -- )
 6491:   here name string, ( entry-num c-addr ) \ parse and save "name"
 6492:   noname create , ( entry-num )
 6493:   latestxt swap cells @var{table} + !
 6494: does> ( addr w -- )
 6495:   \ disassemble instruction w at addr
 6496:   @@ >r 
 6497:   @var{disasm-operands}
 6498:   r> count type ;
 6499: @end example
 6500: 
 6501: Somehow the first solution is simpler, mainly because it's simpler to
 6502: shift a string from definition-time to use-time with @code{sliteral}
 6503: than with @code{string,} and friends.
 6504: 
 6505: I wrote a lot of words following this scheme and soon thought about
 6506: factoring out the commonalities among them.  Note that this uses a
 6507: two-level defining word, i.e., a word that defines ordinary defining
 6508: words.
 6509: 
 6510: This time a solution involving @code{postpone} and friends seemed more
 6511: difficult (try it as an exercise), so I decided to use a
 6512: @code{create}/@code{does>} word; since I was already at it, I also used
 6513: @code{create}/@code{does>} for the lower level (try using
 6514: @code{postpone} etc. as an exercise), resulting in the following
 6515: definition:
 6516: 
 6517: @example
 6518: : define-format ( disasm-xt table-xt -- )
 6519:     \ define an instruction format that uses disasm-xt for
 6520:     \ disassembling and enters the defined instructions into table
 6521:     \ table-xt
 6522:     create 2,
 6523: does> ( u "inst" -- )
 6524:     \ defines an anonymous word for disassembling instruction inst,
 6525:     \ and enters it as u-th entry into table-xt
 6526:     2@@ swap here name string, ( u table-xt disasm-xt c-addr ) \ remember string
 6527:     noname create 2,      \ define anonymous word
 6528:     execute latestxt swap ! \ enter xt of defined word into table-xt
 6529: does> ( addr w -- )
 6530:     \ disassemble instruction w at addr
 6531:     2@@ >r ( addr w disasm-xt R: c-addr )
 6532:     execute ( R: c-addr ) \ disassemble operands
 6533:     r> count type ; \ print name 
 6534: @end example
 6535: 
 6536: Note that the tables here (in contrast to above) do the @code{cells +}
 6537: by themselves (that's why you have to pass an xt).  This word is used in
 6538: the following way:
 6539: 
 6540: @example
 6541: ' @var{disasm-operands} ' @var{table} define-format @var{inst-format}
 6542: @end example
 6543: 
 6544: As shown above, the defined instruction format is then used like this:
 6545: 
 6546: @example
 6547: @var{entry-num} @var{inst-format} @var{inst-name}
 6548: @end example
 6549: 
 6550: In terms of currying, this kind of two-level defining word provides the
 6551: parameters in three stages: first @var{disasm-operands} and @var{table},
 6552: then @var{entry-num} and @var{inst-name}, finally @code{addr w}, i.e.,
 6553: the instruction to be disassembled.  
 6554: 
 6555: Of course this did not quite fit all the instruction format names used
 6556: in @file{insts.fs}, so I had to define a few wrappers that conditioned
 6557: the parameters into the right form.
 6558: 
 6559: If you have trouble following this section, don't worry.  First, this is
 6560: involved and takes time (and probably some playing around) to
 6561: understand; second, this is the first two-level
 6562: @code{create}/@code{does>} word I have written in seventeen years of
 6563: Forth; and if I did not have @file{insts.fs} to start with, I may well
 6564: have elected to use just a one-level defining word (with some repeating
 6565: of parameters when using the defining word). So it is not necessary to
 6566: understand this, but it may improve your understanding of Forth.
 6567: 
 6568: 
 6569: @node Const-does>,  , Advanced does> usage example, User-defined Defining Words
 6570: @subsubsection @code{Const-does>}
 6571: 
 6572: A frequent use of @code{create}...@code{does>} is for transferring some
 6573: values from definition-time to run-time.  Gforth supports this use with
 6574: 
 6575: doc-const-does>
 6576: 
 6577: A typical use of this word is:
 6578: 
 6579: @example
 6580: : curry+ ( n1 "name" -- )
 6581: 1 0 CONST-DOES> ( n2 -- n1+n2 )
 6582:     + ;
 6583: 
 6584: 3 curry+ 3+
 6585: @end example
 6586: 
 6587: Here the @code{1 0} means that 1 cell and 0 floats are transferred from
 6588: definition to run-time.
 6589: 
 6590: The advantages of using @code{const-does>} are:
 6591: 
 6592: @itemize
 6593: 
 6594: @item
 6595: You don't have to deal with storing and retrieving the values, i.e.,
 6596: your program becomes more writable and readable.
 6597: 
 6598: @item
 6599: When using @code{does>}, you have to introduce a @code{@@} that cannot
 6600: be optimized away (because you could change the data using
 6601: @code{>body}...@code{!}); @code{const-does>} avoids this problem.
 6602: 
 6603: @end itemize
 6604: 
 6605: An ANS Forth implementation of @code{const-does>} is available in
 6606: @file{compat/const-does.fs}.
 6607: 
 6608: 
 6609: @node Deferred words, Aliases, User-defined Defining Words, Defining Words
 6610: @subsection Deferred words
 6611: @cindex deferred words
 6612: 
 6613: The defining word @code{Defer} allows you to define a word by name
 6614: without defining its behaviour; the definition of its behaviour is
 6615: deferred. Here are two situation where this can be useful:
 6616: 
 6617: @itemize @bullet
 6618: @item
 6619: Where you want to allow the behaviour of a word to be altered later, and
 6620: for all precompiled references to the word to change when its behaviour
 6621: is changed.
 6622: @item
 6623: For mutual recursion; @xref{Calls and returns}.
 6624: @end itemize
 6625: 
 6626: In the following example, @code{foo} always invokes the version of
 6627: @code{greet} that prints ``@code{Good morning}'' whilst @code{bar}
 6628: always invokes the version that prints ``@code{Hello}''. There is no way
 6629: of getting @code{foo} to use the later version without re-ordering the
 6630: source code and recompiling it.
 6631: 
 6632: @example
 6633: : greet ." Good morning" ;
 6634: : foo ... greet ... ;
 6635: : greet ." Hello" ;
 6636: : bar ... greet ... ;
 6637: @end example
 6638: 
 6639: This problem can be solved by defining @code{greet} as a @code{Defer}red
 6640: word. The behaviour of a @code{Defer}red word can be defined and
 6641: redefined at any time by using @code{IS} to associate the xt of a
 6642: previously-defined word with it. The previous example becomes:
 6643: 
 6644: @example
 6645: Defer greet ( -- )
 6646: : foo ... greet ... ;
 6647: : bar ... greet ... ;
 6648: : greet1 ( -- ) ." Good morning" ;
 6649: : greet2 ( -- ) ." Hello" ;
 6650: ' greet2 IS greet  \ make greet behave like greet2
 6651: @end example
 6652: 
 6653: @progstyle
 6654: You should write a stack comment for every deferred word, and put only
 6655: XTs into deferred words that conform to this stack effect.  Otherwise
 6656: it's too difficult to use the deferred word.
 6657: 
 6658: A deferred word can be used to improve the statistics-gathering example
 6659: from @ref{User-defined Defining Words}; rather than edit the
 6660: application's source code to change every @code{:} to a @code{my:}, do
 6661: this:
 6662: 
 6663: @example
 6664: : real: : ;     \ retain access to the original
 6665: defer :         \ redefine as a deferred word
 6666: ' my: IS :      \ use special version of :
 6667: \
 6668: \ load application here
 6669: \
 6670: ' real: IS :    \ go back to the original
 6671: @end example
 6672: 
 6673: 
 6674: One thing to note is that @code{IS} has special compilation semantics,
 6675: such that it parses the name at compile time (like @code{TO}):
 6676: 
 6677: @example
 6678: : set-greet ( xt -- )
 6679:   IS greet ;
 6680: 
 6681: ' greet1 set-greet
 6682: @end example
 6683: 
 6684: In situations where @code{IS} does not fit, use @code{defer!} instead.
 6685: 
 6686: A deferred word can only inherit execution semantics from the xt
 6687: (because that is all that an xt can represent -- for more discussion of
 6688: this @pxref{Tokens for Words}); by default it will have default
 6689: interpretation and compilation semantics deriving from this execution
 6690: semantics.  However, you can change the interpretation and compilation
 6691: semantics of the deferred word in the usual ways:
 6692: 
 6693: @example
 6694: : bar .... ; immediate
 6695: Defer fred immediate
 6696: Defer jim
 6697: 
 6698: ' bar IS jim  \ jim has default semantics
 6699: ' bar IS fred \ fred is immediate
 6700: @end example
 6701: 
 6702: doc-defer
 6703: doc-defer!
 6704: doc-is
 6705: doc-defer@
 6706: doc-action-of
 6707: @comment TODO document these: what's defers [is]
 6708: doc-defers
 6709: 
 6710: @c Use @code{words-deferred} to see a list of deferred words.
 6711: 
 6712: Definitions of these words (except @code{defers}) in ANS Forth are
 6713: provided in @file{compat/defer.fs}.
 6714: 
 6715: 
 6716: @node Aliases,  , Deferred words, Defining Words
 6717: @subsection Aliases
 6718: @cindex aliases
 6719: 
 6720: The defining word @code{Alias} allows you to define a word by name that
 6721: has the same behaviour as some other word. Here are two situation where
 6722: this can be useful:
 6723: 
 6724: @itemize @bullet
 6725: @item
 6726: When you want access to a word's definition from a different word list
 6727: (for an example of this, see the definition of the @code{Root} word list
 6728: in the Gforth source).
 6729: @item
 6730: When you want to create a synonym; a definition that can be known by
 6731: either of two names (for example, @code{THEN} and @code{ENDIF} are
 6732: aliases).
 6733: @end itemize
 6734: 
 6735: Like deferred words, an alias has default compilation and interpretation
 6736: semantics at the beginning (not the modifications of the other word),
 6737: but you can change them in the usual ways (@code{immediate},
 6738: @code{compile-only}). For example:
 6739: 
 6740: @example
 6741: : foo ... ; immediate
 6742: 
 6743: ' foo Alias bar \ bar is not an immediate word
 6744: ' foo Alias fooby immediate \ fooby is an immediate word
 6745: @end example
 6746: 
 6747: Words that are aliases have the same xt, different headers in the
 6748: dictionary, and consequently different name tokens (@pxref{Tokens for
 6749: Words}) and possibly different immediate flags.  An alias can only have
 6750: default or immediate compilation semantics; you can define aliases for
 6751: combined words with @code{interpret/compile:} -- see @ref{Combined words}.
 6752: 
 6753: doc-alias
 6754: 
 6755: 
 6756: @node Interpretation and Compilation Semantics, Tokens for Words, Defining Words, Words
 6757: @section Interpretation and Compilation Semantics
 6758: @cindex semantics, interpretation and compilation
 6759: 
 6760: @c !! state and ' are used without explanation
 6761: @c example for immediate/compile-only? or is the tutorial enough
 6762: 
 6763: @cindex interpretation semantics
 6764: The @dfn{interpretation semantics} of a (named) word are what the text
 6765: interpreter does when it encounters the word in interpret state. It also
 6766: appears in some other contexts, e.g., the execution token returned by
 6767: @code{' @i{word}} identifies the interpretation semantics of @i{word}
 6768: (in other words, @code{' @i{word} execute} is equivalent to
 6769: interpret-state text interpretation of @code{@i{word}}).
 6770: 
 6771: @cindex compilation semantics
 6772: The @dfn{compilation semantics} of a (named) word are what the text
 6773: interpreter does when it encounters the word in compile state. It also
 6774: appears in other contexts, e.g, @code{POSTPONE @i{word}}
 6775: compiles@footnote{In standard terminology, ``appends to the current
 6776: definition''.} the compilation semantics of @i{word}.
 6777: 
 6778: @cindex execution semantics
 6779: The standard also talks about @dfn{execution semantics}. They are used
 6780: only for defining the interpretation and compilation semantics of many
 6781: words. By default, the interpretation semantics of a word are to
 6782: @code{execute} its execution semantics, and the compilation semantics of
 6783: a word are to @code{compile,} its execution semantics.@footnote{In
 6784: standard terminology: The default interpretation semantics are its
 6785: execution semantics; the default compilation semantics are to append its
 6786: execution semantics to the execution semantics of the current
 6787: definition.}
 6788: 
 6789: Unnamed words (@pxref{Anonymous Definitions}) cannot be encountered by
 6790: the text interpreter, ticked, or @code{postpone}d, so they have no
 6791: interpretation or compilation semantics.  Their behaviour is represented
 6792: by their XT (@pxref{Tokens for Words}), and we call it execution
 6793: semantics, too.
 6794: 
 6795: @comment TODO expand, make it co-operate with new sections on text interpreter.
 6796: 
 6797: @cindex immediate words
 6798: @cindex compile-only words
 6799: You can change the semantics of the most-recently defined word:
 6800: 
 6801: 
 6802: doc-immediate
 6803: doc-compile-only
 6804: doc-restrict
 6805: 
 6806: By convention, words with non-default compilation semantics (e.g.,
 6807: immediate words) often have names surrounded with brackets (e.g.,
 6808: @code{[']}, @pxref{Execution token}).
 6809: 
 6810: Note that ticking (@code{'}) a compile-only word gives an error
 6811: (``Interpreting a compile-only word'').
 6812: 
 6813: @menu
 6814: * Combined words::              
 6815: @end menu
 6816: 
 6817: 
 6818: @node Combined words,  , Interpretation and Compilation Semantics, Interpretation and Compilation Semantics
 6819: @subsection Combined Words
 6820: @cindex combined words
 6821: 
 6822: Gforth allows you to define @dfn{combined words} -- words that have an
 6823: arbitrary combination of interpretation and compilation semantics.
 6824: 
 6825: doc-interpret/compile:
 6826: 
 6827: This feature was introduced for implementing @code{TO} and @code{S"}. I
 6828: recommend that you do not define such words, as cute as they may be:
 6829: they make it hard to get at both parts of the word in some contexts.
 6830: E.g., assume you want to get an execution token for the compilation
 6831: part. Instead, define two words, one that embodies the interpretation
 6832: part, and one that embodies the compilation part.  Once you have done
 6833: that, you can define a combined word with @code{interpret/compile:} for
 6834: the convenience of your users.
 6835: 
 6836: You might try to use this feature to provide an optimizing
 6837: implementation of the default compilation semantics of a word. For
 6838: example, by defining:
 6839: @example
 6840: :noname
 6841:    foo bar ;
 6842: :noname
 6843:    POSTPONE foo POSTPONE bar ;
 6844: interpret/compile: opti-foobar
 6845: @end example
 6846: 
 6847: @noindent
 6848: as an optimizing version of:
 6849: 
 6850: @example
 6851: : foobar
 6852:     foo bar ;
 6853: @end example
 6854: 
 6855: Unfortunately, this does not work correctly with @code{[compile]},
 6856: because @code{[compile]} assumes that the compilation semantics of all
 6857: @code{interpret/compile:} words are non-default. I.e., @code{[compile]
 6858: opti-foobar} would compile compilation semantics, whereas
 6859: @code{[compile] foobar} would compile interpretation semantics.
 6860: 
 6861: @cindex state-smart words (are a bad idea)
 6862: @anchor{state-smartness}
 6863: Some people try to use @dfn{state-smart} words to emulate the feature provided
 6864: by @code{interpret/compile:} (words are state-smart if they check
 6865: @code{STATE} during execution). E.g., they would try to code
 6866: @code{foobar} like this:
 6867: 
 6868: @example
 6869: : foobar
 6870:   STATE @@
 6871:   IF ( compilation state )
 6872:     POSTPONE foo POSTPONE bar
 6873:   ELSE
 6874:     foo bar
 6875:   ENDIF ; immediate
 6876: @end example
 6877: 
 6878: Although this works if @code{foobar} is only processed by the text
 6879: interpreter, it does not work in other contexts (like @code{'} or
 6880: @code{POSTPONE}). E.g., @code{' foobar} will produce an execution token
 6881: for a state-smart word, not for the interpretation semantics of the
 6882: original @code{foobar}; when you execute this execution token (directly
 6883: with @code{EXECUTE} or indirectly through @code{COMPILE,}) in compile
 6884: state, the result will not be what you expected (i.e., it will not
 6885: perform @code{foo bar}). State-smart words are a bad idea. Simply don't
 6886: write them@footnote{For a more detailed discussion of this topic, see
 6887: M. Anton Ertl,
 6888: @cite{@uref{http://www.complang.tuwien.ac.at/papers/ertl98.ps.gz,@code{State}-smartness---Why
 6889: it is Evil and How to Exorcise it}}, EuroForth '98.}!
 6890: 
 6891: @cindex defining words with arbitrary semantics combinations
 6892: It is also possible to write defining words that define words with
 6893: arbitrary combinations of interpretation and compilation semantics. In
 6894: general, they look like this:
 6895: 
 6896: @example
 6897: : def-word
 6898:     create-interpret/compile
 6899:     @i{code1}
 6900: interpretation>
 6901:     @i{code2}
 6902: <interpretation
 6903: compilation>
 6904:     @i{code3}
 6905: <compilation ;
 6906: @end example
 6907: 
 6908: For a @i{word} defined with @code{def-word}, the interpretation
 6909: semantics are to push the address of the body of @i{word} and perform
 6910: @i{code2}, and the compilation semantics are to push the address of
 6911: the body of @i{word} and perform @i{code3}. E.g., @code{constant}
 6912: can also be defined like this (except that the defined constants don't
 6913: behave correctly when @code{[compile]}d):
 6914: 
 6915: @example
 6916: : constant ( n "name" -- )
 6917:     create-interpret/compile
 6918:     ,
 6919: interpretation> ( -- n )
 6920:     @@
 6921: <interpretation
 6922: compilation> ( compilation. -- ; run-time. -- n )
 6923:     @@ postpone literal
 6924: <compilation ;
 6925: @end example
 6926: 
 6927: 
 6928: doc-create-interpret/compile
 6929: doc-interpretation>
 6930: doc-<interpretation
 6931: doc-compilation>
 6932: doc-<compilation
 6933: 
 6934: 
 6935: Words defined with @code{interpret/compile:} and
 6936: @code{create-interpret/compile} have an extended header structure that
 6937: differs from other words; however, unless you try to access them with
 6938: plain address arithmetic, you should not notice this. Words for
 6939: accessing the header structure usually know how to deal with this; e.g.,
 6940: @code{'} @i{word} @code{>body} also gives you the body of a word created
 6941: with @code{create-interpret/compile}.
 6942: 
 6943: 
 6944: @c -------------------------------------------------------------
 6945: @node Tokens for Words, Compiling words, Interpretation and Compilation Semantics, Words
 6946: @section Tokens for Words
 6947: @cindex tokens for words
 6948: 
 6949: This section describes the creation and use of tokens that represent
 6950: words.
 6951: 
 6952: @menu
 6953: * Execution token::             represents execution/interpretation semantics
 6954: * Compilation token::           represents compilation semantics
 6955: * Name token::                  represents named words
 6956: @end menu
 6957: 
 6958: @node Execution token, Compilation token, Tokens for Words, Tokens for Words
 6959: @subsection Execution token
 6960: 
 6961: @cindex xt
 6962: @cindex execution token
 6963: An @dfn{execution token} (@i{XT}) represents some behaviour of a word.
 6964: You can use @code{execute} to invoke this behaviour.
 6965: 
 6966: @cindex tick (')
 6967: You can use @code{'} to get an execution token that represents the
 6968: interpretation semantics of a named word:
 6969: 
 6970: @example
 6971: 5 ' .   ( n xt ) 
 6972: execute ( )      \ execute the xt (i.e., ".")
 6973: @end example
 6974: 
 6975: doc-'
 6976: 
 6977: @code{'} parses at run-time; there is also a word @code{[']} that parses
 6978: when it is compiled, and compiles the resulting XT:
 6979: 
 6980: @example
 6981: : foo ['] . execute ;
 6982: 5 foo
 6983: : bar ' execute ; \ by contrast,
 6984: 5 bar .           \ ' parses "." when bar executes
 6985: @end example
 6986: 
 6987: doc-[']
 6988: 
 6989: If you want the execution token of @i{word}, write @code{['] @i{word}}
 6990: in compiled code and @code{' @i{word}} in interpreted code.  Gforth's
 6991: @code{'} and @code{[']} behave somewhat unusually by complaining about
 6992: compile-only words (because these words have no interpretation
 6993: semantics).  You might get what you want by using @code{COMP' @i{word}
 6994: DROP} or @code{[COMP'] @i{word} DROP} (for details @pxref{Compilation
 6995: token}).
 6996: 
 6997: Another way to get an XT is @code{:noname} or @code{latestxt}
 6998: (@pxref{Anonymous Definitions}).  For anonymous words this gives an xt
 6999: for the only behaviour the word has (the execution semantics).  For
 7000: named words, @code{latestxt} produces an XT for the same behaviour it
 7001: would produce if the word was defined anonymously.
 7002: 
 7003: @example
 7004: :noname ." hello" ;
 7005: execute
 7006: @end example
 7007: 
 7008: An XT occupies one cell and can be manipulated like any other cell.
 7009: 
 7010: @cindex code field address
 7011: @cindex CFA
 7012: In ANS Forth the XT is just an abstract data type (i.e., defined by the
 7013: operations that produce or consume it).  For old hands: In Gforth, the
 7014: XT is implemented as a code field address (CFA).
 7015: 
 7016: doc-execute
 7017: doc-perform
 7018: 
 7019: @node Compilation token, Name token, Execution token, Tokens for Words
 7020: @subsection Compilation token
 7021: 
 7022: @cindex compilation token
 7023: @cindex CT (compilation token)
 7024: Gforth represents the compilation semantics of a named word by a
 7025: @dfn{compilation token} consisting of two cells: @i{w xt}. The top cell
 7026: @i{xt} is an execution token. The compilation semantics represented by
 7027: the compilation token can be performed with @code{execute}, which
 7028: consumes the whole compilation token, with an additional stack effect
 7029: determined by the represented compilation semantics.
 7030: 
 7031: At present, the @i{w} part of a compilation token is an execution token,
 7032: and the @i{xt} part represents either @code{execute} or
 7033: @code{compile,}@footnote{Depending upon the compilation semantics of the
 7034: word. If the word has default compilation semantics, the @i{xt} will
 7035: represent @code{compile,}. Otherwise (e.g., for immediate words), the
 7036: @i{xt} will represent @code{execute}.}. However, don't rely on that
 7037: knowledge, unless necessary; future versions of Gforth may introduce
 7038: unusual compilation tokens (e.g., a compilation token that represents
 7039: the compilation semantics of a literal).
 7040: 
 7041: You can perform the compilation semantics represented by the compilation
 7042: token with @code{execute}.  You can compile the compilation semantics
 7043: with @code{postpone,}. I.e., @code{COMP' @i{word} postpone,} is
 7044: equivalent to @code{postpone @i{word}}.
 7045: 
 7046: doc-[comp']
 7047: doc-comp'
 7048: doc-postpone,
 7049: 
 7050: @node Name token,  , Compilation token, Tokens for Words
 7051: @subsection Name token
 7052: 
 7053: @cindex name token
 7054: Gforth represents named words by the @dfn{name token}, (@i{nt}).  Name
 7055: token is an abstract data type that occurs as argument or result of the
 7056: words below.
 7057: 
 7058: @c !! put this elswhere?
 7059: @cindex name field address
 7060: @cindex NFA
 7061: The closest thing to the nt in older Forth systems is the name field
 7062: address (NFA), but there are significant differences: in older Forth
 7063: systems each word had a unique NFA, LFA, CFA and PFA (in this order, or
 7064: LFA, NFA, CFA, PFA) and there were words for getting from one to the
 7065: next.  In contrast, in Gforth 0@dots{}n nts correspond to one xt; there
 7066: is a link field in the structure identified by the name token, but
 7067: searching usually uses a hash table external to these structures; the
 7068: name in Gforth has a cell-wide count-and-flags field, and the nt is not
 7069: implemented as the address of that count field.
 7070: 
 7071: doc-find-name
 7072: doc-latest
 7073: doc->name
 7074: doc-name>int
 7075: doc-name?int
 7076: doc-name>comp
 7077: doc-name>string
 7078: doc-id.
 7079: doc-.name
 7080: doc-.id
 7081: 
 7082: @c ----------------------------------------------------------
 7083: @node Compiling words, The Text Interpreter, Tokens for Words, Words
 7084: @section Compiling words
 7085: @cindex compiling words
 7086: @cindex macros
 7087: 
 7088: In contrast to most other languages, Forth has no strict boundary
 7089: between compilation and run-time.  E.g., you can run arbitrary code
 7090: between defining words (or for computing data used by defining words
 7091: like @code{constant}). Moreover, @code{Immediate} (@pxref{Interpretation
 7092: and Compilation Semantics} and @code{[}...@code{]} (see below) allow
 7093: running arbitrary code while compiling a colon definition (exception:
 7094: you must not allot dictionary space).
 7095: 
 7096: @menu
 7097: * Literals::                    Compiling data values
 7098: * Macros::                      Compiling words
 7099: @end menu
 7100: 
 7101: @node Literals, Macros, Compiling words, Compiling words
 7102: @subsection Literals
 7103: @cindex Literals
 7104: 
 7105: The simplest and most frequent example is to compute a literal during
 7106: compilation.  E.g., the following definition prints an array of strings,
 7107: one string per line:
 7108: 
 7109: @example
 7110: : .strings ( addr u -- ) \ gforth
 7111:     2* cells bounds U+DO
 7112: 	cr i 2@@ type
 7113:     2 cells +LOOP ;  
 7114: @end example
 7115: 
 7116: With a simple-minded compiler like Gforth's, this computes @code{2
 7117: cells} on every loop iteration.  You can compute this value once and for
 7118: all at compile time and compile it into the definition like this:
 7119: 
 7120: @example
 7121: : .strings ( addr u -- ) \ gforth
 7122:     2* cells bounds U+DO
 7123: 	cr i 2@@ type
 7124:     [ 2 cells ] literal +LOOP ;  
 7125: @end example
 7126: 
 7127: @code{[} switches the text interpreter to interpret state (you will get
 7128: an @code{ok} prompt if you type this example interactively and insert a
 7129: newline between @code{[} and @code{]}), so it performs the
 7130: interpretation semantics of @code{2 cells}; this computes a number.
 7131: @code{]} switches the text interpreter back into compile state.  It then
 7132: performs @code{Literal}'s compilation semantics, which are to compile
 7133: this number into the current word.  You can decompile the word with
 7134: @code{see .strings} to see the effect on the compiled code.
 7135: 
 7136: You can also optimize the @code{2* cells} into @code{[ 2 cells ] literal
 7137: *} in this way.
 7138: 
 7139: doc-[
 7140: doc-]
 7141: doc-literal
 7142: doc-]L
 7143: 
 7144: There are also words for compiling other data types than single cells as
 7145: literals:
 7146: 
 7147: doc-2literal
 7148: doc-fliteral
 7149: doc-sliteral
 7150: 
 7151: @cindex colon-sys, passing data across @code{:}
 7152: @cindex @code{:}, passing data across
 7153: You might be tempted to pass data from outside a colon definition to the
 7154: inside on the data stack.  This does not work, because @code{:} puhes a
 7155: colon-sys, making stuff below unaccessible.  E.g., this does not work:
 7156: 
 7157: @example
 7158: 5 : foo literal ; \ error: "unstructured"
 7159: @end example
 7160: 
 7161: Instead, you have to pass the value in some other way, e.g., through a
 7162: variable:
 7163: 
 7164: @example
 7165: variable temp
 7166: 5 temp !
 7167: : foo [ temp @@ ] literal ;
 7168: @end example
 7169: 
 7170: 
 7171: @node Macros,  , Literals, Compiling words
 7172: @subsection Macros
 7173: @cindex Macros
 7174: @cindex compiling compilation semantics
 7175: 
 7176: @code{Literal} and friends compile data values into the current
 7177: definition.  You can also write words that compile other words into the
 7178: current definition.  E.g.,
 7179: 
 7180: @example
 7181: : compile-+ ( -- ) \ compiled code: ( n1 n2 -- n )
 7182:   POSTPONE + ;
 7183: 
 7184: : foo ( n1 n2 -- n )
 7185:   [ compile-+ ] ;
 7186: 1 2 foo .
 7187: @end example
 7188: 
 7189: This is equivalent to @code{: foo + ;} (@code{see foo} to check this).
 7190: What happens in this example?  @code{Postpone} compiles the compilation
 7191: semantics of @code{+} into @code{compile-+}; later the text interpreter
 7192: executes @code{compile-+} and thus the compilation semantics of +, which
 7193: compile (the execution semantics of) @code{+} into
 7194: @code{foo}.@footnote{A recent RFI answer requires that compiling words
 7195: should only be executed in compile state, so this example is not
 7196: guaranteed to work on all standard systems, but on any decent system it
 7197: will work.}
 7198: 
 7199: doc-postpone
 7200: doc-[compile]
 7201: 
 7202: Compiling words like @code{compile-+} are usually immediate (or similar)
 7203: so you do not have to switch to interpret state to execute them;
 7204: mopifying the last example accordingly produces:
 7205: 
 7206: @example
 7207: : [compile-+] ( compilation: --; interpretation: -- )
 7208:   \ compiled code: ( n1 n2 -- n )
 7209:   POSTPONE + ; immediate
 7210: 
 7211: : foo ( n1 n2 -- n )
 7212:   [compile-+] ;
 7213: 1 2 foo .
 7214: @end example
 7215: 
 7216: Immediate compiling words are similar to macros in other languages (in
 7217: particular, Lisp).  The important differences to macros in, e.g., C are:
 7218: 
 7219: @itemize @bullet
 7220: 
 7221: @item
 7222: You use the same language for defining and processing macros, not a
 7223: separate preprocessing language and processor.
 7224: 
 7225: @item
 7226: Consequently, the full power of Forth is available in macro definitions.
 7227: E.g., you can perform arbitrarily complex computations, or generate
 7228: different code conditionally or in a loop (e.g., @pxref{Advanced macros
 7229: Tutorial}).  This power is very useful when writing a parser generators
 7230: or other code-generating software.
 7231: 
 7232: @item
 7233: Macros defined using @code{postpone} etc. deal with the language at a
 7234: higher level than strings; name binding happens at macro definition
 7235: time, so you can avoid the pitfalls of name collisions that can happen
 7236: in C macros.  Of course, Forth is a liberal language and also allows to
 7237: shoot yourself in the foot with text-interpreted macros like
 7238: 
 7239: @example
 7240: : [compile-+] s" +" evaluate ; immediate
 7241: @end example
 7242: 
 7243: Apart from binding the name at macro use time, using @code{evaluate}
 7244: also makes your definition @code{state}-smart (@pxref{state-smartness}).
 7245: @end itemize
 7246: 
 7247: You may want the macro to compile a number into a word.  The word to do
 7248: it is @code{literal}, but you have to @code{postpone} it, so its
 7249: compilation semantics take effect when the macro is executed, not when
 7250: it is compiled:
 7251: 
 7252: @example
 7253: : [compile-5] ( -- ) \ compiled code: ( -- n )
 7254:   5 POSTPONE literal ; immediate
 7255: 
 7256: : foo [compile-5] ;
 7257: foo .
 7258: @end example
 7259: 
 7260: You may want to pass parameters to a macro, that the macro should
 7261: compile into the current definition.  If the parameter is a number, then
 7262: you can use @code{postpone literal} (similar for other values).
 7263: 
 7264: If you want to pass a word that is to be compiled, the usual way is to
 7265: pass an execution token and @code{compile,} it:
 7266: 
 7267: @example
 7268: : twice1 ( xt -- ) \ compiled code: ... -- ...
 7269:   dup compile, compile, ;
 7270: 
 7271: : 2+ ( n1 -- n2 )
 7272:   [ ' 1+ twice1 ] ;
 7273: @end example
 7274: 
 7275: doc-compile,
 7276: 
 7277: An alternative available in Gforth, that allows you to pass compile-only
 7278: words as parameters is to use the compilation token (@pxref{Compilation
 7279: token}).  The same example in this technique:
 7280: 
 7281: @example
 7282: : twice ( ... ct -- ... ) \ compiled code: ... -- ...
 7283:   2dup 2>r execute 2r> execute ;
 7284: 
 7285: : 2+ ( n1 -- n2 )
 7286:   [ comp' 1+ twice ] ;
 7287: @end example
 7288: 
 7289: In the example above @code{2>r} and @code{2r>} ensure that @code{twice}
 7290: works even if the executed compilation semantics has an effect on the
 7291: data stack.
 7292: 
 7293: You can also define complete definitions with these words; this provides
 7294: an alternative to using @code{does>} (@pxref{User-defined Defining
 7295: Words}).  E.g., instead of
 7296: 
 7297: @example
 7298: : curry+ ( n1 "name" -- )
 7299:     CREATE ,
 7300: DOES> ( n2 -- n1+n2 )
 7301:     @@ + ;
 7302: @end example
 7303: 
 7304: you could define
 7305: 
 7306: @example
 7307: : curry+ ( n1 "name" -- )
 7308:   \ name execution: ( n2 -- n1+n2 )
 7309:   >r : r> POSTPONE literal POSTPONE + POSTPONE ; ;
 7310: 
 7311: -3 curry+ 3-
 7312: see 3-
 7313: @end example
 7314: 
 7315: The sequence @code{>r : r>} is necessary, because @code{:} puts a
 7316: colon-sys on the data stack that makes everything below it unaccessible.
 7317: 
 7318: This way of writing defining words is sometimes more, sometimes less
 7319: convenient than using @code{does>} (@pxref{Advanced does> usage
 7320: example}).  One advantage of this method is that it can be optimized
 7321: better, because the compiler knows that the value compiled with
 7322: @code{literal} is fixed, whereas the data associated with a
 7323: @code{create}d word can be changed.
 7324: 
 7325: @c ----------------------------------------------------------
 7326: @node The Text Interpreter, The Input Stream, Compiling words, Words
 7327: @section  The Text Interpreter
 7328: @cindex interpreter - outer
 7329: @cindex text interpreter
 7330: @cindex outer interpreter
 7331: 
 7332: @c Should we really describe all these ugly details?  IMO the text
 7333: @c interpreter should be much cleaner, but that may not be possible within
 7334: @c ANS Forth. - anton
 7335: @c nac-> I wanted to explain how it works to show how you can exploit
 7336: @c it in your own programs. When I was writing a cross-compiler, figuring out
 7337: @c some of these gory details was very helpful to me. None of the textbooks
 7338: @c I've seen cover it, and the most modern Forth textbook -- Forth Inc's,
 7339: @c seems to positively avoid going into too much detail for some of
 7340: @c the internals.
 7341: 
 7342: @c anton: ok.  I wonder, though, if this is the right place; for some stuff
 7343: @c it is; for the ugly details, I would prefer another place.  I wonder
 7344: @c whether we should have a chapter before "Words" that describes some
 7345: @c basic concepts referred to in words, and a chapter after "Words" that
 7346: @c describes implementation details.
 7347: 
 7348: The text interpreter@footnote{This is an expanded version of the
 7349: material in @ref{Introducing the Text Interpreter}.} is an endless loop
 7350: that processes input from the current input device. It is also called
 7351: the outer interpreter, in contrast to the inner interpreter
 7352: (@pxref{Engine}) which executes the compiled Forth code on interpretive
 7353: implementations.
 7354: 
 7355: @cindex interpret state
 7356: @cindex compile state
 7357: The text interpreter operates in one of two states: @dfn{interpret
 7358: state} and @dfn{compile state}. The current state is defined by the
 7359: aptly-named variable @code{state}.
 7360: 
 7361: This section starts by describing how the text interpreter behaves when
 7362: it is in interpret state, processing input from the user input device --
 7363: the keyboard. This is the mode that a Forth system is in after it starts
 7364: up.
 7365: 
 7366: @cindex input buffer
 7367: @cindex terminal input buffer
 7368: The text interpreter works from an area of memory called the @dfn{input
 7369: buffer}@footnote{When the text interpreter is processing input from the
 7370: keyboard, this area of memory is called the @dfn{terminal input buffer}
 7371: (TIB) and is addressed by the (obsolescent) words @code{TIB} and
 7372: @code{#TIB}.}, which stores your keyboard input when you press the
 7373: @key{RET} key. Starting at the beginning of the input buffer, it skips
 7374: leading spaces (called @dfn{delimiters}) then parses a string (a
 7375: sequence of non-space characters) until it reaches either a space
 7376: character or the end of the buffer. Having parsed a string, it makes two
 7377: attempts to process it:
 7378: 
 7379: @cindex dictionary
 7380: @itemize @bullet
 7381: @item
 7382: It looks for the string in a @dfn{dictionary} of definitions. If the
 7383: string is found, the string names a @dfn{definition} (also known as a
 7384: @dfn{word}) and the dictionary search returns information that allows
 7385: the text interpreter to perform the word's @dfn{interpretation
 7386: semantics}. In most cases, this simply means that the word will be
 7387: executed.
 7388: @item
 7389: If the string is not found in the dictionary, the text interpreter
 7390: attempts to treat it as a number, using the rules described in
 7391: @ref{Number Conversion}. If the string represents a legal number in the
 7392: current radix, the number is pushed onto a parameter stack (the data
 7393: stack for integers, the floating-point stack for floating-point
 7394: numbers).
 7395: @end itemize
 7396: 
 7397: If both attempts fail, or if the word is found in the dictionary but has
 7398: no interpretation semantics@footnote{This happens if the word was
 7399: defined as @code{COMPILE-ONLY}.} the text interpreter discards the
 7400: remainder of the input buffer, issues an error message and waits for
 7401: more input. If one of the attempts succeeds, the text interpreter
 7402: repeats the parsing process until the whole of the input buffer has been
 7403: processed, at which point it prints the status message ``@code{ ok}''
 7404: and waits for more input.
 7405: 
 7406: @c anton: this should be in the input stream subsection (or below it)
 7407: 
 7408: @cindex parse area
 7409: The text interpreter keeps track of its position in the input buffer by
 7410: updating a variable called @code{>IN} (pronounced ``to-in''). The value
 7411: of @code{>IN} starts out as 0, indicating an offset of 0 from the start
 7412: of the input buffer. The region from offset @code{>IN @@} to the end of
 7413: the input buffer is called the @dfn{parse area}@footnote{In other words,
 7414: the text interpreter processes the contents of the input buffer by
 7415: parsing strings from the parse area until the parse area is empty.}.
 7416: This example shows how @code{>IN} changes as the text interpreter parses
 7417: the input buffer:
 7418: 
 7419: @example
 7420: : remaining >IN @@ SOURCE 2 PICK - -ROT + SWAP
 7421:   CR ." ->" TYPE ." <-" ; IMMEDIATE 
 7422: 
 7423: 1 2 3 remaining + remaining . 
 7424: 
 7425: : foo 1 2 3 remaining SWAP remaining ;
 7426: @end example
 7427: 
 7428: @noindent
 7429: The result is:
 7430: 
 7431: @example
 7432: ->+ remaining .<-
 7433: ->.<-5  ok
 7434: 
 7435: ->SWAP remaining ;-<
 7436: ->;<-  ok
 7437: @end example
 7438: 
 7439: @cindex parsing words
 7440: The value of @code{>IN} can also be modified by a word in the input
 7441: buffer that is executed by the text interpreter.  This means that a word
 7442: can ``trick'' the text interpreter into either skipping a section of the
 7443: input buffer@footnote{This is how parsing words work.} or into parsing a
 7444: section twice. For example:
 7445: 
 7446: @example
 7447: : lat ." <<foo>>" ;
 7448: : flat ." <<bar>>" >IN DUP @@ 3 - SWAP ! ;
 7449: @end example
 7450: 
 7451: @noindent
 7452: When @code{flat} is executed, this output is produced@footnote{Exercise
 7453: for the reader: what would happen if the @code{3} were replaced with
 7454: @code{4}?}:
 7455: 
 7456: @example
 7457: <<bar>><<foo>>
 7458: @end example
 7459: 
 7460: This technique can be used to work around some of the interoperability
 7461: problems of parsing words.  Of course, it's better to avoid parsing
 7462: words where possible.
 7463: 
 7464: @noindent
 7465: Two important notes about the behaviour of the text interpreter:
 7466: 
 7467: @itemize @bullet
 7468: @item
 7469: It processes each input string to completion before parsing additional
 7470: characters from the input buffer.
 7471: @item
 7472: It treats the input buffer as a read-only region (and so must your code).
 7473: @end itemize
 7474: 
 7475: @noindent
 7476: When the text interpreter is in compile state, its behaviour changes in
 7477: these ways:
 7478: 
 7479: @itemize @bullet
 7480: @item
 7481: If a parsed string is found in the dictionary, the text interpreter will
 7482: perform the word's @dfn{compilation semantics}. In most cases, this
 7483: simply means that the execution semantics of the word will be appended
 7484: to the current definition.
 7485: @item
 7486: When a number is encountered, it is compiled into the current definition
 7487: (as a literal) rather than being pushed onto a parameter stack.
 7488: @item
 7489: If an error occurs, @code{state} is modified to put the text interpreter
 7490: back into interpret state.
 7491: @item
 7492: Each time a line is entered from the keyboard, Gforth prints
 7493: ``@code{ compiled}'' rather than `` @code{ok}''.
 7494: @end itemize
 7495: 
 7496: @cindex text interpreter - input sources
 7497: When the text interpreter is using an input device other than the
 7498: keyboard, its behaviour changes in these ways:
 7499: 
 7500: @itemize @bullet
 7501: @item
 7502: When the parse area is empty, the text interpreter attempts to refill
 7503: the input buffer from the input source. When the input source is
 7504: exhausted, the input source is set back to the previous input source.
 7505: @item
 7506: It doesn't print out ``@code{ ok}'' or ``@code{ compiled}'' messages each
 7507: time the parse area is emptied.
 7508: @item
 7509: If an error occurs, the input source is set back to the user input
 7510: device.
 7511: @end itemize
 7512: 
 7513: You can read about this in more detail in @ref{Input Sources}.
 7514: 
 7515: doc->in
 7516: doc-source
 7517: 
 7518: doc-tib
 7519: doc-#tib
 7520: 
 7521: 
 7522: @menu
 7523: * Input Sources::               
 7524: * Number Conversion::           
 7525: * Interpret/Compile states::    
 7526: * Interpreter Directives::      
 7527: @end menu
 7528: 
 7529: @node Input Sources, Number Conversion, The Text Interpreter, The Text Interpreter
 7530: @subsection Input Sources
 7531: @cindex input sources
 7532: @cindex text interpreter - input sources
 7533: 
 7534: By default, the text interpreter processes input from the user input
 7535: device (the keyboard) when Forth starts up. The text interpreter can
 7536: process input from any of these sources:
 7537: 
 7538: @itemize @bullet
 7539: @item
 7540: The user input device -- the keyboard.
 7541: @item
 7542: A file, using the words described in @ref{Forth source files}.
 7543: @item
 7544: A block, using the words described in @ref{Blocks}.
 7545: @item
 7546: A text string, using @code{evaluate}.
 7547: @end itemize
 7548: 
 7549: A program can identify the current input device from the values of
 7550: @code{source-id} and @code{blk}.
 7551: 
 7552: 
 7553: doc-source-id
 7554: doc-blk
 7555: 
 7556: doc-save-input
 7557: doc-restore-input
 7558: 
 7559: doc-evaluate
 7560: doc-query
 7561: 
 7562: 
 7563: 
 7564: @node Number Conversion, Interpret/Compile states, Input Sources, The Text Interpreter
 7565: @subsection Number Conversion
 7566: @cindex number conversion
 7567: @cindex double-cell numbers, input format
 7568: @cindex input format for double-cell numbers
 7569: @cindex single-cell numbers, input format
 7570: @cindex input format for single-cell numbers
 7571: @cindex floating-point numbers, input format
 7572: @cindex input format for floating-point numbers
 7573: 
 7574: This section describes the rules that the text interpreter uses when it
 7575: tries to convert a string into a number.
 7576: 
 7577: Let <digit> represent any character that is a legal digit in the current
 7578: number base@footnote{For example, 0-9 when the number base is decimal or
 7579: 0-9, A-F when the number base is hexadecimal.}.
 7580: 
 7581: Let <decimal digit> represent any character in the range 0-9.
 7582: 
 7583: Let @{@i{a b}@} represent the @i{optional} presence of any of the characters
 7584: in the braces (@i{a} or @i{b} or neither).
 7585: 
 7586: Let * represent any number of instances of the previous character
 7587: (including none).
 7588: 
 7589: Let any other character represent itself.
 7590: 
 7591: @noindent
 7592: Now, the conversion rules are:
 7593: 
 7594: @itemize @bullet
 7595: @item
 7596: A string of the form <digit><digit>* is treated as a single-precision
 7597: (cell-sized) positive integer. Examples are 0 123 6784532 32343212343456 42
 7598: @item
 7599: A string of the form -<digit><digit>* is treated as a single-precision
 7600: (cell-sized) negative integer, and is represented using 2's-complement
 7601: arithmetic. Examples are -45 -5681 -0
 7602: @item
 7603: A string of the form <digit><digit>*.<digit>* is treated as a double-precision
 7604: (double-cell-sized) positive integer. Examples are 3465. 3.465 34.65
 7605: (all three of these represent the same number).
 7606: @item
 7607: A string of the form -<digit><digit>*.<digit>* is treated as a
 7608: double-precision (double-cell-sized) negative integer, and is
 7609: represented using 2's-complement arithmetic. Examples are -3465. -3.465
 7610: -34.65 (all three of these represent the same number).
 7611: @item
 7612: A string of the form @{+ -@}<decimal digit>@{.@}<decimal digit>*@{e
 7613: E@}@{+ -@}<decimal digit><decimal digit>* is treated as a floating-point
 7614: number. Examples are 1e 1e0 1.e 1.e0 +1e+0 (which all represent the same
 7615: number) +12.E-4
 7616: @end itemize
 7617: 
 7618: By default, the number base used for integer number conversion is given
 7619: by the contents of the variable @code{base}.  Note that a lot of
 7620: confusion can result from unexpected values of @code{base}.  If you
 7621: change @code{base} anywhere, make sure to save the old value and restore
 7622: it afterwards.  In general I recommend keeping @code{base} decimal, and
 7623: using the prefixes described below for the popular non-decimal bases.
 7624: 
 7625: doc-dpl
 7626: doc-base
 7627: doc-hex
 7628: doc-decimal
 7629: 
 7630: @cindex '-prefix for character strings
 7631: @cindex &-prefix for decimal numbers
 7632: @cindex #-prefix for decimal numbers
 7633: @cindex %-prefix for binary numbers
 7634: @cindex $-prefix for hexadecimal numbers
 7635: @cindex 0x-prefix for hexadecimal numbers
 7636: Gforth allows you to override the value of @code{base} by using a
 7637: prefix@footnote{Some Forth implementations provide a similar scheme by
 7638: implementing @code{$} etc. as parsing words that process the subsequent
 7639: number in the input stream and push it onto the stack. For example, see
 7640: @cite{Number Conversion and Literals}, by Wil Baden; Forth Dimensions
 7641: 20(3) pages 26--27. In such implementations, unlike in Gforth, a space
 7642: is required between the prefix and the number.} before the first digit
 7643: of an (integer) number. The following prefixes are supported:
 7644: 
 7645: @itemize @bullet
 7646: @item
 7647: @code{&} -- decimal
 7648: @item
 7649: @code{#} -- decimal
 7650: @item
 7651: @code{%} -- binary
 7652: @item
 7653: @code{$} -- hexadecimal
 7654: @item
 7655: @code{0x} -- hexadecimal, if base<33.
 7656: @item
 7657: @code{'} -- numeric value (e.g., ASCII code) of next character; an
 7658: optional @code{'} may be present after the character.
 7659: @end itemize
 7660: 
 7661: Here are some examples, with the equivalent decimal number shown after
 7662: in braces:
 7663: 
 7664: -$41 (-65), %1001101 (205), %1001.0001 (145 - a double-precision number),
 7665: 'A (65),
 7666: -'a' (-97),
 7667: &905 (905), $abc (2478), $ABC (2478).
 7668: 
 7669: @cindex number conversion - traps for the unwary
 7670: @noindent
 7671: Number conversion has a number of traps for the unwary:
 7672: 
 7673: @itemize @bullet
 7674: @item
 7675: You cannot determine the current number base using the code sequence
 7676: @code{base @@ .} -- the number base is always 10 in the current number
 7677: base. Instead, use something like @code{base @@ dec.}
 7678: @item
 7679: If the number base is set to a value greater than 14 (for example,
 7680: hexadecimal), the number 123E4 is ambiguous; the conversion rules allow
 7681: it to be intepreted as either a single-precision integer or a
 7682: floating-point number (Gforth treats it as an integer). The ambiguity
 7683: can be resolved by explicitly stating the sign of the mantissa and/or
 7684: exponent: 123E+4 or +123E4 -- if the number base is decimal, no
 7685: ambiguity arises; either representation will be treated as a
 7686: floating-point number.
 7687: @item
 7688: There is a word @code{bin} but it does @i{not} set the number base!
 7689: It is used to specify file types.
 7690: @item
 7691: ANS Forth requires the @code{.} of a double-precision number to be the
 7692: final character in the string.  Gforth allows the @code{.} to be
 7693: anywhere after the first digit.
 7694: @item
 7695: The number conversion process does not check for overflow.
 7696: @item
 7697: In an ANS Forth program @code{base} is required to be decimal when
 7698: converting floating-point numbers.  In Gforth, number conversion to
 7699: floating-point numbers always uses base &10, irrespective of the value
 7700: of @code{base}.
 7701: @end itemize
 7702: 
 7703: You can read numbers into your programs with the words described in
 7704: @ref{Input}.
 7705: 
 7706: @node Interpret/Compile states, Interpreter Directives, Number Conversion, The Text Interpreter
 7707: @subsection Interpret/Compile states
 7708: @cindex Interpret/Compile states
 7709: 
 7710: A standard program is not permitted to change @code{state}
 7711: explicitly. However, it can change @code{state} implicitly, using the
 7712: words @code{[} and @code{]}. When @code{[} is executed it switches
 7713: @code{state} to interpret state, and therefore the text interpreter
 7714: starts interpreting. When @code{]} is executed it switches @code{state}
 7715: to compile state and therefore the text interpreter starts
 7716: compiling. The most common usage for these words is for switching into
 7717: interpret state and back from within a colon definition; this technique
 7718: can be used to compile a literal (for an example, @pxref{Literals}) or
 7719: for conditional compilation (for an example, @pxref{Interpreter
 7720: Directives}).
 7721: 
 7722: 
 7723: @c This is a bad example: It's non-standard, and it's not necessary.
 7724: @c However, I can't think of a good example for switching into compile
 7725: @c state when there is no current word (@code{state}-smart words are not a
 7726: @c good reason).  So maybe we should use an example for switching into
 7727: @c interpret @code{state} in a colon def. - anton
 7728: @c nac-> I agree. I started out by putting in the example, then realised
 7729: @c that it was non-ANS, so wrote more words around it. I hope this
 7730: @c re-written version is acceptable to you. I do want to keep the example
 7731: @c as it is helpful for showing what is and what is not portable, particularly
 7732: @c where it outlaws a style in common use.
 7733: 
 7734: @c anton: it's more important to show what's portable.  After we have done
 7735: @c that, we can also show what's not.  In any case, I have written a
 7736: @c section Compiling Words which also deals with [ ].
 7737: 
 7738: @c  !! The following example does not work in Gforth 0.5.9 or later.
 7739: 
 7740: @c  @code{[} and @code{]} also give you the ability to switch into compile
 7741: @c  state and back, but we cannot think of any useful Standard application
 7742: @c  for this ability. Pre-ANS Forth textbooks have examples like this:
 7743: 
 7744: @c  @example
 7745: @c  : AA ." this is A" ;
 7746: @c  : BB ." this is B" ;
 7747: @c  : CC ." this is C" ;
 7748: 
 7749: @c  create table ] aa bb cc [
 7750: 
 7751: @c  : go ( n -- ) \ n is offset into table.. 0 for 1st entry
 7752: @c    cells table + @@ execute ;
 7753: @c  @end example
 7754: 
 7755: @c  This example builds a jump table; @code{0 go} will display ``@code{this
 7756: @c  is A}''. Using @code{[} and @code{]} in this example is equivalent to
 7757: @c  defining @code{table} like this:
 7758: 
 7759: @c  @example
 7760: @c  create table ' aa COMPILE, ' bb COMPILE, ' cc COMPILE,
 7761: @c  @end example
 7762: 
 7763: @c  The problem with this code is that the definition of @code{table} is not
 7764: @c  portable -- it @i{compile}s execution tokens into code space. Whilst it
 7765: @c  @i{may} work on systems where code space and data space co-incide, the
 7766: @c  Standard only allows data space to be assigned for a @code{CREATE}d
 7767: @c  word. In addition, the Standard only allows @code{@@} to access data
 7768: @c  space, whilst this example is using it to access code space. The only
 7769: @c  portable, Standard way to build this table is to build it in data space,
 7770: @c  like this:
 7771: 
 7772: @c  @example
 7773: @c  create table ' aa , ' bb , ' cc ,
 7774: @c  @end example
 7775: 
 7776: @c  doc-state
 7777: 
 7778: 
 7779: @node Interpreter Directives,  , Interpret/Compile states, The Text Interpreter
 7780: @subsection Interpreter Directives
 7781: @cindex interpreter directives
 7782: @cindex conditional compilation
 7783: 
 7784: These words are usually used in interpret state; typically to control
 7785: which parts of a source file are processed by the text
 7786: interpreter. There are only a few ANS Forth Standard words, but Gforth
 7787: supplements these with a rich set of immediate control structure words
 7788: to compensate for the fact that the non-immediate versions can only be
 7789: used in compile state (@pxref{Control Structures}). Typical usages:
 7790: 
 7791: @example
 7792: FALSE Constant HAVE-ASSEMBLER
 7793: .
 7794: .
 7795: HAVE-ASSEMBLER [IF]
 7796: : ASSEMBLER-FEATURE
 7797:   ...
 7798: ;
 7799: [ENDIF]
 7800: .
 7801: .
 7802: : SEE
 7803:   ... \ general-purpose SEE code
 7804:   [ HAVE-ASSEMBLER [IF] ]
 7805:   ... \ assembler-specific SEE code
 7806:   [ [ENDIF] ]
 7807: ;
 7808: @end example
 7809: 
 7810: 
 7811: doc-[IF]
 7812: doc-[ELSE]
 7813: doc-[THEN]
 7814: doc-[ENDIF]
 7815: 
 7816: doc-[IFDEF]
 7817: doc-[IFUNDEF]
 7818: 
 7819: doc-[?DO]
 7820: doc-[DO]
 7821: doc-[FOR]
 7822: doc-[LOOP]
 7823: doc-[+LOOP]
 7824: doc-[NEXT]
 7825: 
 7826: doc-[BEGIN]
 7827: doc-[UNTIL]
 7828: doc-[AGAIN]
 7829: doc-[WHILE]
 7830: doc-[REPEAT]
 7831: 
 7832: 
 7833: @c -------------------------------------------------------------
 7834: @node The Input Stream, Word Lists, The Text Interpreter, Words
 7835: @section The Input Stream
 7836: @cindex input stream
 7837: 
 7838: @c !! integrate this better with the "Text Interpreter" section
 7839: The text interpreter reads from the input stream, which can come from
 7840: several sources (@pxref{Input Sources}).  Some words, in particular
 7841: defining words, but also words like @code{'}, read parameters from the
 7842: input stream instead of from the stack.
 7843: 
 7844: Such words are called parsing words, because they parse the input
 7845: stream.  Parsing words are hard to use in other words, because it is
 7846: hard to pass program-generated parameters through the input stream.
 7847: They also usually have an unintuitive combination of interpretation and
 7848: compilation semantics when implemented naively, leading to various
 7849: approaches that try to produce a more intuitive behaviour
 7850: (@pxref{Combined words}).
 7851: 
 7852: It should be obvious by now that parsing words are a bad idea.  If you
 7853: want to implement a parsing word for convenience, also provide a factor
 7854: of the word that does not parse, but takes the parameters on the stack.
 7855: To implement the parsing word on top if it, you can use the following
 7856: words:
 7857: 
 7858: @c anton: these belong in the input stream section
 7859: doc-parse
 7860: doc-parse-name
 7861: doc-parse-word
 7862: doc-name
 7863: doc-word
 7864: doc-\"-parse
 7865: doc-refill
 7866: 
 7867: Conversely, if you have the bad luck (or lack of foresight) to have to
 7868: deal with parsing words without having such factors, how do you pass a
 7869: string that is not in the input stream to it?
 7870: 
 7871: doc-execute-parsing
 7872: 
 7873: A definition of this word in ANS Forth is provided in
 7874: @file{compat/execute-parsing.fs}.
 7875: 
 7876: If you want to run a parsing word on a file, the following word should
 7877: help:
 7878: 
 7879: doc-execute-parsing-file
 7880: 
 7881: @c -------------------------------------------------------------
 7882: @node Word Lists, Environmental Queries, The Input Stream, Words
 7883: @section Word Lists
 7884: @cindex word lists
 7885: @cindex header space
 7886: 
 7887: A wordlist is a list of named words; you can add new words and look up
 7888: words by name (and you can remove words in a restricted way with
 7889: markers).  Every named (and @code{reveal}ed) word is in one wordlist.
 7890: 
 7891: @cindex search order stack
 7892: The text interpreter searches the wordlists present in the search order
 7893: (a stack of wordlists), from the top to the bottom.  Within each
 7894: wordlist, the search starts conceptually at the newest word; i.e., if
 7895: two words in a wordlist have the same name, the newer word is found.
 7896: 
 7897: @cindex compilation word list
 7898: New words are added to the @dfn{compilation wordlist} (aka current
 7899: wordlist).
 7900: 
 7901: @cindex wid
 7902: A word list is identified by a cell-sized word list identifier (@i{wid})
 7903: in much the same way as a file is identified by a file handle. The
 7904: numerical value of the wid has no (portable) meaning, and might change
 7905: from session to session.
 7906: 
 7907: The ANS Forth ``Search order'' word set is intended to provide a set of
 7908: low-level tools that allow various different schemes to be
 7909: implemented. Gforth also provides @code{vocabulary}, a traditional Forth
 7910: word.  @file{compat/vocabulary.fs} provides an implementation in ANS
 7911: Forth.
 7912: 
 7913: @comment TODO: locals section refers to here, saying that every word list (aka
 7914: @comment vocabulary) has its own methods for searching etc. Need to document that.
 7915: @c anton: but better in a separate subsection on wordlist internals
 7916: 
 7917: @comment TODO: document markers, reveal, tables, mappedwordlist
 7918: 
 7919: @comment the gforthman- prefix is used to pick out the true definition of a
 7920: @comment word from the source files, rather than some alias.
 7921: 
 7922: doc-forth-wordlist
 7923: doc-definitions
 7924: doc-get-current
 7925: doc-set-current
 7926: doc-get-order
 7927: doc---gforthman-set-order
 7928: doc-wordlist
 7929: doc-table
 7930: doc->order
 7931: doc-previous
 7932: doc-also
 7933: doc---gforthman-forth
 7934: doc-only
 7935: doc---gforthman-order
 7936: 
 7937: doc-find
 7938: doc-search-wordlist
 7939: 
 7940: doc-words
 7941: doc-vlist
 7942: @c doc-words-deferred
 7943: 
 7944: @c doc-mappedwordlist @c map-structure undefined, implemantation-specific
 7945: doc-root
 7946: doc-vocabulary
 7947: doc-seal
 7948: doc-vocs
 7949: doc-current
 7950: doc-context
 7951: 
 7952: 
 7953: @menu
 7954: * Vocabularies::                
 7955: * Why use word lists?::         
 7956: * Word list example::           
 7957: @end menu
 7958: 
 7959: @node Vocabularies, Why use word lists?, Word Lists, Word Lists
 7960: @subsection Vocabularies
 7961: @cindex Vocabularies, detailed explanation
 7962: 
 7963: Here is an example of creating and using a new wordlist using ANS
 7964: Forth words:
 7965: 
 7966: @example
 7967: wordlist constant my-new-words-wordlist
 7968: : my-new-words get-order nip my-new-words-wordlist swap set-order ;
 7969: 
 7970: \ add it to the search order
 7971: also my-new-words
 7972: 
 7973: \ alternatively, add it to the search order and make it
 7974: \ the compilation word list
 7975: also my-new-words definitions
 7976: \ type "order" to see the problem
 7977: @end example
 7978: 
 7979: The problem with this example is that @code{order} has no way to
 7980: associate the name @code{my-new-words} with the wid of the word list (in
 7981: Gforth, @code{order} and @code{vocs} will display @code{???}  for a wid
 7982: that has no associated name). There is no Standard way of associating a
 7983: name with a wid.
 7984: 
 7985: In Gforth, this example can be re-coded using @code{vocabulary}, which
 7986: associates a name with a wid:
 7987: 
 7988: @example
 7989: vocabulary my-new-words
 7990: 
 7991: \ add it to the search order
 7992: also my-new-words
 7993: 
 7994: \ alternatively, add it to the search order and make it
 7995: \ the compilation word list
 7996: my-new-words definitions
 7997: \ type "order" to see that the problem is solved
 7998: @end example
 7999: 
 8000: 
 8001: @node Why use word lists?, Word list example, Vocabularies, Word Lists
 8002: @subsection Why use word lists?
 8003: @cindex word lists - why use them?
 8004: 
 8005: Here are some reasons why people use wordlists:
 8006: 
 8007: @itemize @bullet
 8008: 
 8009: @c anton: Gforth's hashing implementation makes the search speed
 8010: @c independent from the number of words.  But it is linear with the number
 8011: @c of wordlists that have to be searched, so in effect using more wordlists
 8012: @c actually slows down compilation.
 8013: 
 8014: @c @item
 8015: @c To improve compilation speed by reducing the number of header space
 8016: @c entries that must be searched. This is achieved by creating a new
 8017: @c word list that contains all of the definitions that are used in the
 8018: @c definition of a Forth system but which would not usually be used by
 8019: @c programs running on that system. That word list would be on the search
 8020: @c list when the Forth system was compiled but would be removed from the
 8021: @c search list for normal operation. This can be a useful technique for
 8022: @c low-performance systems (for example, 8-bit processors in embedded
 8023: @c systems) but is unlikely to be necessary in high-performance desktop
 8024: @c systems.
 8025: 
 8026: @item
 8027: To prevent a set of words from being used outside the context in which
 8028: they are valid. Two classic examples of this are an integrated editor
 8029: (all of the edit commands are defined in a separate word list; the
 8030: search order is set to the editor word list when the editor is invoked;
 8031: the old search order is restored when the editor is terminated) and an
 8032: integrated assembler (the op-codes for the machine are defined in a
 8033: separate word list which is used when a @code{CODE} word is defined).
 8034: 
 8035: @item
 8036: To organize the words of an application or library into a user-visible
 8037: set (in @code{forth-wordlist} or some other common wordlist) and a set
 8038: of helper words used just for the implementation (hidden in a separate
 8039: wordlist).  This keeps @code{words}' output smaller, separates
 8040: implementation and interface, and reduces the chance of name conflicts
 8041: within the common wordlist.
 8042: 
 8043: @item
 8044: To prevent a name-space clash between multiple definitions with the same
 8045: name. For example, when building a cross-compiler you might have a word
 8046: @code{IF} that generates conditional code for your target system. By
 8047: placing this definition in a different word list you can control whether
 8048: the host system's @code{IF} or the target system's @code{IF} get used in
 8049: any particular context by controlling the order of the word lists on the
 8050: search order stack.
 8051: 
 8052: @end itemize
 8053: 
 8054: The downsides of using wordlists are:
 8055: 
 8056: @itemize
 8057: 
 8058: @item
 8059: Debugging becomes more cumbersome.
 8060: 
 8061: @item
 8062: Name conflicts worked around with wordlists are still there, and you
 8063: have to arrange the search order carefully to get the desired results;
 8064: if you forget to do that, you get hard-to-find errors (as in any case
 8065: where you read the code differently from the compiler; @code{see} can
 8066: help seeing which of several possible words the name resolves to in such
 8067: cases).  @code{See} displays just the name of the words, not what
 8068: wordlist they belong to, so it might be misleading.  Using unique names
 8069: is a better approach to avoid name conflicts.
 8070: 
 8071: @item
 8072: You have to explicitly undo any changes to the search order.  In many
 8073: cases it would be more convenient if this happened implicitly.  Gforth
 8074: currently does not provide such a feature, but it may do so in the
 8075: future.
 8076: @end itemize
 8077: 
 8078: 
 8079: @node Word list example,  , Why use word lists?, Word Lists
 8080: @subsection Word list example
 8081: @cindex word lists - example
 8082: 
 8083: The following example is from the
 8084: @uref{http://www.complang.tuwien.ac.at/forth/garbage-collection.zip,
 8085: garbage collector} and uses wordlists to separate public words from
 8086: helper words:
 8087: 
 8088: @example
 8089: get-current ( wid )
 8090: vocabulary garbage-collector also garbage-collector definitions
 8091: ... \ define helper words
 8092: ( wid ) set-current \ restore original (i.e., public) compilation wordlist
 8093: ... \ define the public (i.e., API) words
 8094:     \ they can refer to the helper words
 8095: previous \ restore original search order (helper words become invisible)
 8096: @end example
 8097: 
 8098: @c -------------------------------------------------------------
 8099: @node Environmental Queries, Files, Word Lists, Words
 8100: @section Environmental Queries
 8101: @cindex environmental queries
 8102: 
 8103: ANS Forth introduced the idea of ``environmental queries'' as a way
 8104: for a program running on a system to determine certain characteristics of the system.
 8105: The Standard specifies a number of strings that might be recognised by a system.
 8106: 
 8107: The Standard requires that the header space used for environmental queries
 8108: be distinct from the header space used for definitions.
 8109: 
 8110: Typically, environmental queries are supported by creating a set of
 8111: definitions in a word list that is @i{only} used during environmental
 8112: queries; that is what Gforth does. There is no Standard way of adding
 8113: definitions to the set of recognised environmental queries, but any
 8114: implementation that supports the loading of optional word sets must have
 8115: some mechanism for doing this (after loading the word set, the
 8116: associated environmental query string must return @code{true}). In
 8117: Gforth, the word list used to honour environmental queries can be
 8118: manipulated just like any other word list.
 8119: 
 8120: 
 8121: doc-environment?
 8122: doc-environment-wordlist
 8123: 
 8124: doc-gforth
 8125: doc-os-class
 8126: 
 8127: 
 8128: Note that, whilst the documentation for (e.g.) @code{gforth} shows it
 8129: returning two items on the stack, querying it using @code{environment?}
 8130: will return an additional item; the @code{true} flag that shows that the
 8131: string was recognised.
 8132: 
 8133: @comment TODO Document the standard strings or note where they are documented herein
 8134: 
 8135: Here are some examples of using environmental queries:
 8136: 
 8137: @example
 8138: s" address-unit-bits" environment? 0=
 8139: [IF]
 8140:      cr .( environmental attribute address-units-bits unknown... ) cr
 8141: [ELSE]
 8142:      drop \ ensure balanced stack effect
 8143: [THEN]
 8144: 
 8145: \ this might occur in the prelude of a standard program that uses THROW
 8146: s" exception" environment? [IF]
 8147:    0= [IF]
 8148:       : throw abort" exception thrown" ;
 8149:    [THEN]
 8150: [ELSE] \ we don't know, so make sure
 8151:    : throw abort" exception thrown" ;
 8152: [THEN]
 8153: 
 8154: s" gforth" environment? [IF] .( Gforth version ) TYPE
 8155:                         [ELSE] .( Not Gforth..) [THEN]
 8156: 
 8157: \ a program using v*
 8158: s" gforth" environment? [IF]
 8159:   s" 0.5.0" compare 0< [IF] \ v* is a primitive since 0.5.0
 8160:    : v* ( f_addr1 nstride1 f_addr2 nstride2 ucount -- r )
 8161:      >r swap 2swap swap 0e r> 0 ?DO
 8162:        dup f@ over + 2swap dup f@ f* f+ over + 2swap
 8163:      LOOP
 8164:      2drop 2drop ; 
 8165:   [THEN]
 8166: [ELSE] \ 
 8167:   : v* ( f_addr1 nstride1 f_addr2 nstride2 ucount -- r )
 8168:   ...
 8169: [THEN]
 8170: @end example
 8171: 
 8172: Here is an example of adding a definition to the environment word list:
 8173: 
 8174: @example
 8175: get-current environment-wordlist set-current
 8176: true constant block
 8177: true constant block-ext
 8178: set-current
 8179: @end example
 8180: 
 8181: You can see what definitions are in the environment word list like this:
 8182: 
 8183: @example
 8184: environment-wordlist >order words previous
 8185: @end example
 8186: 
 8187: 
 8188: @c -------------------------------------------------------------
 8189: @node Files, Blocks, Environmental Queries, Words
 8190: @section Files
 8191: @cindex files
 8192: @cindex I/O - file-handling
 8193: 
 8194: Gforth provides facilities for accessing files that are stored in the
 8195: host operating system's file-system. Files that are processed by Gforth
 8196: can be divided into two categories:
 8197: 
 8198: @itemize @bullet
 8199: @item
 8200: Files that are processed by the Text Interpreter (@dfn{Forth source files}).
 8201: @item
 8202: Files that are processed by some other program (@dfn{general files}).
 8203: @end itemize
 8204: 
 8205: @menu
 8206: * Forth source files::          
 8207: * General files::               
 8208: * Search Paths::                
 8209: @end menu
 8210: 
 8211: @c -------------------------------------------------------------
 8212: @node Forth source files, General files, Files, Files
 8213: @subsection Forth source files
 8214: @cindex including files
 8215: @cindex Forth source files
 8216: 
 8217: The simplest way to interpret the contents of a file is to use one of
 8218: these two formats:
 8219: 
 8220: @example
 8221: include mysource.fs
 8222: s" mysource.fs" included
 8223: @end example
 8224: 
 8225: You usually want to include a file only if it is not included already
 8226: (by, say, another source file). In that case, you can use one of these
 8227: three formats:
 8228: 
 8229: @example
 8230: require mysource.fs
 8231: needs mysource.fs
 8232: s" mysource.fs" required
 8233: @end example
 8234: 
 8235: @cindex stack effect of included files
 8236: @cindex including files, stack effect
 8237: It is good practice to write your source files such that interpreting them
 8238: does not change the stack. Source files designed in this way can be used with
 8239: @code{required} and friends without complications. For example:
 8240: 
 8241: @example
 8242: 1024 require foo.fs drop
 8243: @end example
 8244: 
 8245: Here you want to pass the argument 1024 (e.g., a buffer size) to
 8246: @file{foo.fs}.  Interpreting @file{foo.fs} has the stack effect ( n -- n
 8247: ), which allows its use with @code{require}.  Of course with such
 8248: parameters to required files, you have to ensure that the first
 8249: @code{require} fits for all uses (i.e., @code{require} it early in the
 8250: master load file).
 8251: 
 8252: doc-include-file
 8253: doc-included
 8254: doc-included?
 8255: doc-include
 8256: doc-required
 8257: doc-require
 8258: doc-needs
 8259: @c doc-init-included-files @c internal
 8260: doc-sourcefilename
 8261: doc-sourceline#
 8262: 
 8263: A definition in ANS Forth for @code{required} is provided in
 8264: @file{compat/required.fs}.
 8265: 
 8266: @c -------------------------------------------------------------
 8267: @node General files, Search Paths, Forth source files, Files
 8268: @subsection General files
 8269: @cindex general files
 8270: @cindex file-handling
 8271: 
 8272: Files are opened/created by name and type. The following file access
 8273: methods (FAMs) are recognised:
 8274: 
 8275: @cindex fam (file access method)
 8276: doc-r/o
 8277: doc-r/w
 8278: doc-w/o
 8279: doc-bin
 8280: 
 8281: 
 8282: When a file is opened/created, it returns a file identifier,
 8283: @i{wfileid} that is used for all other file commands. All file
 8284: commands also return a status value, @i{wior}, that is 0 for a
 8285: successful operation and an implementation-defined non-zero value in the
 8286: case of an error.
 8287: 
 8288: 
 8289: doc-open-file
 8290: doc-create-file
 8291: 
 8292: doc-close-file
 8293: doc-delete-file
 8294: doc-rename-file
 8295: doc-read-file
 8296: doc-read-line
 8297: doc-write-file
 8298: doc-write-line
 8299: doc-emit-file
 8300: doc-flush-file
 8301: 
 8302: doc-file-status
 8303: doc-file-position
 8304: doc-reposition-file
 8305: doc-file-size
 8306: doc-resize-file
 8307: 
 8308: doc-slurp-file
 8309: doc-slurp-fid
 8310: doc-stdin
 8311: doc-stdout
 8312: doc-stderr
 8313: 
 8314: @c ---------------------------------------------------------
 8315: @node Search Paths,  , General files, Files
 8316: @subsection Search Paths
 8317: @cindex path for @code{included}
 8318: @cindex file search path
 8319: @cindex @code{include} search path
 8320: @cindex search path for files
 8321: 
 8322: If you specify an absolute filename (i.e., a filename starting with
 8323: @file{/} or @file{~}, or with @file{:} in the second position (as in
 8324: @samp{C:...})) for @code{included} and friends, that file is included
 8325: just as you would expect.
 8326: 
 8327: If the filename starts with @file{./}, this refers to the directory that
 8328: the present file was @code{included} from.  This allows files to include
 8329: other files relative to their own position (irrespective of the current
 8330: working directory or the absolute position).  This feature is essential
 8331: for libraries consisting of several files, where a file may include
 8332: other files from the library.  It corresponds to @code{#include "..."}
 8333: in C. If the current input source is not a file, @file{.} refers to the
 8334: directory of the innermost file being included, or, if there is no file
 8335: being included, to the current working directory.
 8336: 
 8337: For relative filenames (not starting with @file{./}), Gforth uses a
 8338: search path similar to Forth's search order (@pxref{Word Lists}). It
 8339: tries to find the given filename in the directories present in the path,
 8340: and includes the first one it finds. There are separate search paths for
 8341: Forth source files and general files.  If the search path contains the
 8342: directory @file{.}, this refers to the directory of the current file, or
 8343: the working directory, as if the file had been specified with @file{./}.
 8344: 
 8345: Use @file{~+} to refer to the current working directory (as in the
 8346: @code{bash}).
 8347: 
 8348: @c anton: fold the following subsubsections into this subsection?
 8349: 
 8350: @menu
 8351: * Source Search Paths::         
 8352: * General Search Paths::        
 8353: @end menu
 8354: 
 8355: @c ---------------------------------------------------------
 8356: @node Source Search Paths, General Search Paths, Search Paths, Search Paths
 8357: @subsubsection Source Search Paths
 8358: @cindex search path control, source files
 8359: 
 8360: The search path is initialized when you start Gforth (@pxref{Invoking
 8361: Gforth}). You can display it and change it using @code{fpath} in
 8362: combination with the general path handling words.
 8363: 
 8364: doc-fpath
 8365: @c the functionality of the following words is easily available through
 8366: @c   fpath and the general path words.  The may go away.
 8367: @c doc-.fpath
 8368: @c doc-fpath+
 8369: @c doc-fpath=
 8370: @c doc-open-fpath-file
 8371: 
 8372: @noindent
 8373: Here is an example of using @code{fpath} and @code{require}:
 8374: 
 8375: @example
 8376: fpath path= /usr/lib/forth/|./
 8377: require timer.fs
 8378: @end example
 8379: 
 8380: 
 8381: @c ---------------------------------------------------------
 8382: @node General Search Paths,  , Source Search Paths, Search Paths
 8383: @subsubsection General Search Paths
 8384: @cindex search path control, source files
 8385: 
 8386: Your application may need to search files in several directories, like
 8387: @code{included} does. To facilitate this, Gforth allows you to define
 8388: and use your own search paths, by providing generic equivalents of the
 8389: Forth search path words:
 8390: 
 8391: doc-open-path-file
 8392: doc-path-allot
 8393: doc-clear-path
 8394: doc-also-path
 8395: doc-.path
 8396: doc-path+
 8397: doc-path=
 8398: 
 8399: @c anton: better define a word for it, say "path-allot ( ucount -- path-addr )
 8400: 
 8401: Here's an example of creating an empty search path:
 8402: @c
 8403: @example
 8404: create mypath 500 path-allot \ maximum length 500 chars (is checked)
 8405: @end example
 8406: 
 8407: @c -------------------------------------------------------------
 8408: @node Blocks, Other I/O, Files, Words
 8409: @section Blocks
 8410: @cindex I/O - blocks
 8411: @cindex blocks
 8412: 
 8413: When you run Gforth on a modern desk-top computer, it runs under the
 8414: control of an operating system which provides certain services.  One of
 8415: these services is @var{file services}, which allows Forth source code
 8416: and data to be stored in files and read into Gforth (@pxref{Files}).
 8417: 
 8418: Traditionally, Forth has been an important programming language on
 8419: systems where it has interfaced directly to the underlying hardware with
 8420: no intervening operating system. Forth provides a mechanism, called
 8421: @dfn{blocks}, for accessing mass storage on such systems.
 8422: 
 8423: A block is a 1024-byte data area, which can be used to hold data or
 8424: Forth source code. No structure is imposed on the contents of the
 8425: block. A block is identified by its number; blocks are numbered
 8426: contiguously from 1 to an implementation-defined maximum.
 8427: 
 8428: A typical system that used blocks but no operating system might use a
 8429: single floppy-disk drive for mass storage, with the disks formatted to
 8430: provide 256-byte sectors. Blocks would be implemented by assigning the
 8431: first four sectors of the disk to block 1, the second four sectors to
 8432: block 2 and so on, up to the limit of the capacity of the disk. The disk
 8433: would not contain any file system information, just the set of blocks.
 8434: 
 8435: @cindex blocks file
 8436: On systems that do provide file services, blocks are typically
 8437: implemented by storing a sequence of blocks within a single @dfn{blocks
 8438: file}.  The size of the blocks file will be an exact multiple of 1024
 8439: bytes, corresponding to the number of blocks it contains. This is the
 8440: mechanism that Gforth uses.
 8441: 
 8442: @cindex @file{blocks.fb}
 8443: Only one blocks file can be open at a time. If you use block words without
 8444: having specified a blocks file, Gforth defaults to the blocks file
 8445: @file{blocks.fb}. Gforth uses the Forth search path when attempting to
 8446: locate a blocks file (@pxref{Source Search Paths}).
 8447: 
 8448: @cindex block buffers
 8449: When you read and write blocks under program control, Gforth uses a
 8450: number of @dfn{block buffers} as intermediate storage. These buffers are
 8451: not used when you use @code{load} to interpret the contents of a block.
 8452: 
 8453: The behaviour of the block buffers is analagous to that of a cache.
 8454: Each block buffer has three states:
 8455: 
 8456: @itemize @bullet
 8457: @item
 8458: Unassigned
 8459: @item
 8460: Assigned-clean
 8461: @item
 8462: Assigned-dirty
 8463: @end itemize
 8464: 
 8465: Initially, all block buffers are @i{unassigned}. In order to access a
 8466: block, the block (specified by its block number) must be assigned to a
 8467: block buffer.
 8468: 
 8469: The assignment of a block to a block buffer is performed by @code{block}
 8470: or @code{buffer}. Use @code{block} when you wish to modify the existing
 8471: contents of a block. Use @code{buffer} when you don't care about the
 8472: existing contents of the block@footnote{The ANS Forth definition of
 8473: @code{buffer} is intended not to cause disk I/O; if the data associated
 8474: with the particular block is already stored in a block buffer due to an
 8475: earlier @code{block} command, @code{buffer} will return that block
 8476: buffer and the existing contents of the block will be
 8477: available. Otherwise, @code{buffer} will simply assign a new, empty
 8478: block buffer for the block.}.
 8479: 
 8480: Once a block has been assigned to a block buffer using @code{block} or
 8481: @code{buffer}, that block buffer becomes the @i{current block
 8482: buffer}. Data may only be manipulated (read or written) within the
 8483: current block buffer.
 8484: 
 8485: When the contents of the current block buffer has been modified it is
 8486: necessary, @emph{before calling @code{block} or @code{buffer} again}, to
 8487: either abandon the changes (by doing nothing) or mark the block as
 8488: changed (assigned-dirty), using @code{update}. Using @code{update} does
 8489: not change the blocks file; it simply changes a block buffer's state to
 8490: @i{assigned-dirty}.  The block will be written implicitly when it's
 8491: buffer is needed for another block, or explicitly by @code{flush} or
 8492: @code{save-buffers}.
 8493: 
 8494: word @code{Flush} writes all @i{assigned-dirty} blocks back to the
 8495: blocks file on disk. Leaving Gforth with @code{bye} also performs a
 8496: @code{flush}.
 8497: 
 8498: In Gforth, @code{block} and @code{buffer} use a @i{direct-mapped}
 8499: algorithm to assign a block buffer to a block. That means that any
 8500: particular block can only be assigned to one specific block buffer,
 8501: called (for the particular operation) the @i{victim buffer}. If the
 8502: victim buffer is @i{unassigned} or @i{assigned-clean} it is allocated to
 8503: the new block immediately. If it is @i{assigned-dirty} its current
 8504: contents are written back to the blocks file on disk before it is
 8505: allocated to the new block.
 8506: 
 8507: Although no structure is imposed on the contents of a block, it is
 8508: traditional to display the contents as 16 lines each of 64 characters.  A
 8509: block provides a single, continuous stream of input (for example, it
 8510: acts as a single parse area) -- there are no end-of-line characters
 8511: within a block, and no end-of-file character at the end of a
 8512: block. There are two consequences of this:
 8513: 
 8514: @itemize @bullet
 8515: @item
 8516: The last character of one line wraps straight into the first character
 8517: of the following line
 8518: @item
 8519: The word @code{\} -- comment to end of line -- requires special
 8520: treatment; in the context of a block it causes all characters until the
 8521: end of the current 64-character ``line'' to be ignored.
 8522: @end itemize
 8523: 
 8524: In Gforth, when you use @code{block} with a non-existent block number,
 8525: the current blocks file will be extended to the appropriate size and the
 8526: block buffer will be initialised with spaces.
 8527: 
 8528: Gforth includes a simple block editor (type @code{use blocked.fb 0 list}
 8529: for details) but doesn't encourage the use of blocks; the mechanism is
 8530: only provided for backward compatibility -- ANS Forth requires blocks to
 8531: be available when files are.
 8532: 
 8533: Common techniques that are used when working with blocks include:
 8534: 
 8535: @itemize @bullet
 8536: @item
 8537: A screen editor that allows you to edit blocks without leaving the Forth
 8538: environment.
 8539: @item
 8540: Shadow screens; where every code block has an associated block
 8541: containing comments (for example: code in odd block numbers, comments in
 8542: even block numbers). Typically, the block editor provides a convenient
 8543: mechanism to toggle between code and comments.
 8544: @item
 8545: Load blocks; a single block (typically block 1) contains a number of
 8546: @code{thru} commands which @code{load} the whole of the application.
 8547: @end itemize
 8548: 
 8549: See Frank Sergeant's Pygmy Forth to see just how well blocks can be
 8550: integrated into a Forth programming environment.
 8551: 
 8552: @comment TODO what about errors on open-blocks?
 8553: 
 8554: doc-open-blocks
 8555: doc-use
 8556: doc-block-offset
 8557: doc-get-block-fid
 8558: doc-block-position
 8559: 
 8560: doc-list
 8561: doc-scr
 8562: 
 8563: doc---gforthman-block
 8564: doc-buffer
 8565: 
 8566: doc-empty-buffers
 8567: doc-empty-buffer
 8568: doc-update
 8569: doc-updated?
 8570: doc-save-buffers
 8571: doc-save-buffer
 8572: doc-flush
 8573: 
 8574: doc-load
 8575: doc-thru
 8576: doc-+load
 8577: doc-+thru
 8578: doc---gforthman--->
 8579: doc-block-included
 8580: 
 8581: 
 8582: @c -------------------------------------------------------------
 8583: @node Other I/O, OS command line arguments, Blocks, Words
 8584: @section Other I/O
 8585: @cindex I/O - keyboard and display
 8586: 
 8587: @menu
 8588: * Simple numeric output::       Predefined formats
 8589: * Formatted numeric output::    Formatted (pictured) output
 8590: * String Formats::              How Forth stores strings in memory
 8591: * Displaying characters and strings::  Other stuff
 8592: * Input::                       Input
 8593: * Pipes::                       How to create your own pipes
 8594: * Xchars and Unicode::          Non-ASCII characters
 8595: @end menu
 8596: 
 8597: @node Simple numeric output, Formatted numeric output, Other I/O, Other I/O
 8598: @subsection Simple numeric output
 8599: @cindex numeric output - simple/free-format
 8600: 
 8601: The simplest output functions are those that display numbers from the
 8602: data or floating-point stacks. Floating-point output is always displayed
 8603: using base 10. Numbers displayed from the data stack use the value stored
 8604: in @code{base}.
 8605: 
 8606: 
 8607: doc-.
 8608: doc-dec.
 8609: doc-hex.
 8610: doc-u.
 8611: doc-.r
 8612: doc-u.r
 8613: doc-d.
 8614: doc-ud.
 8615: doc-d.r
 8616: doc-ud.r
 8617: doc-f.
 8618: doc-fe.
 8619: doc-fs.
 8620: doc-f.rdp
 8621: 
 8622: Examples of printing the number 1234.5678E23 in the different floating-point output
 8623: formats are shown below:
 8624: 
 8625: @example
 8626: f. 123456779999999000000000000.
 8627: fe. 123.456779999999E24
 8628: fs. 1.23456779999999E26
 8629: @end example
 8630: 
 8631: 
 8632: @node Formatted numeric output, String Formats, Simple numeric output, Other I/O
 8633: @subsection Formatted numeric output
 8634: @cindex formatted numeric output
 8635: @cindex pictured numeric output
 8636: @cindex numeric output - formatted
 8637: 
 8638: Forth traditionally uses a technique called @dfn{pictured numeric
 8639: output} for formatted printing of integers.  In this technique, digits
 8640: are extracted from the number (using the current output radix defined by
 8641: @code{base}), converted to ASCII codes and appended to a string that is
 8642: built in a scratch-pad area of memory (@pxref{core-idef,
 8643: Implementation-defined options, Implementation-defined
 8644: options}). Arbitrary characters can be appended to the string during the
 8645: extraction process. The completed string is specified by an address
 8646: and length and can be manipulated (@code{TYPE}ed, copied, modified)
 8647: under program control.
 8648: 
 8649: All of the integer output words described in the previous section
 8650: (@pxref{Simple numeric output}) are implemented in Gforth using pictured
 8651: numeric output.
 8652: 
 8653: Three important things to remember about pictured numeric output:
 8654: 
 8655: @itemize @bullet
 8656: @item
 8657: It always operates on double-precision numbers; to display a
 8658: single-precision number, convert it first (for ways of doing this
 8659: @pxref{Double precision}).
 8660: @item
 8661: It always treats the double-precision number as though it were
 8662: unsigned. The examples below show ways of printing signed numbers.
 8663: @item
 8664: The string is built up from right to left; least significant digit first.
 8665: @end itemize
 8666: 
 8667: 
 8668: doc-<#
 8669: doc-<<#
 8670: doc-#
 8671: doc-#s
 8672: doc-hold
 8673: doc-sign
 8674: doc-#>
 8675: doc-#>>
 8676: 
 8677: doc-represent
 8678: doc-f>str-rdp
 8679: doc-f>buf-rdp
 8680: 
 8681: 
 8682: @noindent
 8683: Here are some examples of using pictured numeric output:
 8684: 
 8685: @example
 8686: : my-u. ( u -- )
 8687:   \ Simplest use of pns.. behaves like Standard u. 
 8688:   0              \ convert to unsigned double
 8689:   <<#            \ start conversion
 8690:   #s             \ convert all digits
 8691:   #>             \ complete conversion
 8692:   TYPE SPACE     \ display, with trailing space
 8693:   #>> ;          \ release hold area
 8694: 
 8695: : cents-only ( u -- )
 8696:   0              \ convert to unsigned double
 8697:   <<#            \ start conversion
 8698:   # #            \ convert two least-significant digits
 8699:   #>             \ complete conversion, discard other digits
 8700:   TYPE SPACE     \ display, with trailing space
 8701:   #>> ;          \ release hold area
 8702: 
 8703: : dollars-and-cents ( u -- )
 8704:   0              \ convert to unsigned double
 8705:   <<#            \ start conversion
 8706:   # #            \ convert two least-significant digits
 8707:   [char] . hold  \ insert decimal point
 8708:   #s             \ convert remaining digits
 8709:   [char] $ hold  \ append currency symbol
 8710:   #>             \ complete conversion
 8711:   TYPE SPACE     \ display, with trailing space
 8712:   #>> ;          \ release hold area
 8713: 
 8714: : my-. ( n -- )
 8715:   \ handling negatives.. behaves like Standard .
 8716:   s>d            \ convert to signed double
 8717:   swap over dabs \ leave sign byte followed by unsigned double
 8718:   <<#            \ start conversion
 8719:   #s             \ convert all digits
 8720:   rot sign       \ get at sign byte, append "-" if needed
 8721:   #>             \ complete conversion
 8722:   TYPE SPACE     \ display, with trailing space
 8723:   #>> ;          \ release hold area
 8724: 
 8725: : account. ( n -- )
 8726:   \ accountants don't like minus signs, they use parentheses
 8727:   \ for negative numbers
 8728:   s>d            \ convert to signed double
 8729:   swap over dabs \ leave sign byte followed by unsigned double
 8730:   <<#            \ start conversion
 8731:   2 pick         \ get copy of sign byte
 8732:   0< IF [char] ) hold THEN \ right-most character of output
 8733:   #s             \ convert all digits
 8734:   rot            \ get at sign byte
 8735:   0< IF [char] ( hold THEN
 8736:   #>             \ complete conversion
 8737:   TYPE SPACE     \ display, with trailing space
 8738:   #>> ;          \ release hold area
 8739: 
 8740: @end example
 8741: 
 8742: Here are some examples of using these words:
 8743: 
 8744: @example
 8745: 1 my-u. 1
 8746: hex -1 my-u. decimal FFFFFFFF
 8747: 1 cents-only 01
 8748: 1234 cents-only 34
 8749: 2 dollars-and-cents $0.02
 8750: 1234 dollars-and-cents $12.34
 8751: 123 my-. 123
 8752: -123 my. -123
 8753: 123 account. 123
 8754: -456 account. (456)
 8755: @end example
 8756: 
 8757: 
 8758: @node String Formats, Displaying characters and strings, Formatted numeric output, Other I/O
 8759: @subsection String Formats
 8760: @cindex strings - see character strings
 8761: @cindex character strings - formats
 8762: @cindex I/O - see character strings
 8763: @cindex counted strings
 8764: 
 8765: @c anton: this does not really belong here; maybe the memory section,
 8766: @c  or the principles chapter
 8767: 
 8768: Forth commonly uses two different methods for representing character
 8769: strings:
 8770: 
 8771: @itemize @bullet
 8772: @item
 8773: @cindex address of counted string
 8774: @cindex counted string
 8775: As a @dfn{counted string}, represented by a @i{c-addr}. The char
 8776: addressed by @i{c-addr} contains a character-count, @i{n}, of the
 8777: string and the string occupies the subsequent @i{n} char addresses in
 8778: memory.
 8779: @item
 8780: As cell pair on the stack; @i{c-addr u}, where @i{u} is the length
 8781: of the string in characters, and @i{c-addr} is the address of the
 8782: first byte of the string.
 8783: @end itemize
 8784: 
 8785: ANS Forth encourages the use of the second format when representing
 8786: strings.
 8787: 
 8788: 
 8789: doc-count
 8790: 
 8791: 
 8792: For words that move, copy and search for strings see @ref{Memory
 8793: Blocks}. For words that display characters and strings see
 8794: @ref{Displaying characters and strings}.
 8795: 
 8796: @node Displaying characters and strings, Input, String Formats, Other I/O
 8797: @subsection Displaying characters and strings
 8798: @cindex characters - compiling and displaying
 8799: @cindex character strings - compiling and displaying
 8800: 
 8801: This section starts with a glossary of Forth words and ends with a set
 8802: of examples.
 8803: 
 8804: 
 8805: doc-bl
 8806: doc-space
 8807: doc-spaces
 8808: doc-emit
 8809: doc-toupper
 8810: doc-."
 8811: doc-.(
 8812: doc-.\"
 8813: doc-type
 8814: doc-typewhite
 8815: doc-cr
 8816: @cindex cursor control
 8817: doc-at-xy
 8818: doc-page
 8819: doc-s"
 8820: doc-s\"
 8821: doc-c"
 8822: doc-char
 8823: doc-[char]
 8824: 
 8825: 
 8826: @noindent
 8827: As an example, consider the following text, stored in a file @file{test.fs}:
 8828: 
 8829: @example
 8830: .( text-1)
 8831: : my-word
 8832:   ." text-2" cr
 8833:   .( text-3)
 8834: ;
 8835: 
 8836: ." text-4"
 8837: 
 8838: : my-char
 8839:   [char] ALPHABET emit
 8840:   char emit
 8841: ;
 8842: @end example
 8843: 
 8844: When you load this code into Gforth, the following output is generated:
 8845: 
 8846: @example
 8847: @kbd{include test.fs @key{RET}} text-1text-3text-4 ok
 8848: @end example
 8849: 
 8850: @itemize @bullet
 8851: @item
 8852: Messages @code{text-1} and @code{text-3} are displayed because @code{.(} 
 8853: is an immediate word; it behaves in the same way whether it is used inside
 8854: or outside a colon definition.
 8855: @item
 8856: Message @code{text-4} is displayed because of Gforth's added interpretation
 8857: semantics for @code{."}.
 8858: @item
 8859: Message @code{text-2} is @i{not} displayed, because the text interpreter
 8860: performs the compilation semantics for @code{."} within the definition of
 8861: @code{my-word}.
 8862: @end itemize
 8863: 
 8864: Here are some examples of executing @code{my-word} and @code{my-char}:
 8865: 
 8866: @example
 8867: @kbd{my-word @key{RET}} text-2
 8868:  ok
 8869: @kbd{my-char fred @key{RET}} Af ok
 8870: @kbd{my-char jim @key{RET}} Aj ok
 8871: @end example
 8872: 
 8873: @itemize @bullet
 8874: @item
 8875: Message @code{text-2} is displayed because of the run-time behaviour of
 8876: @code{."}.
 8877: @item
 8878: @code{[char]} compiles the ``A'' from ``ALPHABET'' and puts its display code
 8879: on the stack at run-time. @code{emit} always displays the character
 8880: when @code{my-char} is executed.
 8881: @item
 8882: @code{char} parses a string at run-time and the second @code{emit} displays
 8883: the first character of the string.
 8884: @item
 8885: If you type @code{see my-char} you can see that @code{[char]} discarded
 8886: the text ``LPHABET'' and only compiled the display code for ``A'' into the
 8887: definition of @code{my-char}.
 8888: @end itemize
 8889: 
 8890: 
 8891: 
 8892: @node Input, Pipes, Displaying characters and strings, Other I/O
 8893: @subsection Input
 8894: @cindex input
 8895: @cindex I/O - see input
 8896: @cindex parsing a string
 8897: 
 8898: For ways of storing character strings in memory see @ref{String Formats}.
 8899: 
 8900: @comment TODO examples for >number >float accept key key? pad parse word refill
 8901: @comment then index them
 8902: 
 8903: 
 8904: doc-key
 8905: doc-key?
 8906: doc-ekey
 8907: doc-ekey>char
 8908: doc-ekey?
 8909: 
 8910: Gforth recognizes various keys available on ANSI terminals (in MS-DOS
 8911: you need the ANSI.SYS driver to get that behaviour).  These are the
 8912: keyboard events produced by various common keys:
 8913: 
 8914: doc-k-left
 8915: doc-k-right
 8916: doc-k-up	
 8917: doc-k-down	
 8918: doc-k-home	
 8919: doc-k-end	
 8920: doc-k-prior
 8921: doc-k-next
 8922: doc-k-insert
 8923: doc-k-delete
 8924: 
 8925: The function keys (aka keypad keys) are:
 8926: 
 8927: doc-k1
 8928: doc-k2
 8929: doc-k3
 8930: doc-k4
 8931: doc-k5
 8932: doc-k6
 8933: doc-k7
 8934: doc-k8
 8935: doc-k9
 8936: doc-k10
 8937: doc-k11
 8938: doc-k12
 8939: 
 8940: Note that K11 and K12 are not as widely available.  The shifted
 8941: function keys are also not very widely available:
 8942: 
 8943: doc-s-k8
 8944: doc-s-k1
 8945: doc-s-k2
 8946: doc-s-k3
 8947: doc-s-k4
 8948: doc-s-k5
 8949: doc-s-k6
 8950: doc-s-k7
 8951: doc-s-k8
 8952: doc-s-k9
 8953: doc-s-k10
 8954: doc-s-k11
 8955: doc-s-k12
 8956: 
 8957: Words for inputting one line from the keyboard:
 8958: 
 8959: doc-accept
 8960: doc-edit-line
 8961: 
 8962: Conversion words:
 8963: 
 8964: doc-s>number?
 8965: doc-s>unumber?
 8966: doc->number
 8967: doc->float
 8968: 
 8969: 
 8970: @comment obsolescent words..
 8971: Obsolescent input and conversion words:
 8972: 
 8973: doc-convert
 8974: doc-expect
 8975: doc-span
 8976: 
 8977: 
 8978: @node Pipes, Xchars and Unicode, Input, Other I/O
 8979: @subsection Pipes
 8980: @cindex pipes, creating your own
 8981: 
 8982: In addition to using Gforth in pipes created by other processes
 8983: (@pxref{Gforth in pipes}), you can create your own pipe with
 8984: @code{open-pipe}, and read from or write to it.
 8985: 
 8986: doc-open-pipe
 8987: doc-close-pipe
 8988: 
 8989: If you write to a pipe, Gforth can throw a @code{broken-pipe-error}; if
 8990: you don't catch this exception, Gforth will catch it and exit, usually
 8991: silently (@pxref{Gforth in pipes}).  Since you probably do not want
 8992: this, you should wrap a @code{catch} or @code{try} block around the code
 8993: from @code{open-pipe} to @code{close-pipe}, so you can deal with the
 8994: problem yourself, and then return to regular processing.
 8995: 
 8996: doc-broken-pipe-error
 8997: 
 8998: @node Xchars and Unicode, , Pipes, Other I/O
 8999: 
 9000: This chapter needs completion
 9001: 
 9002: @node OS command line arguments, Locals, Other I/O, Words
 9003: @section OS command line arguments
 9004: @cindex OS command line arguments
 9005: @cindex command line arguments, OS
 9006: @cindex arguments, OS command line
 9007: 
 9008: The usual way to pass arguments to Gforth programs on the command line
 9009: is via the @option{-e} option, e.g.
 9010: 
 9011: @example
 9012: gforth -e "123 456" foo.fs -e bye
 9013: @end example
 9014: 
 9015: However, you may want to interpret the command-line arguments directly.
 9016: In that case, you can access the (image-specific) command-line arguments
 9017: through @code{next-arg}:
 9018: 
 9019: doc-next-arg
 9020: 
 9021: Here's an example program @file{echo.fs} for @code{next-arg}:
 9022: 
 9023: @example
 9024: : echo ( -- )
 9025:     begin
 9026: 	next-arg 2dup 0 0 d<> while
 9027: 	    type space
 9028:     repeat
 9029:     2drop ;
 9030: 
 9031: echo cr bye
 9032: @end example
 9033: 
 9034: This can be invoked with
 9035: 
 9036: @example
 9037: gforth echo.fs hello world
 9038: @end example
 9039: 
 9040: and it will print
 9041: 
 9042: @example
 9043: hello world
 9044: @end example
 9045: 
 9046: The next lower level of dealing with the OS command line are the
 9047: following words:
 9048: 
 9049: doc-arg
 9050: doc-shift-args
 9051: 
 9052: Finally, at the lowest level Gforth provides the following words:
 9053: 
 9054: doc-argc
 9055: doc-argv
 9056: 
 9057: @c -------------------------------------------------------------
 9058: @node Locals, Structures, OS command line arguments, Words
 9059: @section Locals
 9060: @cindex locals
 9061: 
 9062: Local variables can make Forth programming more enjoyable and Forth
 9063: programs easier to read. Unfortunately, the locals of ANS Forth are
 9064: laden with restrictions. Therefore, we provide not only the ANS Forth
 9065: locals wordset, but also our own, more powerful locals wordset (we
 9066: implemented the ANS Forth locals wordset through our locals wordset).
 9067: 
 9068: The ideas in this section have also been published in M. Anton Ertl,
 9069: @cite{@uref{http://www.complang.tuwien.ac.at/papers/ertl94l.ps.gz,
 9070: Automatic Scoping of Local Variables}}, EuroForth '94.
 9071: 
 9072: @menu
 9073: * Gforth locals::               
 9074: * ANS Forth locals::            
 9075: @end menu
 9076: 
 9077: @node Gforth locals, ANS Forth locals, Locals, Locals
 9078: @subsection Gforth locals
 9079: @cindex Gforth locals
 9080: @cindex locals, Gforth style
 9081: 
 9082: Locals can be defined with
 9083: 
 9084: @example
 9085: @{ local1 local2 ... -- comment @}
 9086: @end example
 9087: or
 9088: @example
 9089: @{ local1 local2 ... @}
 9090: @end example
 9091: 
 9092: E.g.,
 9093: @example
 9094: : max @{ n1 n2 -- n3 @}
 9095:  n1 n2 > if
 9096:    n1
 9097:  else
 9098:    n2
 9099:  endif ;
 9100: @end example
 9101: 
 9102: The similarity of locals definitions with stack comments is intended. A
 9103: locals definition often replaces the stack comment of a word. The order
 9104: of the locals corresponds to the order in a stack comment and everything
 9105: after the @code{--} is really a comment.
 9106: 
 9107: This similarity has one disadvantage: It is too easy to confuse locals
 9108: declarations with stack comments, causing bugs and making them hard to
 9109: find. However, this problem can be avoided by appropriate coding
 9110: conventions: Do not use both notations in the same program. If you do,
 9111: they should be distinguished using additional means, e.g. by position.
 9112: 
 9113: @cindex types of locals
 9114: @cindex locals types
 9115: The name of the local may be preceded by a type specifier, e.g.,
 9116: @code{F:} for a floating point value:
 9117: 
 9118: @example
 9119: : CX* @{ F: Ar F: Ai F: Br F: Bi -- Cr Ci @}
 9120: \ complex multiplication
 9121:  Ar Br f* Ai Bi f* f-
 9122:  Ar Bi f* Ai Br f* f+ ;
 9123: @end example
 9124: 
 9125: @cindex flavours of locals
 9126: @cindex locals flavours
 9127: @cindex value-flavoured locals
 9128: @cindex variable-flavoured locals
 9129: Gforth currently supports cells (@code{W:}, @code{W^}), doubles
 9130: (@code{D:}, @code{D^}), floats (@code{F:}, @code{F^}) and characters
 9131: (@code{C:}, @code{C^}) in two flavours: a value-flavoured local (defined
 9132: with @code{W:}, @code{D:} etc.) produces its value and can be changed
 9133: with @code{TO}. A variable-flavoured local (defined with @code{W^} etc.)
 9134: produces its address (which becomes invalid when the variable's scope is
 9135: left). E.g., the standard word @code{emit} can be defined in terms of
 9136: @code{type} like this:
 9137: 
 9138: @example
 9139: : emit @{ C^ char* -- @}
 9140:     char* 1 type ;
 9141: @end example
 9142: 
 9143: @cindex default type of locals
 9144: @cindex locals, default type
 9145: A local without type specifier is a @code{W:} local. Both flavours of
 9146: locals are initialized with values from the data or FP stack.
 9147: 
 9148: Currently there is no way to define locals with user-defined data
 9149: structures, but we are working on it.
 9150: 
 9151: Gforth allows defining locals everywhere in a colon definition. This
 9152: poses the following questions:
 9153: 
 9154: @menu
 9155: * Where are locals visible by name?::  
 9156: * How long do locals live?::    
 9157: * Locals programming style::    
 9158: * Locals implementation::       
 9159: @end menu
 9160: 
 9161: @node Where are locals visible by name?, How long do locals live?, Gforth locals, Gforth locals
 9162: @subsubsection Where are locals visible by name?
 9163: @cindex locals visibility
 9164: @cindex visibility of locals
 9165: @cindex scope of locals
 9166: 
 9167: Basically, the answer is that locals are visible where you would expect
 9168: it in block-structured languages, and sometimes a little longer. If you
 9169: want to restrict the scope of a local, enclose its definition in
 9170: @code{SCOPE}...@code{ENDSCOPE}.
 9171: 
 9172: 
 9173: doc-scope
 9174: doc-endscope
 9175: 
 9176: 
 9177: These words behave like control structure words, so you can use them
 9178: with @code{CS-PICK} and @code{CS-ROLL} to restrict the scope in
 9179: arbitrary ways.
 9180: 
 9181: If you want a more exact answer to the visibility question, here's the
 9182: basic principle: A local is visible in all places that can only be
 9183: reached through the definition of the local@footnote{In compiler
 9184: construction terminology, all places dominated by the definition of the
 9185: local.}. In other words, it is not visible in places that can be reached
 9186: without going through the definition of the local. E.g., locals defined
 9187: in @code{IF}...@code{ENDIF} are visible until the @code{ENDIF}, locals
 9188: defined in @code{BEGIN}...@code{UNTIL} are visible after the
 9189: @code{UNTIL} (until, e.g., a subsequent @code{ENDSCOPE}).
 9190: 
 9191: The reasoning behind this solution is: We want to have the locals
 9192: visible as long as it is meaningful. The user can always make the
 9193: visibility shorter by using explicit scoping. In a place that can
 9194: only be reached through the definition of a local, the meaning of a
 9195: local name is clear. In other places it is not: How is the local
 9196: initialized at the control flow path that does not contain the
 9197: definition? Which local is meant, if the same name is defined twice in
 9198: two independent control flow paths?
 9199: 
 9200: This should be enough detail for nearly all users, so you can skip the
 9201: rest of this section. If you really must know all the gory details and
 9202: options, read on.
 9203: 
 9204: In order to implement this rule, the compiler has to know which places
 9205: are unreachable. It knows this automatically after @code{AHEAD},
 9206: @code{AGAIN}, @code{EXIT} and @code{LEAVE}; in other cases (e.g., after
 9207: most @code{THROW}s), you can use the word @code{UNREACHABLE} to tell the
 9208: compiler that the control flow never reaches that place. If
 9209: @code{UNREACHABLE} is not used where it could, the only consequence is
 9210: that the visibility of some locals is more limited than the rule above
 9211: says. If @code{UNREACHABLE} is used where it should not (i.e., if you
 9212: lie to the compiler), buggy code will be produced.
 9213: 
 9214: 
 9215: doc-unreachable
 9216: 
 9217: 
 9218: Another problem with this rule is that at @code{BEGIN}, the compiler
 9219: does not know which locals will be visible on the incoming
 9220: back-edge. All problems discussed in the following are due to this
 9221: ignorance of the compiler (we discuss the problems using @code{BEGIN}
 9222: loops as examples; the discussion also applies to @code{?DO} and other
 9223: loops). Perhaps the most insidious example is:
 9224: @example
 9225: AHEAD
 9226: BEGIN
 9227:   x
 9228: [ 1 CS-ROLL ] THEN
 9229:   @{ x @}
 9230:   ...
 9231: UNTIL
 9232: @end example
 9233: 
 9234: This should be legal according to the visibility rule. The use of
 9235: @code{x} can only be reached through the definition; but that appears
 9236: textually below the use.
 9237: 
 9238: From this example it is clear that the visibility rules cannot be fully
 9239: implemented without major headaches. Our implementation treats common
 9240: cases as advertised and the exceptions are treated in a safe way: The
 9241: compiler makes a reasonable guess about the locals visible after a
 9242: @code{BEGIN}; if it is too pessimistic, the
 9243: user will get a spurious error about the local not being defined; if the
 9244: compiler is too optimistic, it will notice this later and issue a
 9245: warning. In the case above the compiler would complain about @code{x}
 9246: being undefined at its use. You can see from the obscure examples in
 9247: this section that it takes quite unusual control structures to get the
 9248: compiler into trouble, and even then it will often do fine.
 9249: 
 9250: If the @code{BEGIN} is reachable from above, the most optimistic guess
 9251: is that all locals visible before the @code{BEGIN} will also be
 9252: visible after the @code{BEGIN}. This guess is valid for all loops that
 9253: are entered only through the @code{BEGIN}, in particular, for normal
 9254: @code{BEGIN}...@code{WHILE}...@code{REPEAT} and
 9255: @code{BEGIN}...@code{UNTIL} loops and it is implemented in our
 9256: compiler. When the branch to the @code{BEGIN} is finally generated by
 9257: @code{AGAIN} or @code{UNTIL}, the compiler checks the guess and
 9258: warns the user if it was too optimistic:
 9259: @example
 9260: IF
 9261:   @{ x @}
 9262: BEGIN
 9263:   \ x ? 
 9264: [ 1 cs-roll ] THEN
 9265:   ...
 9266: UNTIL
 9267: @end example
 9268: 
 9269: Here, @code{x} lives only until the @code{BEGIN}, but the compiler
 9270: optimistically assumes that it lives until the @code{THEN}. It notices
 9271: this difference when it compiles the @code{UNTIL} and issues a
 9272: warning. The user can avoid the warning, and make sure that @code{x}
 9273: is not used in the wrong area by using explicit scoping:
 9274: @example
 9275: IF
 9276:   SCOPE
 9277:   @{ x @}
 9278:   ENDSCOPE
 9279: BEGIN
 9280: [ 1 cs-roll ] THEN
 9281:   ...
 9282: UNTIL
 9283: @end example
 9284: 
 9285: Since the guess is optimistic, there will be no spurious error messages
 9286: about undefined locals.
 9287: 
 9288: If the @code{BEGIN} is not reachable from above (e.g., after
 9289: @code{AHEAD} or @code{EXIT}), the compiler cannot even make an
 9290: optimistic guess, as the locals visible after the @code{BEGIN} may be
 9291: defined later. Therefore, the compiler assumes that no locals are
 9292: visible after the @code{BEGIN}. However, the user can use
 9293: @code{ASSUME-LIVE} to make the compiler assume that the same locals are
 9294: visible at the BEGIN as at the point where the top control-flow stack
 9295: item was created.
 9296: 
 9297: 
 9298: doc-assume-live
 9299: 
 9300: 
 9301: @noindent
 9302: E.g.,
 9303: @example
 9304: @{ x @}
 9305: AHEAD
 9306: ASSUME-LIVE
 9307: BEGIN
 9308:   x
 9309: [ 1 CS-ROLL ] THEN
 9310:   ...
 9311: UNTIL
 9312: @end example
 9313: 
 9314: Other cases where the locals are defined before the @code{BEGIN} can be
 9315: handled by inserting an appropriate @code{CS-ROLL} before the
 9316: @code{ASSUME-LIVE} (and changing the control-flow stack manipulation
 9317: behind the @code{ASSUME-LIVE}).
 9318: 
 9319: Cases where locals are defined after the @code{BEGIN} (but should be
 9320: visible immediately after the @code{BEGIN}) can only be handled by
 9321: rearranging the loop. E.g., the ``most insidious'' example above can be
 9322: arranged into:
 9323: @example
 9324: BEGIN
 9325:   @{ x @}
 9326:   ... 0=
 9327: WHILE
 9328:   x
 9329: REPEAT
 9330: @end example
 9331: 
 9332: @node How long do locals live?, Locals programming style, Where are locals visible by name?, Gforth locals
 9333: @subsubsection How long do locals live?
 9334: @cindex locals lifetime
 9335: @cindex lifetime of locals
 9336: 
 9337: The right answer for the lifetime question would be: A local lives at
 9338: least as long as it can be accessed. For a value-flavoured local this
 9339: means: until the end of its visibility. However, a variable-flavoured
 9340: local could be accessed through its address far beyond its visibility
 9341: scope. Ultimately, this would mean that such locals would have to be
 9342: garbage collected. Since this entails un-Forth-like implementation
 9343: complexities, I adopted the same cowardly solution as some other
 9344: languages (e.g., C): The local lives only as long as it is visible;
 9345: afterwards its address is invalid (and programs that access it
 9346: afterwards are erroneous).
 9347: 
 9348: @node Locals programming style, Locals implementation, How long do locals live?, Gforth locals
 9349: @subsubsection Locals programming style
 9350: @cindex locals programming style
 9351: @cindex programming style, locals
 9352: 
 9353: The freedom to define locals anywhere has the potential to change
 9354: programming styles dramatically. In particular, the need to use the
 9355: return stack for intermediate storage vanishes. Moreover, all stack
 9356: manipulations (except @code{PICK}s and @code{ROLL}s with run-time
 9357: determined arguments) can be eliminated: If the stack items are in the
 9358: wrong order, just write a locals definition for all of them; then
 9359: write the items in the order you want.
 9360: 
 9361: This seems a little far-fetched and eliminating stack manipulations is
 9362: unlikely to become a conscious programming objective. Still, the number
 9363: of stack manipulations will be reduced dramatically if local variables
 9364: are used liberally (e.g., compare @code{max} (@pxref{Gforth locals}) with
 9365: a traditional implementation of @code{max}).
 9366: 
 9367: This shows one potential benefit of locals: making Forth programs more
 9368: readable. Of course, this benefit will only be realized if the
 9369: programmers continue to honour the principle of factoring instead of
 9370: using the added latitude to make the words longer.
 9371: 
 9372: @cindex single-assignment style for locals
 9373: Using @code{TO} can and should be avoided.  Without @code{TO},
 9374: every value-flavoured local has only a single assignment and many
 9375: advantages of functional languages apply to Forth. I.e., programs are
 9376: easier to analyse, to optimize and to read: It is clear from the
 9377: definition what the local stands for, it does not turn into something
 9378: different later.
 9379: 
 9380: E.g., a definition using @code{TO} might look like this:
 9381: @example
 9382: : strcmp @{ addr1 u1 addr2 u2 -- n @}
 9383:  u1 u2 min 0
 9384:  ?do
 9385:    addr1 c@@ addr2 c@@ -
 9386:    ?dup-if
 9387:      unloop exit
 9388:    then
 9389:    addr1 char+ TO addr1
 9390:    addr2 char+ TO addr2
 9391:  loop
 9392:  u1 u2 - ;
 9393: @end example
 9394: Here, @code{TO} is used to update @code{addr1} and @code{addr2} at
 9395: every loop iteration. @code{strcmp} is a typical example of the
 9396: readability problems of using @code{TO}. When you start reading
 9397: @code{strcmp}, you think that @code{addr1} refers to the start of the
 9398: string. Only near the end of the loop you realize that it is something
 9399: else.
 9400: 
 9401: This can be avoided by defining two locals at the start of the loop that
 9402: are initialized with the right value for the current iteration.
 9403: @example
 9404: : strcmp @{ addr1 u1 addr2 u2 -- n @}
 9405:  addr1 addr2
 9406:  u1 u2 min 0 
 9407:  ?do @{ s1 s2 @}
 9408:    s1 c@@ s2 c@@ -
 9409:    ?dup-if
 9410:      unloop exit
 9411:    then
 9412:    s1 char+ s2 char+
 9413:  loop
 9414:  2drop
 9415:  u1 u2 - ;
 9416: @end example
 9417: Here it is clear from the start that @code{s1} has a different value
 9418: in every loop iteration.
 9419: 
 9420: @node Locals implementation,  , Locals programming style, Gforth locals
 9421: @subsubsection Locals implementation
 9422: @cindex locals implementation
 9423: @cindex implementation of locals
 9424: 
 9425: @cindex locals stack
 9426: Gforth uses an extra locals stack. The most compelling reason for
 9427: this is that the return stack is not float-aligned; using an extra stack
 9428: also eliminates the problems and restrictions of using the return stack
 9429: as locals stack. Like the other stacks, the locals stack grows toward
 9430: lower addresses. A few primitives allow an efficient implementation:
 9431: 
 9432: 
 9433: doc-@local#
 9434: doc-f@local#
 9435: doc-laddr#
 9436: doc-lp+!#
 9437: doc-lp!
 9438: doc->l
 9439: doc-f>l
 9440: 
 9441: 
 9442: In addition to these primitives, some specializations of these
 9443: primitives for commonly occurring inline arguments are provided for
 9444: efficiency reasons, e.g., @code{@@local0} as specialization of
 9445: @code{@@local#} for the inline argument 0. The following compiling words
 9446: compile the right specialized version, or the general version, as
 9447: appropriate:
 9448: 
 9449: 
 9450: @c doc-compile-@local
 9451: @c doc-compile-f@local
 9452: doc-compile-lp+!
 9453: 
 9454: 
 9455: Combinations of conditional branches and @code{lp+!#} like
 9456: @code{?branch-lp+!#} (the locals pointer is only changed if the branch
 9457: is taken) are provided for efficiency and correctness in loops.
 9458: 
 9459: A special area in the dictionary space is reserved for keeping the
 9460: local variable names. @code{@{} switches the dictionary pointer to this
 9461: area and @code{@}} switches it back and generates the locals
 9462: initializing code. @code{W:} etc.@ are normal defining words. This
 9463: special area is cleared at the start of every colon definition.
 9464: 
 9465: @cindex word list for defining locals
 9466: A special feature of Gforth's dictionary is used to implement the
 9467: definition of locals without type specifiers: every word list (aka
 9468: vocabulary) has its own methods for searching
 9469: etc. (@pxref{Word Lists}). For the present purpose we defined a word list
 9470: with a special search method: When it is searched for a word, it
 9471: actually creates that word using @code{W:}. @code{@{} changes the search
 9472: order to first search the word list containing @code{@}}, @code{W:} etc.,
 9473: and then the word list for defining locals without type specifiers.
 9474: 
 9475: The lifetime rules support a stack discipline within a colon
 9476: definition: The lifetime of a local is either nested with other locals
 9477: lifetimes or it does not overlap them.
 9478: 
 9479: At @code{BEGIN}, @code{IF}, and @code{AHEAD} no code for locals stack
 9480: pointer manipulation is generated. Between control structure words
 9481: locals definitions can push locals onto the locals stack. @code{AGAIN}
 9482: is the simplest of the other three control flow words. It has to
 9483: restore the locals stack depth of the corresponding @code{BEGIN}
 9484: before branching. The code looks like this:
 9485: @format
 9486: @code{lp+!#} current-locals-size @minus{} dest-locals-size
 9487: @code{branch} <begin>
 9488: @end format
 9489: 
 9490: @code{UNTIL} is a little more complicated: If it branches back, it
 9491: must adjust the stack just like @code{AGAIN}. But if it falls through,
 9492: the locals stack must not be changed. The compiler generates the
 9493: following code:
 9494: @format
 9495: @code{?branch-lp+!#} <begin> current-locals-size @minus{} dest-locals-size
 9496: @end format
 9497: The locals stack pointer is only adjusted if the branch is taken.
 9498: 
 9499: @code{THEN} can produce somewhat inefficient code:
 9500: @format
 9501: @code{lp+!#} current-locals-size @minus{} orig-locals-size
 9502: <orig target>:
 9503: @code{lp+!#} orig-locals-size @minus{} new-locals-size
 9504: @end format
 9505: The second @code{lp+!#} adjusts the locals stack pointer from the
 9506: level at the @i{orig} point to the level after the @code{THEN}. The
 9507: first @code{lp+!#} adjusts the locals stack pointer from the current
 9508: level to the level at the orig point, so the complete effect is an
 9509: adjustment from the current level to the right level after the
 9510: @code{THEN}.
 9511: 
 9512: @cindex locals information on the control-flow stack
 9513: @cindex control-flow stack items, locals information
 9514: In a conventional Forth implementation a dest control-flow stack entry
 9515: is just the target address and an orig entry is just the address to be
 9516: patched. Our locals implementation adds a word list to every orig or dest
 9517: item. It is the list of locals visible (or assumed visible) at the point
 9518: described by the entry. Our implementation also adds a tag to identify
 9519: the kind of entry, in particular to differentiate between live and dead
 9520: (reachable and unreachable) orig entries.
 9521: 
 9522: A few unusual operations have to be performed on locals word lists:
 9523: 
 9524: 
 9525: doc-common-list
 9526: doc-sub-list?
 9527: doc-list-size
 9528: 
 9529: 
 9530: Several features of our locals word list implementation make these
 9531: operations easy to implement: The locals word lists are organised as
 9532: linked lists; the tails of these lists are shared, if the lists
 9533: contain some of the same locals; and the address of a name is greater
 9534: than the address of the names behind it in the list.
 9535: 
 9536: Another important implementation detail is the variable
 9537: @code{dead-code}. It is used by @code{BEGIN} and @code{THEN} to
 9538: determine if they can be reached directly or only through the branch
 9539: that they resolve. @code{dead-code} is set by @code{UNREACHABLE},
 9540: @code{AHEAD}, @code{EXIT} etc., and cleared at the start of a colon
 9541: definition, by @code{BEGIN} and usually by @code{THEN}.
 9542: 
 9543: Counted loops are similar to other loops in most respects, but
 9544: @code{LEAVE} requires special attention: It performs basically the same
 9545: service as @code{AHEAD}, but it does not create a control-flow stack
 9546: entry. Therefore the information has to be stored elsewhere;
 9547: traditionally, the information was stored in the target fields of the
 9548: branches created by the @code{LEAVE}s, by organizing these fields into a
 9549: linked list. Unfortunately, this clever trick does not provide enough
 9550: space for storing our extended control flow information. Therefore, we
 9551: introduce another stack, the leave stack. It contains the control-flow
 9552: stack entries for all unresolved @code{LEAVE}s.
 9553: 
 9554: Local names are kept until the end of the colon definition, even if
 9555: they are no longer visible in any control-flow path. In a few cases
 9556: this may lead to increased space needs for the locals name area, but
 9557: usually less than reclaiming this space would cost in code size.
 9558: 
 9559: 
 9560: @node ANS Forth locals,  , Gforth locals, Locals
 9561: @subsection ANS Forth locals
 9562: @cindex locals, ANS Forth style
 9563: 
 9564: The ANS Forth locals wordset does not define a syntax for locals, but
 9565: words that make it possible to define various syntaxes. One of the
 9566: possible syntaxes is a subset of the syntax we used in the Gforth locals
 9567: wordset, i.e.:
 9568: 
 9569: @example
 9570: @{ local1 local2 ... -- comment @}
 9571: @end example
 9572: @noindent
 9573: or
 9574: @example
 9575: @{ local1 local2 ... @}
 9576: @end example
 9577: 
 9578: The order of the locals corresponds to the order in a stack comment. The
 9579: restrictions are:
 9580: 
 9581: @itemize @bullet
 9582: @item
 9583: Locals can only be cell-sized values (no type specifiers are allowed).
 9584: @item
 9585: Locals can be defined only outside control structures.
 9586: @item
 9587: Locals can interfere with explicit usage of the return stack. For the
 9588: exact (and long) rules, see the standard. If you don't use return stack
 9589: accessing words in a definition using locals, you will be all right. The
 9590: purpose of this rule is to make locals implementation on the return
 9591: stack easier.
 9592: @item
 9593: The whole definition must be in one line.
 9594: @end itemize
 9595: 
 9596: Locals defined in ANS Forth behave like @code{VALUE}s
 9597: (@pxref{Values}). I.e., they are initialized from the stack. Using their
 9598: name produces their value. Their value can be changed using @code{TO}.
 9599: 
 9600: Since the syntax above is supported by Gforth directly, you need not do
 9601: anything to use it. If you want to port a program using this syntax to
 9602: another ANS Forth system, use @file{compat/anslocal.fs} to implement the
 9603: syntax on the other system.
 9604: 
 9605: Note that a syntax shown in the standard, section A.13 looks
 9606: similar, but is quite different in having the order of locals
 9607: reversed. Beware!
 9608: 
 9609: The ANS Forth locals wordset itself consists of one word:
 9610: 
 9611: doc-(local)
 9612: 
 9613: The ANS Forth locals extension wordset defines a syntax using
 9614: @code{locals|}, but it is so awful that we strongly recommend not to use
 9615: it. We have implemented this syntax to make porting to Gforth easy, but
 9616: do not document it here. The problem with this syntax is that the locals
 9617: are defined in an order reversed with respect to the standard stack
 9618: comment notation, making programs harder to read, and easier to misread
 9619: and miswrite. The only merit of this syntax is that it is easy to
 9620: implement using the ANS Forth locals wordset.
 9621: 
 9622: 
 9623: @c ----------------------------------------------------------
 9624: @node Structures, Object-oriented Forth, Locals, Words
 9625: @section  Structures
 9626: @cindex structures
 9627: @cindex records
 9628: 
 9629: This section presents the structure package that comes with Gforth. A
 9630: version of the package implemented in ANS Forth is available in
 9631: @file{compat/struct.fs}. This package was inspired by a posting on
 9632: comp.lang.forth in 1989 (unfortunately I don't remember, by whom;
 9633: possibly John Hayes). A version of this section has been published in
 9634: M. Anton Ertl,
 9635: @uref{http://www.complang.tuwien.ac.at/forth/objects/structs.html, Yet
 9636: Another Forth Structures Package}, Forth Dimensions 19(3), pages
 9637: 13--16. Marcel Hendrix provided helpful comments.
 9638: 
 9639: @menu
 9640: * Why explicit structure support?::  
 9641: * Structure Usage::             
 9642: * Structure Naming Convention::  
 9643: * Structure Implementation::    
 9644: * Structure Glossary::          
 9645: @end menu
 9646: 
 9647: @node Why explicit structure support?, Structure Usage, Structures, Structures
 9648: @subsection Why explicit structure support?
 9649: 
 9650: @cindex address arithmetic for structures
 9651: @cindex structures using address arithmetic
 9652: If we want to use a structure containing several fields, we could simply
 9653: reserve memory for it, and access the fields using address arithmetic
 9654: (@pxref{Address arithmetic}). As an example, consider a structure with
 9655: the following fields
 9656: 
 9657: @table @code
 9658: @item a
 9659: is a float
 9660: @item b
 9661: is a cell
 9662: @item c
 9663: is a float
 9664: @end table
 9665: 
 9666: Given the (float-aligned) base address of the structure we get the
 9667: address of the field
 9668: 
 9669: @table @code
 9670: @item a
 9671: without doing anything further.
 9672: @item b
 9673: with @code{float+}
 9674: @item c
 9675: with @code{float+ cell+ faligned}
 9676: @end table
 9677: 
 9678: It is easy to see that this can become quite tiring. 
 9679: 
 9680: Moreover, it is not very readable, because seeing a
 9681: @code{cell+} tells us neither which kind of structure is
 9682: accessed nor what field is accessed; we have to somehow infer the kind
 9683: of structure, and then look up in the documentation, which field of
 9684: that structure corresponds to that offset.
 9685: 
 9686: Finally, this kind of address arithmetic also causes maintenance
 9687: troubles: If you add or delete a field somewhere in the middle of the
 9688: structure, you have to find and change all computations for the fields
 9689: afterwards.
 9690: 
 9691: So, instead of using @code{cell+} and friends directly, how
 9692: about storing the offsets in constants:
 9693: 
 9694: @example
 9695: 0 constant a-offset
 9696: 0 float+ constant b-offset
 9697: 0 float+ cell+ faligned c-offset
 9698: @end example
 9699: 
 9700: Now we can get the address of field @code{x} with @code{x-offset
 9701: +}. This is much better in all respects. Of course, you still
 9702: have to change all later offset definitions if you add a field. You can
 9703: fix this by declaring the offsets in the following way:
 9704: 
 9705: @example
 9706: 0 constant a-offset
 9707: a-offset float+ constant b-offset
 9708: b-offset cell+ faligned constant c-offset
 9709: @end example
 9710: 
 9711: Since we always use the offsets with @code{+}, we could use a defining
 9712: word @code{cfield} that includes the @code{+} in the action of the
 9713: defined word:
 9714: 
 9715: @example
 9716: : cfield ( n "name" -- )
 9717:     create ,
 9718: does> ( name execution: addr1 -- addr2 )
 9719:     @@ + ;
 9720: 
 9721: 0 cfield a
 9722: 0 a float+ cfield b
 9723: 0 b cell+ faligned cfield c
 9724: @end example
 9725: 
 9726: Instead of @code{x-offset +}, we now simply write @code{x}.
 9727: 
 9728: The structure field words now can be used quite nicely. However,
 9729: their definition is still a bit cumbersome: We have to repeat the
 9730: name, the information about size and alignment is distributed before
 9731: and after the field definitions etc.  The structure package presented
 9732: here addresses these problems.
 9733: 
 9734: @node Structure Usage, Structure Naming Convention, Why explicit structure support?, Structures
 9735: @subsection Structure Usage
 9736: @cindex structure usage
 9737: 
 9738: @cindex @code{field} usage
 9739: @cindex @code{struct} usage
 9740: @cindex @code{end-struct} usage
 9741: You can define a structure for a (data-less) linked list with:
 9742: @example
 9743: struct
 9744:     cell% field list-next
 9745: end-struct list%
 9746: @end example
 9747: 
 9748: With the address of the list node on the stack, you can compute the
 9749: address of the field that contains the address of the next node with
 9750: @code{list-next}. E.g., you can determine the length of a list
 9751: with:
 9752: 
 9753: @example
 9754: : list-length ( list -- n )
 9755: \ "list" is a pointer to the first element of a linked list
 9756: \ "n" is the length of the list
 9757:     0 BEGIN ( list1 n1 )
 9758:         over
 9759:     WHILE ( list1 n1 )
 9760:         1+ swap list-next @@ swap
 9761:     REPEAT
 9762:     nip ;
 9763: @end example
 9764: 
 9765: You can reserve memory for a list node in the dictionary with
 9766: @code{list% %allot}, which leaves the address of the list node on the
 9767: stack. For the equivalent allocation on the heap you can use @code{list%
 9768: %alloc} (or, for an @code{allocate}-like stack effect (i.e., with ior),
 9769: use @code{list% %allocate}). You can get the the size of a list
 9770: node with @code{list% %size} and its alignment with @code{list%
 9771: %alignment}.
 9772: 
 9773: Note that in ANS Forth the body of a @code{create}d word is
 9774: @code{aligned} but not necessarily @code{faligned};
 9775: therefore, if you do a:
 9776: 
 9777: @example
 9778: create @emph{name} foo% %allot drop
 9779: @end example
 9780: 
 9781: @noindent
 9782: then the memory alloted for @code{foo%} is guaranteed to start at the
 9783: body of @code{@emph{name}} only if @code{foo%} contains only character,
 9784: cell and double fields.  Therefore, if your structure contains floats,
 9785: better use
 9786: 
 9787: @example
 9788: foo% %allot constant @emph{name}
 9789: @end example
 9790: 
 9791: @cindex structures containing structures
 9792: You can include a structure @code{foo%} as a field of
 9793: another structure, like this:
 9794: @example
 9795: struct
 9796: ...
 9797:     foo% field ...
 9798: ...
 9799: end-struct ...
 9800: @end example
 9801: 
 9802: @cindex structure extension
 9803: @cindex extended records
 9804: Instead of starting with an empty structure, you can extend an
 9805: existing structure. E.g., a plain linked list without data, as defined
 9806: above, is hardly useful; You can extend it to a linked list of integers,
 9807: like this:@footnote{This feature is also known as @emph{extended
 9808: records}. It is the main innovation in the Oberon language; in other
 9809: words, adding this feature to Modula-2 led Wirth to create a new
 9810: language, write a new compiler etc.  Adding this feature to Forth just
 9811: required a few lines of code.}
 9812: 
 9813: @example
 9814: list%
 9815:     cell% field intlist-int
 9816: end-struct intlist%
 9817: @end example
 9818: 
 9819: @code{intlist%} is a structure with two fields:
 9820: @code{list-next} and @code{intlist-int}.
 9821: 
 9822: @cindex structures containing arrays
 9823: You can specify an array type containing @emph{n} elements of
 9824: type @code{foo%} like this:
 9825: 
 9826: @example
 9827: foo% @emph{n} *
 9828: @end example
 9829: 
 9830: You can use this array type in any place where you can use a normal
 9831: type, e.g., when defining a @code{field}, or with
 9832: @code{%allot}.
 9833: 
 9834: @cindex first field optimization
 9835: The first field is at the base address of a structure and the word for
 9836: this field (e.g., @code{list-next}) actually does not change the address
 9837: on the stack. You may be tempted to leave it away in the interest of
 9838: run-time and space efficiency. This is not necessary, because the
 9839: structure package optimizes this case: If you compile a first-field
 9840: words, no code is generated. So, in the interest of readability and
 9841: maintainability you should include the word for the field when accessing
 9842: the field.
 9843: 
 9844: 
 9845: @node Structure Naming Convention, Structure Implementation, Structure Usage, Structures
 9846: @subsection Structure Naming Convention
 9847: @cindex structure naming convention
 9848: 
 9849: The field names that come to (my) mind are often quite generic, and,
 9850: if used, would cause frequent name clashes. E.g., many structures
 9851: probably contain a @code{counter} field. The structure names
 9852: that come to (my) mind are often also the logical choice for the names
 9853: of words that create such a structure.
 9854: 
 9855: Therefore, I have adopted the following naming conventions: 
 9856: 
 9857: @itemize @bullet
 9858: @cindex field naming convention
 9859: @item
 9860: The names of fields are of the form
 9861: @code{@emph{struct}-@emph{field}}, where
 9862: @code{@emph{struct}} is the basic name of the structure, and
 9863: @code{@emph{field}} is the basic name of the field. You can
 9864: think of field words as converting the (address of the)
 9865: structure into the (address of the) field.
 9866: 
 9867: @cindex structure naming convention
 9868: @item
 9869: The names of structures are of the form
 9870: @code{@emph{struct}%}, where
 9871: @code{@emph{struct}} is the basic name of the structure.
 9872: @end itemize
 9873: 
 9874: This naming convention does not work that well for fields of extended
 9875: structures; e.g., the integer list structure has a field
 9876: @code{intlist-int}, but has @code{list-next}, not
 9877: @code{intlist-next}.
 9878: 
 9879: @node Structure Implementation, Structure Glossary, Structure Naming Convention, Structures
 9880: @subsection Structure Implementation
 9881: @cindex structure implementation
 9882: @cindex implementation of structures
 9883: 
 9884: The central idea in the implementation is to pass the data about the
 9885: structure being built on the stack, not in some global
 9886: variable. Everything else falls into place naturally once this design
 9887: decision is made.
 9888: 
 9889: The type description on the stack is of the form @emph{align
 9890: size}. Keeping the size on the top-of-stack makes dealing with arrays
 9891: very simple.
 9892: 
 9893: @code{field} is a defining word that uses @code{Create}
 9894: and @code{DOES>}. The body of the field contains the offset
 9895: of the field, and the normal @code{DOES>} action is simply:
 9896: 
 9897: @example
 9898: @@ +
 9899: @end example
 9900: 
 9901: @noindent
 9902: i.e., add the offset to the address, giving the stack effect
 9903: @i{addr1 -- addr2} for a field.
 9904: 
 9905: @cindex first field optimization, implementation
 9906: This simple structure is slightly complicated by the optimization
 9907: for fields with offset 0, which requires a different
 9908: @code{DOES>}-part (because we cannot rely on there being
 9909: something on the stack if such a field is invoked during
 9910: compilation). Therefore, we put the different @code{DOES>}-parts
 9911: in separate words, and decide which one to invoke based on the
 9912: offset. For a zero offset, the field is basically a noop; it is
 9913: immediate, and therefore no code is generated when it is compiled.
 9914: 
 9915: @node Structure Glossary,  , Structure Implementation, Structures
 9916: @subsection Structure Glossary
 9917: @cindex structure glossary
 9918: 
 9919: 
 9920: doc-%align
 9921: doc-%alignment
 9922: doc-%alloc
 9923: doc-%allocate
 9924: doc-%allot
 9925: doc-cell%
 9926: doc-char%
 9927: doc-dfloat%
 9928: doc-double%
 9929: doc-end-struct
 9930: doc-field
 9931: doc-float%
 9932: doc-naligned
 9933: doc-sfloat%
 9934: doc-%size
 9935: doc-struct
 9936: 
 9937: 
 9938: @c -------------------------------------------------------------
 9939: @node Object-oriented Forth, Programming Tools, Structures, Words
 9940: @section Object-oriented Forth
 9941: 
 9942: Gforth comes with three packages for object-oriented programming:
 9943: @file{objects.fs}, @file{oof.fs}, and @file{mini-oof.fs}; none of them
 9944: is preloaded, so you have to @code{include} them before use. The most
 9945: important differences between these packages (and others) are discussed
 9946: in @ref{Comparison with other object models}. All packages are written
 9947: in ANS Forth and can be used with any other ANS Forth.
 9948: 
 9949: @menu
 9950: * Why object-oriented programming?::  
 9951: * Object-Oriented Terminology::  
 9952: * Objects::                     
 9953: * OOF::                         
 9954: * Mini-OOF::                    
 9955: * Comparison with other object models::  
 9956: @end menu
 9957: 
 9958: @c ----------------------------------------------------------------
 9959: @node Why object-oriented programming?, Object-Oriented Terminology, Object-oriented Forth, Object-oriented Forth
 9960: @subsection Why object-oriented programming?
 9961: @cindex object-oriented programming motivation
 9962: @cindex motivation for object-oriented programming
 9963: 
 9964: Often we have to deal with several data structures (@emph{objects}),
 9965: that have to be treated similarly in some respects, but differently in
 9966: others. Graphical objects are the textbook example: circles, triangles,
 9967: dinosaurs, icons, and others, and we may want to add more during program
 9968: development. We want to apply some operations to any graphical object,
 9969: e.g., @code{draw} for displaying it on the screen. However, @code{draw}
 9970: has to do something different for every kind of object.
 9971: @comment TODO add some other operations eg perimeter, area
 9972: @comment and tie in to concrete examples later..
 9973: 
 9974: We could implement @code{draw} as a big @code{CASE}
 9975: control structure that executes the appropriate code depending on the
 9976: kind of object to be drawn. This would be not be very elegant, and,
 9977: moreover, we would have to change @code{draw} every time we add
 9978: a new kind of graphical object (say, a spaceship).
 9979: 
 9980: What we would rather do is: When defining spaceships, we would tell
 9981: the system: ``Here's how you @code{draw} a spaceship; you figure
 9982: out the rest''.
 9983: 
 9984: This is the problem that all systems solve that (rightfully) call
 9985: themselves object-oriented; the object-oriented packages presented here
 9986: solve this problem (and not much else).
 9987: @comment TODO ?list properties of oo systems.. oo vs o-based?
 9988: 
 9989: @c ------------------------------------------------------------------------
 9990: @node Object-Oriented Terminology, Objects, Why object-oriented programming?, Object-oriented Forth
 9991: @subsection Object-Oriented Terminology
 9992: @cindex object-oriented terminology
 9993: @cindex terminology for object-oriented programming
 9994: 
 9995: This section is mainly for reference, so you don't have to understand
 9996: all of it right away.  The terminology is mainly Smalltalk-inspired.  In
 9997: short:
 9998: 
 9999: @table @emph
10000: @cindex class
10001: @item class
10002: a data structure definition with some extras.
10003: 
10004: @cindex object
10005: @item object
10006: an instance of the data structure described by the class definition.
10007: 
10008: @cindex instance variables
10009: @item instance variables
10010: fields of the data structure.
10011: 
10012: @cindex selector
10013: @cindex method selector
10014: @cindex virtual function
10015: @item selector
10016: (or @emph{method selector}) a word (e.g.,
10017: @code{draw}) that performs an operation on a variety of data
10018: structures (classes). A selector describes @emph{what} operation to
10019: perform. In C++ terminology: a (pure) virtual function.
10020: 
10021: @cindex method
10022: @item method
10023: the concrete definition that performs the operation
10024: described by the selector for a specific class. A method specifies
10025: @emph{how} the operation is performed for a specific class.
10026: 
10027: @cindex selector invocation
10028: @cindex message send
10029: @cindex invoking a selector
10030: @item selector invocation
10031: a call of a selector. One argument of the call (the TOS (top-of-stack))
10032: is used for determining which method is used. In Smalltalk terminology:
10033: a message (consisting of the selector and the other arguments) is sent
10034: to the object.
10035: 
10036: @cindex receiving object
10037: @item receiving object
10038: the object used for determining the method executed by a selector
10039: invocation. In the @file{objects.fs} model, it is the object that is on
10040: the TOS when the selector is invoked. (@emph{Receiving} comes from
10041: the Smalltalk @emph{message} terminology.)
10042: 
10043: @cindex child class
10044: @cindex parent class
10045: @cindex inheritance
10046: @item child class
10047: a class that has (@emph{inherits}) all properties (instance variables,
10048: selectors, methods) from a @emph{parent class}. In Smalltalk
10049: terminology: The subclass inherits from the superclass. In C++
10050: terminology: The derived class inherits from the base class.
10051: 
10052: @end table
10053: 
10054: @c If you wonder about the message sending terminology, it comes from
10055: @c a time when each object had it's own task and objects communicated via
10056: @c message passing; eventually the Smalltalk developers realized that
10057: @c they can do most things through simple (indirect) calls. They kept the
10058: @c terminology.
10059: 
10060: @c --------------------------------------------------------------
10061: @node Objects, OOF, Object-Oriented Terminology, Object-oriented Forth
10062: @subsection The @file{objects.fs} model
10063: @cindex objects
10064: @cindex object-oriented programming
10065: 
10066: @cindex @file{objects.fs}
10067: @cindex @file{oof.fs}
10068: 
10069: This section describes the @file{objects.fs} package. This material also
10070: has been published in M. Anton Ertl,
10071: @cite{@uref{http://www.complang.tuwien.ac.at/forth/objects/objects.html,
10072: Yet Another Forth Objects Package}}, Forth Dimensions 19(2), pages
10073: 37--43.
10074: @c McKewan's and Zsoter's packages
10075: 
10076: This section assumes that you have read @ref{Structures}.
10077: 
10078: The techniques on which this model is based have been used to implement
10079: the parser generator, Gray, and have also been used in Gforth for
10080: implementing the various flavours of word lists (hashed or not,
10081: case-sensitive or not, special-purpose word lists for locals etc.).
10082: 
10083: 
10084: @menu
10085: * Properties of the Objects model::  
10086: * Basic Objects Usage::         
10087: * The Objects base class::      
10088: * Creating objects::            
10089: * Object-Oriented Programming Style::  
10090: * Class Binding::               
10091: * Method conveniences::         
10092: * Classes and Scoping::         
10093: * Dividing classes::            
10094: * Object Interfaces::           
10095: * Objects Implementation::      
10096: * Objects Glossary::            
10097: @end menu
10098: 
10099: Marcel Hendrix provided helpful comments on this section.
10100: 
10101: @node Properties of the Objects model, Basic Objects Usage, Objects, Objects
10102: @subsubsection Properties of the @file{objects.fs} model
10103: @cindex @file{objects.fs} properties
10104: 
10105: @itemize @bullet
10106: @item
10107: It is straightforward to pass objects on the stack. Passing
10108: selectors on the stack is a little less convenient, but possible.
10109: 
10110: @item
10111: Objects are just data structures in memory, and are referenced by their
10112: address. You can create words for objects with normal defining words
10113: like @code{constant}. Likewise, there is no difference between instance
10114: variables that contain objects and those that contain other data.
10115: 
10116: @item
10117: Late binding is efficient and easy to use.
10118: 
10119: @item
10120: It avoids parsing, and thus avoids problems with state-smartness
10121: and reduced extensibility; for convenience there are a few parsing
10122: words, but they have non-parsing counterparts. There are also a few
10123: defining words that parse. This is hard to avoid, because all standard
10124: defining words parse (except @code{:noname}); however, such
10125: words are not as bad as many other parsing words, because they are not
10126: state-smart.
10127: 
10128: @item
10129: It does not try to incorporate everything. It does a few things and does
10130: them well (IMO). In particular, this model was not designed to support
10131: information hiding (although it has features that may help); you can use
10132: a separate package for achieving this.
10133: 
10134: @item
10135: It is layered; you don't have to learn and use all features to use this
10136: model. Only a few features are necessary (@pxref{Basic Objects Usage},
10137: @pxref{The Objects base class}, @pxref{Creating objects}.), the others
10138: are optional and independent of each other.
10139: 
10140: @item
10141: An implementation in ANS Forth is available.
10142: 
10143: @end itemize
10144: 
10145: 
10146: @node Basic Objects Usage, The Objects base class, Properties of the Objects model, Objects
10147: @subsubsection Basic @file{objects.fs} Usage
10148: @cindex basic objects usage
10149: @cindex objects, basic usage
10150: 
10151: You can define a class for graphical objects like this:
10152: 
10153: @cindex @code{class} usage
10154: @cindex @code{end-class} usage
10155: @cindex @code{selector} usage
10156: @example
10157: object class \ "object" is the parent class
10158:   selector draw ( x y graphical -- )
10159: end-class graphical
10160: @end example
10161: 
10162: This code defines a class @code{graphical} with an
10163: operation @code{draw}.  We can perform the operation
10164: @code{draw} on any @code{graphical} object, e.g.:
10165: 
10166: @example
10167: 100 100 t-rex draw
10168: @end example
10169: 
10170: @noindent
10171: where @code{t-rex} is a word (say, a constant) that produces a
10172: graphical object.
10173: 
10174: @comment TODO add a 2nd operation eg perimeter.. and use for
10175: @comment a concrete example
10176: 
10177: @cindex abstract class
10178: How do we create a graphical object? With the present definitions,
10179: we cannot create a useful graphical object. The class
10180: @code{graphical} describes graphical objects in general, but not
10181: any concrete graphical object type (C++ users would call it an
10182: @emph{abstract class}); e.g., there is no method for the selector
10183: @code{draw} in the class @code{graphical}.
10184: 
10185: For concrete graphical objects, we define child classes of the
10186: class @code{graphical}, e.g.:
10187: 
10188: @cindex @code{overrides} usage
10189: @cindex @code{field} usage in class definition
10190: @example
10191: graphical class \ "graphical" is the parent class
10192:   cell% field circle-radius
10193: 
10194: :noname ( x y circle -- )
10195:   circle-radius @@ draw-circle ;
10196: overrides draw
10197: 
10198: :noname ( n-radius circle -- )
10199:   circle-radius ! ;
10200: overrides construct
10201: 
10202: end-class circle
10203: @end example
10204: 
10205: Here we define a class @code{circle} as a child of @code{graphical},
10206: with field @code{circle-radius} (which behaves just like a field
10207: (@pxref{Structures}); it defines (using @code{overrides}) new methods
10208: for the selectors @code{draw} and @code{construct} (@code{construct} is
10209: defined in @code{object}, the parent class of @code{graphical}).
10210: 
10211: Now we can create a circle on the heap (i.e.,
10212: @code{allocate}d memory) with:
10213: 
10214: @cindex @code{heap-new} usage
10215: @example
10216: 50 circle heap-new constant my-circle
10217: @end example
10218: 
10219: @noindent
10220: @code{heap-new} invokes @code{construct}, thus
10221: initializing the field @code{circle-radius} with 50. We can draw
10222: this new circle at (100,100) with:
10223: 
10224: @example
10225: 100 100 my-circle draw
10226: @end example
10227: 
10228: @cindex selector invocation, restrictions
10229: @cindex class definition, restrictions
10230: Note: You can only invoke a selector if the object on the TOS
10231: (the receiving object) belongs to the class where the selector was
10232: defined or one of its descendents; e.g., you can invoke
10233: @code{draw} only for objects belonging to @code{graphical}
10234: or its descendents (e.g., @code{circle}).  Immediately before
10235: @code{end-class}, the search order has to be the same as
10236: immediately after @code{class}.
10237: 
10238: @node The Objects base class, Creating objects, Basic Objects Usage, Objects
10239: @subsubsection The @file{object.fs} base class
10240: @cindex @code{object} class
10241: 
10242: When you define a class, you have to specify a parent class.  So how do
10243: you start defining classes? There is one class available from the start:
10244: @code{object}. It is ancestor for all classes and so is the
10245: only class that has no parent. It has two selectors: @code{construct}
10246: and @code{print}.
10247: 
10248: @node Creating objects, Object-Oriented Programming Style, The Objects base class, Objects
10249: @subsubsection Creating objects
10250: @cindex creating objects
10251: @cindex object creation
10252: @cindex object allocation options
10253: 
10254: @cindex @code{heap-new} discussion
10255: @cindex @code{dict-new} discussion
10256: @cindex @code{construct} discussion
10257: You can create and initialize an object of a class on the heap with
10258: @code{heap-new} ( ... class -- object ) and in the dictionary
10259: (allocation with @code{allot}) with @code{dict-new} (
10260: ... class -- object ). Both words invoke @code{construct}, which
10261: consumes the stack items indicated by "..." above.
10262: 
10263: @cindex @code{init-object} discussion
10264: @cindex @code{class-inst-size} discussion
10265: If you want to allocate memory for an object yourself, you can get its
10266: alignment and size with @code{class-inst-size 2@@} ( class --
10267: align size ). Once you have memory for an object, you can initialize
10268: it with @code{init-object} ( ... class object -- );
10269: @code{construct} does only a part of the necessary work.
10270: 
10271: @node Object-Oriented Programming Style, Class Binding, Creating objects, Objects
10272: @subsubsection Object-Oriented Programming Style
10273: @cindex object-oriented programming style
10274: @cindex programming style, object-oriented
10275: 
10276: This section is not exhaustive.
10277: 
10278: @cindex stack effects of selectors
10279: @cindex selectors and stack effects
10280: In general, it is a good idea to ensure that all methods for the
10281: same selector have the same stack effect: when you invoke a selector,
10282: you often have no idea which method will be invoked, so, unless all
10283: methods have the same stack effect, you will not know the stack effect
10284: of the selector invocation.
10285: 
10286: One exception to this rule is methods for the selector
10287: @code{construct}. We know which method is invoked, because we
10288: specify the class to be constructed at the same place. Actually, I
10289: defined @code{construct} as a selector only to give the users a
10290: convenient way to specify initialization. The way it is used, a
10291: mechanism different from selector invocation would be more natural
10292: (but probably would take more code and more space to explain).
10293: 
10294: @node Class Binding, Method conveniences, Object-Oriented Programming Style, Objects
10295: @subsubsection Class Binding
10296: @cindex class binding
10297: @cindex early binding
10298: 
10299: @cindex late binding
10300: Normal selector invocations determine the method at run-time depending
10301: on the class of the receiving object. This run-time selection is called
10302: @i{late binding}.
10303: 
10304: Sometimes it's preferable to invoke a different method. For example,
10305: you might want to use the simple method for @code{print}ing
10306: @code{object}s instead of the possibly long-winded @code{print} method
10307: of the receiver class. You can achieve this by replacing the invocation
10308: of @code{print} with:
10309: 
10310: @cindex @code{[bind]} usage
10311: @example
10312: [bind] object print
10313: @end example
10314: 
10315: @noindent
10316: in compiled code or:
10317: 
10318: @cindex @code{bind} usage
10319: @example
10320: bind object print
10321: @end example
10322: 
10323: @cindex class binding, alternative to
10324: @noindent
10325: in interpreted code. Alternatively, you can define the method with a
10326: name (e.g., @code{print-object}), and then invoke it through the
10327: name. Class binding is just a (often more convenient) way to achieve
10328: the same effect; it avoids name clutter and allows you to invoke
10329: methods directly without naming them first.
10330: 
10331: @cindex superclass binding
10332: @cindex parent class binding
10333: A frequent use of class binding is this: When we define a method
10334: for a selector, we often want the method to do what the selector does
10335: in the parent class, and a little more. There is a special word for
10336: this purpose: @code{[parent]}; @code{[parent]
10337: @emph{selector}} is equivalent to @code{[bind] @emph{parent
10338: selector}}, where @code{@emph{parent}} is the parent
10339: class of the current class. E.g., a method definition might look like:
10340: 
10341: @cindex @code{[parent]} usage
10342: @example
10343: :noname
10344:   dup [parent] foo \ do parent's foo on the receiving object
10345:   ... \ do some more
10346: ; overrides foo
10347: @end example
10348: 
10349: @cindex class binding as optimization
10350: In @cite{Object-oriented programming in ANS Forth} (Forth Dimensions,
10351: March 1997), Andrew McKewan presents class binding as an optimization
10352: technique. I recommend not using it for this purpose unless you are in
10353: an emergency. Late binding is pretty fast with this model anyway, so the
10354: benefit of using class binding is small; the cost of using class binding
10355: where it is not appropriate is reduced maintainability.
10356: 
10357: While we are at programming style questions: You should bind
10358: selectors only to ancestor classes of the receiving object. E.g., say,
10359: you know that the receiving object is of class @code{foo} or its
10360: descendents; then you should bind only to @code{foo} and its
10361: ancestors.
10362: 
10363: @node Method conveniences, Classes and Scoping, Class Binding, Objects
10364: @subsubsection Method conveniences
10365: @cindex method conveniences
10366: 
10367: In a method you usually access the receiving object pretty often.  If
10368: you define the method as a plain colon definition (e.g., with
10369: @code{:noname}), you may have to do a lot of stack
10370: gymnastics. To avoid this, you can define the method with @code{m:
10371: ... ;m}. E.g., you could define the method for
10372: @code{draw}ing a @code{circle} with
10373: 
10374: @cindex @code{this} usage
10375: @cindex @code{m:} usage
10376: @cindex @code{;m} usage
10377: @example
10378: m: ( x y circle -- )
10379:   ( x y ) this circle-radius @@ draw-circle ;m
10380: @end example
10381: 
10382: @cindex @code{exit} in @code{m: ... ;m}
10383: @cindex @code{exitm} discussion
10384: @cindex @code{catch} in @code{m: ... ;m}
10385: When this method is executed, the receiver object is removed from the
10386: stack; you can access it with @code{this} (admittedly, in this
10387: example the use of @code{m: ... ;m} offers no advantage). Note
10388: that I specify the stack effect for the whole method (i.e. including
10389: the receiver object), not just for the code between @code{m:}
10390: and @code{;m}. You cannot use @code{exit} in
10391: @code{m:...;m}; instead, use
10392: @code{exitm}.@footnote{Moreover, for any word that calls
10393: @code{catch} and was defined before loading
10394: @code{objects.fs}, you have to redefine it like I redefined
10395: @code{catch}: @code{: catch this >r catch r> to-this ;}}
10396: 
10397: @cindex @code{inst-var} usage
10398: You will frequently use sequences of the form @code{this
10399: @emph{field}} (in the example above: @code{this
10400: circle-radius}). If you use the field only in this way, you can
10401: define it with @code{inst-var} and eliminate the
10402: @code{this} before the field name. E.g., the @code{circle}
10403: class above could also be defined with:
10404: 
10405: @example
10406: graphical class
10407:   cell% inst-var radius
10408: 
10409: m: ( x y circle -- )
10410:   radius @@ draw-circle ;m
10411: overrides draw
10412: 
10413: m: ( n-radius circle -- )
10414:   radius ! ;m
10415: overrides construct
10416: 
10417: end-class circle
10418: @end example
10419: 
10420: @code{radius} can only be used in @code{circle} and its
10421: descendent classes and inside @code{m:...;m}.
10422: 
10423: @cindex @code{inst-value} usage
10424: You can also define fields with @code{inst-value}, which is
10425: to @code{inst-var} what @code{value} is to
10426: @code{variable}.  You can change the value of such a field with
10427: @code{[to-inst]}.  E.g., we could also define the class
10428: @code{circle} like this:
10429: 
10430: @example
10431: graphical class
10432:   inst-value radius
10433: 
10434: m: ( x y circle -- )
10435:   radius draw-circle ;m
10436: overrides draw
10437: 
10438: m: ( n-radius circle -- )
10439:   [to-inst] radius ;m
10440: overrides construct
10441: 
10442: end-class circle
10443: @end example
10444: 
10445: @c !! :m is easy to confuse with m:.  Another name would be better.
10446: 
10447: @c Finally, you can define named methods with @code{:m}.  One use of this
10448: @c feature is the definition of words that occur only in one class and are
10449: @c not intended to be overridden, but which still need method context
10450: @c (e.g., for accessing @code{inst-var}s).  Another use is for methods that
10451: @c would be bound frequently, if defined anonymously.
10452: 
10453: 
10454: @node Classes and Scoping, Dividing classes, Method conveniences, Objects
10455: @subsubsection Classes and Scoping
10456: @cindex classes and scoping
10457: @cindex scoping and classes
10458: 
10459: Inheritance is frequent, unlike structure extension. This exacerbates
10460: the problem with the field name convention (@pxref{Structure Naming
10461: Convention}): One always has to remember in which class the field was
10462: originally defined; changing a part of the class structure would require
10463: changes for renaming in otherwise unaffected code.
10464: 
10465: @cindex @code{inst-var} visibility
10466: @cindex @code{inst-value} visibility
10467: To solve this problem, I added a scoping mechanism (which was not in my
10468: original charter): A field defined with @code{inst-var} (or
10469: @code{inst-value}) is visible only in the class where it is defined and in
10470: the descendent classes of this class.  Using such fields only makes
10471: sense in @code{m:}-defined methods in these classes anyway.
10472: 
10473: This scoping mechanism allows us to use the unadorned field name,
10474: because name clashes with unrelated words become much less likely.
10475: 
10476: @cindex @code{protected} discussion
10477: @cindex @code{private} discussion
10478: Once we have this mechanism, we can also use it for controlling the
10479: visibility of other words: All words defined after
10480: @code{protected} are visible only in the current class and its
10481: descendents. @code{public} restores the compilation
10482: (i.e. @code{current}) word list that was in effect before. If you
10483: have several @code{protected}s without an intervening
10484: @code{public} or @code{set-current}, @code{public}
10485: will restore the compilation word list in effect before the first of
10486: these @code{protected}s.
10487: 
10488: @node Dividing classes, Object Interfaces, Classes and Scoping, Objects
10489: @subsubsection Dividing classes
10490: @cindex Dividing classes
10491: @cindex @code{methods}...@code{end-methods}
10492: 
10493: You may want to do the definition of methods separate from the
10494: definition of the class, its selectors, fields, and instance variables,
10495: i.e., separate the implementation from the definition.  You can do this
10496: in the following way:
10497: 
10498: @example
10499: graphical class
10500:   inst-value radius
10501: end-class circle
10502: 
10503: ... \ do some other stuff
10504: 
10505: circle methods \ now we are ready
10506: 
10507: m: ( x y circle -- )
10508:   radius draw-circle ;m
10509: overrides draw
10510: 
10511: m: ( n-radius circle -- )
10512:   [to-inst] radius ;m
10513: overrides construct
10514: 
10515: end-methods
10516: @end example
10517: 
10518: You can use several @code{methods}...@code{end-methods} sections.  The
10519: only things you can do to the class in these sections are: defining
10520: methods, and overriding the class's selectors.  You must not define new
10521: selectors or fields.
10522: 
10523: Note that you often have to override a selector before using it.  In
10524: particular, you usually have to override @code{construct} with a new
10525: method before you can invoke @code{heap-new} and friends.  E.g., you
10526: must not create a circle before the @code{overrides construct} sequence
10527: in the example above.
10528: 
10529: @node Object Interfaces, Objects Implementation, Dividing classes, Objects
10530: @subsubsection Object Interfaces
10531: @cindex object interfaces
10532: @cindex interfaces for objects
10533: 
10534: In this model you can only call selectors defined in the class of the
10535: receiving objects or in one of its ancestors. If you call a selector
10536: with a receiving object that is not in one of these classes, the
10537: result is undefined; if you are lucky, the program crashes
10538: immediately.
10539: 
10540: @cindex selectors common to hardly-related classes
10541: Now consider the case when you want to have a selector (or several)
10542: available in two classes: You would have to add the selector to a
10543: common ancestor class, in the worst case to @code{object}. You
10544: may not want to do this, e.g., because someone else is responsible for
10545: this ancestor class.
10546: 
10547: The solution for this problem is interfaces. An interface is a
10548: collection of selectors. If a class implements an interface, the
10549: selectors become available to the class and its descendents. A class
10550: can implement an unlimited number of interfaces. For the problem
10551: discussed above, we would define an interface for the selector(s), and
10552: both classes would implement the interface.
10553: 
10554: As an example, consider an interface @code{storage} for
10555: writing objects to disk and getting them back, and a class
10556: @code{foo} that implements it. The code would look like this:
10557: 
10558: @cindex @code{interface} usage
10559: @cindex @code{end-interface} usage
10560: @cindex @code{implementation} usage
10561: @example
10562: interface
10563:   selector write ( file object -- )
10564:   selector read1 ( file object -- )
10565: end-interface storage
10566: 
10567: bar class
10568:   storage implementation
10569: 
10570: ... overrides write
10571: ... overrides read1
10572: ...
10573: end-class foo
10574: @end example
10575: 
10576: @noindent
10577: (I would add a word @code{read} @i{( file -- object )} that uses
10578: @code{read1} internally, but that's beyond the point illustrated
10579: here.)
10580: 
10581: Note that you cannot use @code{protected} in an interface; and
10582: of course you cannot define fields.
10583: 
10584: In the Neon model, all selectors are available for all classes;
10585: therefore it does not need interfaces. The price you pay in this model
10586: is slower late binding, and therefore, added complexity to avoid late
10587: binding.
10588: 
10589: @node Objects Implementation, Objects Glossary, Object Interfaces, Objects
10590: @subsubsection @file{objects.fs} Implementation
10591: @cindex @file{objects.fs} implementation
10592: 
10593: @cindex @code{object-map} discussion
10594: An object is a piece of memory, like one of the data structures
10595: described with @code{struct...end-struct}. It has a field
10596: @code{object-map} that points to the method map for the object's
10597: class.
10598: 
10599: @cindex method map
10600: @cindex virtual function table
10601: The @emph{method map}@footnote{This is Self terminology; in C++
10602: terminology: virtual function table.} is an array that contains the
10603: execution tokens (@i{xt}s) of the methods for the object's class. Each
10604: selector contains an offset into a method map.
10605: 
10606: @cindex @code{selector} implementation, class
10607: @code{selector} is a defining word that uses
10608: @code{CREATE} and @code{DOES>}. The body of the
10609: selector contains the offset; the @code{DOES>} action for a
10610: class selector is, basically:
10611: 
10612: @example
10613: ( object addr ) @@ over object-map @@ + @@ execute
10614: @end example
10615: 
10616: Since @code{object-map} is the first field of the object, it
10617: does not generate any code. As you can see, calling a selector has a
10618: small, constant cost.
10619: 
10620: @cindex @code{current-interface} discussion
10621: @cindex class implementation and representation
10622: A class is basically a @code{struct} combined with a method
10623: map. During the class definition the alignment and size of the class
10624: are passed on the stack, just as with @code{struct}s, so
10625: @code{field} can also be used for defining class
10626: fields. However, passing more items on the stack would be
10627: inconvenient, so @code{class} builds a data structure in memory,
10628: which is accessed through the variable
10629: @code{current-interface}. After its definition is complete, the
10630: class is represented on the stack by a pointer (e.g., as parameter for
10631: a child class definition).
10632: 
10633: A new class starts off with the alignment and size of its parent,
10634: and a copy of the parent's method map. Defining new fields extends the
10635: size and alignment; likewise, defining new selectors extends the
10636: method map. @code{overrides} just stores a new @i{xt} in the method
10637: map at the offset given by the selector.
10638: 
10639: @cindex class binding, implementation
10640: Class binding just gets the @i{xt} at the offset given by the selector
10641: from the class's method map and @code{compile,}s (in the case of
10642: @code{[bind]}) it.
10643: 
10644: @cindex @code{this} implementation
10645: @cindex @code{catch} and @code{this}
10646: @cindex @code{this} and @code{catch}
10647: I implemented @code{this} as a @code{value}. At the
10648: start of an @code{m:...;m} method the old @code{this} is
10649: stored to the return stack and restored at the end; and the object on
10650: the TOS is stored @code{TO this}. This technique has one
10651: disadvantage: If the user does not leave the method via
10652: @code{;m}, but via @code{throw} or @code{exit},
10653: @code{this} is not restored (and @code{exit} may
10654: crash). To deal with the @code{throw} problem, I have redefined
10655: @code{catch} to save and restore @code{this}; the same
10656: should be done with any word that can catch an exception. As for
10657: @code{exit}, I simply forbid it (as a replacement, there is
10658: @code{exitm}).
10659: 
10660: @cindex @code{inst-var} implementation
10661: @code{inst-var} is just the same as @code{field}, with
10662: a different @code{DOES>} action:
10663: @example
10664: @@ this +
10665: @end example
10666: Similar for @code{inst-value}.
10667: 
10668: @cindex class scoping implementation
10669: Each class also has a word list that contains the words defined with
10670: @code{inst-var} and @code{inst-value}, and its protected
10671: words. It also has a pointer to its parent. @code{class} pushes
10672: the word lists of the class and all its ancestors onto the search order stack,
10673: and @code{end-class} drops them.
10674: 
10675: @cindex interface implementation
10676: An interface is like a class without fields, parent and protected
10677: words; i.e., it just has a method map. If a class implements an
10678: interface, its method map contains a pointer to the method map of the
10679: interface. The positive offsets in the map are reserved for class
10680: methods, therefore interface map pointers have negative
10681: offsets. Interfaces have offsets that are unique throughout the
10682: system, unlike class selectors, whose offsets are only unique for the
10683: classes where the selector is available (invokable).
10684: 
10685: This structure means that interface selectors have to perform one
10686: indirection more than class selectors to find their method. Their body
10687: contains the interface map pointer offset in the class method map, and
10688: the method offset in the interface method map. The
10689: @code{does>} action for an interface selector is, basically:
10690: 
10691: @example
10692: ( object selector-body )
10693: 2dup selector-interface @@ ( object selector-body object interface-offset )
10694: swap object-map @@ + @@ ( object selector-body map )
10695: swap selector-offset @@ + @@ execute
10696: @end example
10697: 
10698: where @code{object-map} and @code{selector-offset} are
10699: first fields and generate no code.
10700: 
10701: As a concrete example, consider the following code:
10702: 
10703: @example
10704: interface
10705:   selector if1sel1
10706:   selector if1sel2
10707: end-interface if1
10708: 
10709: object class
10710:   if1 implementation
10711:   selector cl1sel1
10712:   cell% inst-var cl1iv1
10713: 
10714: ' m1 overrides construct
10715: ' m2 overrides if1sel1
10716: ' m3 overrides if1sel2
10717: ' m4 overrides cl1sel2
10718: end-class cl1
10719: 
10720: create obj1 object dict-new drop
10721: create obj2 cl1    dict-new drop
10722: @end example
10723: 
10724: The data structure created by this code (including the data structure
10725: for @code{object}) is shown in the
10726: @uref{objects-implementation.eps,figure}, assuming a cell size of 4.
10727: @comment TODO add this diagram..
10728: 
10729: @node Objects Glossary,  , Objects Implementation, Objects
10730: @subsubsection @file{objects.fs} Glossary
10731: @cindex @file{objects.fs} Glossary
10732: 
10733: 
10734: doc---objects-bind
10735: doc---objects-<bind>
10736: doc---objects-bind'
10737: doc---objects-[bind]
10738: doc---objects-class
10739: doc---objects-class->map
10740: doc---objects-class-inst-size
10741: doc---objects-class-override!
10742: doc---objects-class-previous
10743: doc---objects-class>order
10744: doc---objects-construct
10745: doc---objects-current'
10746: doc---objects-[current]
10747: doc---objects-current-interface
10748: doc---objects-dict-new
10749: doc---objects-end-class
10750: doc---objects-end-class-noname
10751: doc---objects-end-interface
10752: doc---objects-end-interface-noname
10753: doc---objects-end-methods
10754: doc---objects-exitm
10755: doc---objects-heap-new
10756: doc---objects-implementation
10757: doc---objects-init-object
10758: doc---objects-inst-value
10759: doc---objects-inst-var
10760: doc---objects-interface
10761: doc---objects-m:
10762: doc---objects-:m
10763: doc---objects-;m
10764: doc---objects-method
10765: doc---objects-methods
10766: doc---objects-object
10767: doc---objects-overrides
10768: doc---objects-[parent]
10769: doc---objects-print
10770: doc---objects-protected
10771: doc---objects-public
10772: doc---objects-selector
10773: doc---objects-this
10774: doc---objects-<to-inst>
10775: doc---objects-[to-inst]
10776: doc---objects-to-this
10777: doc---objects-xt-new
10778: 
10779: 
10780: @c -------------------------------------------------------------
10781: @node OOF, Mini-OOF, Objects, Object-oriented Forth
10782: @subsection The @file{oof.fs} model
10783: @cindex oof
10784: @cindex object-oriented programming
10785: 
10786: @cindex @file{objects.fs}
10787: @cindex @file{oof.fs}
10788: 
10789: This section describes the @file{oof.fs} package.
10790: 
10791: The package described in this section has been used in bigFORTH since 1991, and
10792: used for two large applications: a chromatographic system used to
10793: create new medicaments, and a graphic user interface library (MINOS).
10794: 
10795: You can find a description (in German) of @file{oof.fs} in @cite{Object
10796: oriented bigFORTH} by Bernd Paysan, published in @cite{Vierte Dimension}
10797: 10(2), 1994.
10798: 
10799: @menu
10800: * Properties of the OOF model::  
10801: * Basic OOF Usage::             
10802: * The OOF base class::          
10803: * Class Declaration::           
10804: * Class Implementation::        
10805: @end menu
10806: 
10807: @node Properties of the OOF model, Basic OOF Usage, OOF, OOF
10808: @subsubsection Properties of the @file{oof.fs} model
10809: @cindex @file{oof.fs} properties
10810: 
10811: @itemize @bullet
10812: @item
10813: This model combines object oriented programming with information
10814: hiding. It helps you writing large application, where scoping is
10815: necessary, because it provides class-oriented scoping.
10816: 
10817: @item
10818: Named objects, object pointers, and object arrays can be created,
10819: selector invocation uses the ``object selector'' syntax. Selector invocation
10820: to objects and/or selectors on the stack is a bit less convenient, but
10821: possible.
10822: 
10823: @item
10824: Selector invocation and instance variable usage of the active object is
10825: straightforward, since both make use of the active object.
10826: 
10827: @item
10828: Late binding is efficient and easy to use.
10829: 
10830: @item
10831: State-smart objects parse selectors. However, extensibility is provided
10832: using a (parsing) selector @code{postpone} and a selector @code{'}.
10833: 
10834: @item
10835: An implementation in ANS Forth is available.
10836: 
10837: @end itemize
10838: 
10839: 
10840: @node Basic OOF Usage, The OOF base class, Properties of the OOF model, OOF
10841: @subsubsection Basic @file{oof.fs} Usage
10842: @cindex @file{oof.fs} usage
10843: 
10844: This section uses the same example as for @code{objects} (@pxref{Basic Objects Usage}).
10845: 
10846: You can define a class for graphical objects like this:
10847: 
10848: @cindex @code{class} usage
10849: @cindex @code{class;} usage
10850: @cindex @code{method} usage
10851: @example
10852: object class graphical \ "object" is the parent class
10853:   method draw ( x y -- )
10854: class;
10855: @end example
10856: 
10857: This code defines a class @code{graphical} with an
10858: operation @code{draw}.  We can perform the operation
10859: @code{draw} on any @code{graphical} object, e.g.:
10860: 
10861: @example
10862: 100 100 t-rex draw
10863: @end example
10864: 
10865: @noindent
10866: where @code{t-rex} is an object or object pointer, created with e.g.
10867: @code{graphical : t-rex}.
10868: 
10869: @cindex abstract class
10870: How do we create a graphical object? With the present definitions,
10871: we cannot create a useful graphical object. The class
10872: @code{graphical} describes graphical objects in general, but not
10873: any concrete graphical object type (C++ users would call it an
10874: @emph{abstract class}); e.g., there is no method for the selector
10875: @code{draw} in the class @code{graphical}.
10876: 
10877: For concrete graphical objects, we define child classes of the
10878: class @code{graphical}, e.g.:
10879: 
10880: @example
10881: graphical class circle \ "graphical" is the parent class
10882:   cell var circle-radius
10883: how:
10884:   : draw ( x y -- )
10885:     circle-radius @@ draw-circle ;
10886: 
10887:   : init ( n-radius -- )
10888:     circle-radius ! ;
10889: class;
10890: @end example
10891: 
10892: Here we define a class @code{circle} as a child of @code{graphical},
10893: with a field @code{circle-radius}; it defines new methods for the
10894: selectors @code{draw} and @code{init} (@code{init} is defined in
10895: @code{object}, the parent class of @code{graphical}).
10896: 
10897: Now we can create a circle in the dictionary with:
10898: 
10899: @example
10900: 50 circle : my-circle
10901: @end example
10902: 
10903: @noindent
10904: @code{:} invokes @code{init}, thus initializing the field
10905: @code{circle-radius} with 50. We can draw this new circle at (100,100)
10906: with:
10907: 
10908: @example
10909: 100 100 my-circle draw
10910: @end example
10911: 
10912: @cindex selector invocation, restrictions
10913: @cindex class definition, restrictions
10914: Note: You can only invoke a selector if the receiving object belongs to
10915: the class where the selector was defined or one of its descendents;
10916: e.g., you can invoke @code{draw} only for objects belonging to
10917: @code{graphical} or its descendents (e.g., @code{circle}). The scoping
10918: mechanism will check if you try to invoke a selector that is not
10919: defined in this class hierarchy, so you'll get an error at compilation
10920: time.
10921: 
10922: 
10923: @node The OOF base class, Class Declaration, Basic OOF Usage, OOF
10924: @subsubsection The @file{oof.fs} base class
10925: @cindex @file{oof.fs} base class
10926: 
10927: When you define a class, you have to specify a parent class.  So how do
10928: you start defining classes? There is one class available from the start:
10929: @code{object}. You have to use it as ancestor for all classes. It is the
10930: only class that has no parent. Classes are also objects, except that
10931: they don't have instance variables; class manipulation such as
10932: inheritance or changing definitions of a class is handled through
10933: selectors of the class @code{object}.
10934: 
10935: @code{object} provides a number of selectors:
10936: 
10937: @itemize @bullet
10938: @item
10939: @code{class} for subclassing, @code{definitions} to add definitions
10940: later on, and @code{class?} to get type informations (is the class a
10941: subclass of the class passed on the stack?).
10942: 
10943: doc---object-class
10944: doc---object-definitions
10945: doc---object-class?
10946: 
10947: 
10948: @item
10949: @code{init} and @code{dispose} as constructor and destructor of the
10950: object. @code{init} is invocated after the object's memory is allocated,
10951: while @code{dispose} also handles deallocation. Thus if you redefine
10952: @code{dispose}, you have to call the parent's dispose with @code{super
10953: dispose}, too.
10954: 
10955: doc---object-init
10956: doc---object-dispose
10957: 
10958: 
10959: @item
10960: @code{new}, @code{new[]}, @code{:}, @code{ptr}, @code{asptr}, and
10961: @code{[]} to create named and unnamed objects and object arrays or
10962: object pointers.
10963: 
10964: doc---object-new
10965: doc---object-new[]
10966: doc---object-:
10967: doc---object-ptr
10968: doc---object-asptr
10969: doc---object-[]
10970: 
10971: 
10972: @item
10973: @code{::} and @code{super} for explicit scoping. You should use explicit
10974: scoping only for super classes or classes with the same set of instance
10975: variables. Explicitly-scoped selectors use early binding.
10976: 
10977: doc---object-::
10978: doc---object-super
10979: 
10980: 
10981: @item
10982: @code{self} to get the address of the object
10983: 
10984: doc---object-self
10985: 
10986: 
10987: @item
10988: @code{bind}, @code{bound}, @code{link}, and @code{is} to assign object
10989: pointers and instance defers.
10990: 
10991: doc---object-bind
10992: doc---object-bound
10993: doc---object-link
10994: doc---object-is
10995: 
10996: 
10997: @item
10998: @code{'} to obtain selector tokens, @code{send} to invocate selectors
10999: form the stack, and @code{postpone} to generate selector invocation code.
11000: 
11001: doc---object-'
11002: doc---object-postpone
11003: 
11004: 
11005: @item
11006: @code{with} and @code{endwith} to select the active object from the
11007: stack, and enable its scope. Using @code{with} and @code{endwith}
11008: also allows you to create code using selector @code{postpone} without being
11009: trapped by the state-smart objects.
11010: 
11011: doc---object-with
11012: doc---object-endwith
11013: 
11014: 
11015: @end itemize
11016: 
11017: @node Class Declaration, Class Implementation, The OOF base class, OOF
11018: @subsubsection Class Declaration
11019: @cindex class declaration
11020: 
11021: @itemize @bullet
11022: @item
11023: Instance variables
11024: 
11025: doc---oof-var
11026: 
11027: 
11028: @item
11029: Object pointers
11030: 
11031: doc---oof-ptr
11032: doc---oof-asptr
11033: 
11034: 
11035: @item
11036: Instance defers
11037: 
11038: doc---oof-defer
11039: 
11040: 
11041: @item
11042: Method selectors
11043: 
11044: doc---oof-early
11045: doc---oof-method
11046: 
11047: 
11048: @item
11049: Class-wide variables
11050: 
11051: doc---oof-static
11052: 
11053: 
11054: @item
11055: End declaration
11056: 
11057: doc---oof-how:
11058: doc---oof-class;
11059: 
11060: 
11061: @end itemize
11062: 
11063: @c -------------------------------------------------------------
11064: @node Class Implementation,  , Class Declaration, OOF
11065: @subsubsection Class Implementation
11066: @cindex class implementation
11067: 
11068: @c -------------------------------------------------------------
11069: @node Mini-OOF, Comparison with other object models, OOF, Object-oriented Forth
11070: @subsection The @file{mini-oof.fs} model
11071: @cindex mini-oof
11072: 
11073: Gforth's third object oriented Forth package is a 12-liner. It uses a
11074: mixture of the @file{objects.fs} and the @file{oof.fs} syntax,
11075: and reduces to the bare minimum of features. This is based on a posting
11076: of Bernd Paysan in comp.lang.forth.
11077: 
11078: @menu
11079: * Basic Mini-OOF Usage::        
11080: * Mini-OOF Example::            
11081: * Mini-OOF Implementation::     
11082: @end menu
11083: 
11084: @c -------------------------------------------------------------
11085: @node Basic Mini-OOF Usage, Mini-OOF Example, Mini-OOF, Mini-OOF
11086: @subsubsection Basic @file{mini-oof.fs} Usage
11087: @cindex mini-oof usage
11088: 
11089: There is a base class (@code{class}, which allocates one cell for the
11090: object pointer) plus seven other words: to define a method, a variable,
11091: a class; to end a class, to resolve binding, to allocate an object and
11092: to compile a class method.
11093: @comment TODO better description of the last one
11094: 
11095: 
11096: doc-object
11097: doc-method
11098: doc-var
11099: doc-class
11100: doc-end-class
11101: doc-defines
11102: doc-new
11103: doc-::
11104: 
11105: 
11106: 
11107: @c -------------------------------------------------------------
11108: @node Mini-OOF Example, Mini-OOF Implementation, Basic Mini-OOF Usage, Mini-OOF
11109: @subsubsection Mini-OOF Example
11110: @cindex mini-oof example
11111: 
11112: A short example shows how to use this package. This example, in slightly
11113: extended form, is supplied as @file{moof-exm.fs}
11114: @comment TODO could flesh this out with some comments from the Forthwrite article
11115: 
11116: @example
11117: object class
11118:   method init
11119:   method draw
11120: end-class graphical
11121: @end example
11122: 
11123: This code defines a class @code{graphical} with an
11124: operation @code{draw}.  We can perform the operation
11125: @code{draw} on any @code{graphical} object, e.g.:
11126: 
11127: @example
11128: 100 100 t-rex draw
11129: @end example
11130: 
11131: where @code{t-rex} is an object or object pointer, created with e.g.
11132: @code{graphical new Constant t-rex}.
11133: 
11134: For concrete graphical objects, we define child classes of the
11135: class @code{graphical}, e.g.:
11136: 
11137: @example
11138: graphical class
11139:   cell var circle-radius
11140: end-class circle \ "graphical" is the parent class
11141: 
11142: :noname ( x y -- )
11143:   circle-radius @@ draw-circle ; circle defines draw
11144: :noname ( r -- )
11145:   circle-radius ! ; circle defines init
11146: @end example
11147: 
11148: There is no implicit init method, so we have to define one. The creation
11149: code of the object now has to call init explicitely.
11150: 
11151: @example
11152: circle new Constant my-circle
11153: 50 my-circle init
11154: @end example
11155: 
11156: It is also possible to add a function to create named objects with
11157: automatic call of @code{init}, given that all objects have @code{init}
11158: on the same place:
11159: 
11160: @example
11161: : new: ( .. o "name" -- )
11162:     new dup Constant init ;
11163: 80 circle new: large-circle
11164: @end example
11165: 
11166: We can draw this new circle at (100,100) with:
11167: 
11168: @example
11169: 100 100 my-circle draw
11170: @end example
11171: 
11172: @node Mini-OOF Implementation,  , Mini-OOF Example, Mini-OOF
11173: @subsubsection @file{mini-oof.fs} Implementation
11174: 
11175: Object-oriented systems with late binding typically use a
11176: ``vtable''-approach: the first variable in each object is a pointer to a
11177: table, which contains the methods as function pointers. The vtable
11178: may also contain other information.
11179: 
11180: So first, let's declare selectors:
11181: 
11182: @example
11183: : method ( m v "name" -- m' v ) Create  over , swap cell+ swap
11184:   DOES> ( ... o -- ... ) @@ over @@ + @@ execute ;
11185: @end example
11186: 
11187: During selector declaration, the number of selectors and instance
11188: variables is on the stack (in address units). @code{method} creates one
11189: selector and increments the selector number. To execute a selector, it
11190: takes the object, fetches the vtable pointer, adds the offset, and
11191: executes the method @i{xt} stored there. Each selector takes the object
11192: it is invoked with as top of stack parameter; it passes the parameters
11193: (including the object) unchanged to the appropriate method which should
11194: consume that object.
11195: 
11196: Now, we also have to declare instance variables
11197: 
11198: @example
11199: : var ( m v size "name" -- m v' ) Create  over , +
11200:   DOES> ( o -- addr ) @@ + ;
11201: @end example
11202: 
11203: As before, a word is created with the current offset. Instance
11204: variables can have different sizes (cells, floats, doubles, chars), so
11205: all we do is take the size and add it to the offset. If your machine
11206: has alignment restrictions, put the proper @code{aligned} or
11207: @code{faligned} before the variable, to adjust the variable
11208: offset. That's why it is on the top of stack.
11209: 
11210: We need a starting point (the base object) and some syntactic sugar:
11211: 
11212: @example
11213: Create object  1 cells , 2 cells ,
11214: : class ( class -- class selectors vars ) dup 2@@ ;
11215: @end example
11216: 
11217: For inheritance, the vtable of the parent object has to be
11218: copied when a new, derived class is declared. This gives all the
11219: methods of the parent class, which can be overridden, though.
11220: 
11221: @example
11222: : end-class  ( class selectors vars "name" -- )
11223:   Create  here >r , dup , 2 cells ?DO ['] noop , 1 cells +LOOP
11224:   cell+ dup cell+ r> rot @@ 2 cells /string move ;
11225: @end example
11226: 
11227: The first line creates the vtable, initialized with
11228: @code{noop}s. The second line is the inheritance mechanism, it
11229: copies the xts from the parent vtable.
11230: 
11231: We still have no way to define new methods, let's do that now:
11232: 
11233: @example
11234: : defines ( xt class "name" -- ) ' >body @@ + ! ;
11235: @end example
11236: 
11237: To allocate a new object, we need a word, too:
11238: 
11239: @example
11240: : new ( class -- o )  here over @@ allot swap over ! ;
11241: @end example
11242: 
11243: Sometimes derived classes want to access the method of the
11244: parent object. There are two ways to achieve this with Mini-OOF:
11245: first, you could use named words, and second, you could look up the
11246: vtable of the parent object.
11247: 
11248: @example
11249: : :: ( class "name" -- ) ' >body @@ + @@ compile, ;
11250: @end example
11251: 
11252: 
11253: Nothing can be more confusing than a good example, so here is
11254: one. First let's declare a text object (called
11255: @code{button}), that stores text and position:
11256: 
11257: @example
11258: object class
11259:   cell var text
11260:   cell var len
11261:   cell var x
11262:   cell var y
11263:   method init
11264:   method draw
11265: end-class button
11266: @end example
11267: 
11268: @noindent
11269: Now, implement the two methods, @code{draw} and @code{init}:
11270: 
11271: @example
11272: :noname ( o -- )
11273:  >r r@@ x @@ r@@ y @@ at-xy  r@@ text @@ r> len @@ type ;
11274:  button defines draw
11275: :noname ( addr u o -- )
11276:  >r 0 r@@ x ! 0 r@@ y ! r@@ len ! r> text ! ;
11277:  button defines init
11278: @end example
11279: 
11280: @noindent
11281: To demonstrate inheritance, we define a class @code{bold-button}, with no
11282: new data and no new selectors:
11283: 
11284: @example
11285: button class
11286: end-class bold-button
11287: 
11288: : bold   27 emit ." [1m" ;
11289: : normal 27 emit ." [0m" ;
11290: @end example
11291: 
11292: @noindent
11293: The class @code{bold-button} has a different draw method to
11294: @code{button}, but the new method is defined in terms of the draw method
11295: for @code{button}:
11296: 
11297: @example
11298: :noname bold [ button :: draw ] normal ; bold-button defines draw
11299: @end example
11300: 
11301: @noindent
11302: Finally, create two objects and apply selectors:
11303: 
11304: @example
11305: button new Constant foo
11306: s" thin foo" foo init
11307: page
11308: foo draw
11309: bold-button new Constant bar
11310: s" fat bar" bar init
11311: 1 bar y !
11312: bar draw
11313: @end example
11314: 
11315: 
11316: @node Comparison with other object models,  , Mini-OOF, Object-oriented Forth
11317: @subsection Comparison with other object models
11318: @cindex comparison of object models
11319: @cindex object models, comparison
11320: 
11321: Many object-oriented Forth extensions have been proposed (@cite{A survey
11322: of object-oriented Forths} (SIGPLAN Notices, April 1996) by Bradford
11323: J. Rodriguez and W. F. S. Poehlman lists 17). This section discusses the
11324: relation of the object models described here to two well-known and two
11325: closely-related (by the use of method maps) models.  Andras Zsoter
11326: helped us with this section.
11327: 
11328: @cindex Neon model
11329: The most popular model currently seems to be the Neon model (see
11330: @cite{Object-oriented programming in ANS Forth} (Forth Dimensions, March
11331: 1997) by Andrew McKewan) but this model has a number of limitations
11332: @footnote{A longer version of this critique can be
11333: found in @cite{On Standardizing Object-Oriented Forth Extensions} (Forth
11334: Dimensions, May 1997) by Anton Ertl.}:
11335: 
11336: @itemize @bullet
11337: @item
11338: It uses a @code{@emph{selector object}} syntax, which makes it unnatural
11339: to pass objects on the stack.
11340: 
11341: @item
11342: It requires that the selector parses the input stream (at
11343: compile time); this leads to reduced extensibility and to bugs that are
11344: hard to find.
11345: 
11346: @item
11347: It allows using every selector on every object; this eliminates the
11348: need for interfaces, but makes it harder to create efficient
11349: implementations.
11350: @end itemize
11351: 
11352: @cindex Pountain's object-oriented model
11353: Another well-known publication is @cite{Object-Oriented Forth} (Academic
11354: Press, London, 1987) by Dick Pountain. However, it is not really about
11355: object-oriented programming, because it hardly deals with late
11356: binding. Instead, it focuses on features like information hiding and
11357: overloading that are characteristic of modular languages like Ada (83).
11358: 
11359: @cindex Zsoter's object-oriented model
11360: In @uref{http://www.forth.org/oopf.html, Does late binding have to be
11361: slow?} (Forth Dimensions 18(1) 1996, pages 31-35) Andras Zsoter
11362: describes a model that makes heavy use of an active object (like
11363: @code{this} in @file{objects.fs}): The active object is not only used
11364: for accessing all fields, but also specifies the receiving object of
11365: every selector invocation; you have to change the active object
11366: explicitly with @code{@{ ... @}}, whereas in @file{objects.fs} it
11367: changes more or less implicitly at @code{m: ... ;m}. Such a change at
11368: the method entry point is unnecessary with Zsoter's model, because the
11369: receiving object is the active object already. On the other hand, the
11370: explicit change is absolutely necessary in that model, because otherwise
11371: no one could ever change the active object. An ANS Forth implementation
11372: of this model is available through
11373: @uref{http://www.forth.org/oopf.html}.
11374: 
11375: @cindex @file{oof.fs}, differences to other models
11376: The @file{oof.fs} model combines information hiding and overloading
11377: resolution (by keeping names in various word lists) with object-oriented
11378: programming. It sets the active object implicitly on method entry, but
11379: also allows explicit changing (with @code{>o...o>} or with
11380: @code{with...endwith}). It uses parsing and state-smart objects and
11381: classes for resolving overloading and for early binding: the object or
11382: class parses the selector and determines the method from this. If the
11383: selector is not parsed by an object or class, it performs a call to the
11384: selector for the active object (late binding), like Zsoter's model.
11385: Fields are always accessed through the active object. The big
11386: disadvantage of this model is the parsing and the state-smartness, which
11387: reduces extensibility and increases the opportunities for subtle bugs;
11388: essentially, you are only safe if you never tick or @code{postpone} an
11389: object or class (Bernd disagrees, but I (Anton) am not convinced).
11390: 
11391: @cindex @file{mini-oof.fs}, differences to other models
11392: The @file{mini-oof.fs} model is quite similar to a very stripped-down
11393: version of the @file{objects.fs} model, but syntactically it is a
11394: mixture of the @file{objects.fs} and @file{oof.fs} models.
11395: 
11396: 
11397: @c -------------------------------------------------------------
11398: @node Programming Tools, C Interface, Object-oriented Forth, Words
11399: @section Programming Tools
11400: @cindex programming tools
11401: 
11402: @c !! move this and assembler down below OO stuff.
11403: 
11404: @menu
11405: * Examining::                   Data and Code.
11406: * Forgetting words::            Usually before reloading.
11407: * Debugging::                   Simple and quick.
11408: * Assertions::                  Making your programs self-checking.
11409: * Singlestep Debugger::         Executing your program word by word.
11410: @end menu
11411: 
11412: @node Examining, Forgetting words, Programming Tools, Programming Tools
11413: @subsection Examining data and code
11414: @cindex examining data and code
11415: @cindex data examination
11416: @cindex code examination
11417: 
11418: The following words inspect the stack non-destructively:
11419: 
11420: doc-.s
11421: doc-f.s
11422: 
11423: There is a word @code{.r} but it does @i{not} display the return stack!
11424: It is used for formatted numeric output (@pxref{Simple numeric output}).
11425: 
11426: doc-depth
11427: doc-fdepth
11428: doc-clearstack
11429: doc-clearstacks
11430: 
11431: The following words inspect memory.
11432: 
11433: doc-?
11434: doc-dump
11435: 
11436: And finally, @code{see} allows to inspect code:
11437: 
11438: doc-see
11439: doc-xt-see
11440: doc-simple-see
11441: doc-simple-see-range
11442: 
11443: @node Forgetting words, Debugging, Examining, Programming Tools
11444: @subsection Forgetting words
11445: @cindex words, forgetting
11446: @cindex forgeting words
11447: 
11448: @c  anton: other, maybe better places for this subsection: Defining Words;
11449: @c  Dictionary allocation.  At least a reference should be there.
11450: 
11451: Forth allows you to forget words (and everything that was alloted in the
11452: dictonary after them) in a LIFO manner.
11453: 
11454: doc-marker
11455: 
11456: The most common use of this feature is during progam development: when
11457: you change a source file, forget all the words it defined and load it
11458: again (since you also forget everything defined after the source file
11459: was loaded, you have to reload that, too).  Note that effects like
11460: storing to variables and destroyed system words are not undone when you
11461: forget words.  With a system like Gforth, that is fast enough at
11462: starting up and compiling, I find it more convenient to exit and restart
11463: Gforth, as this gives me a clean slate.
11464: 
11465: Here's an example of using @code{marker} at the start of a source file
11466: that you are debugging; it ensures that you only ever have one copy of
11467: the file's definitions compiled at any time:
11468: 
11469: @example
11470: [IFDEF] my-code
11471:     my-code
11472: [ENDIF]
11473: 
11474: marker my-code
11475: init-included-files
11476: 
11477: \ .. definitions start here
11478: \ .
11479: \ .
11480: \ end
11481: @end example
11482: 
11483: 
11484: @node Debugging, Assertions, Forgetting words, Programming Tools
11485: @subsection Debugging
11486: @cindex debugging
11487: 
11488: Languages with a slow edit/compile/link/test development loop tend to
11489: require sophisticated tracing/stepping debuggers to facilate debugging.
11490: 
11491: A much better (faster) way in fast-compiling languages is to add
11492: printing code at well-selected places, let the program run, look at
11493: the output, see where things went wrong, add more printing code, etc.,
11494: until the bug is found.
11495: 
11496: The simple debugging aids provided in @file{debugs.fs}
11497: are meant to support this style of debugging.
11498: 
11499: The word @code{~~} prints debugging information (by default the source
11500: location and the stack contents). It is easy to insert. If you use Emacs
11501: it is also easy to remove (@kbd{C-x ~} in the Emacs Forth mode to
11502: query-replace them with nothing). The deferred words
11503: @code{printdebugdata} and @code{.debugline} control the output of
11504: @code{~~}. The default source location output format works well with
11505: Emacs' compilation mode, so you can step through the program at the
11506: source level using @kbd{C-x `} (the advantage over a stepping debugger
11507: is that you can step in any direction and you know where the crash has
11508: happened or where the strange data has occurred).
11509: 
11510: doc-~~
11511: doc-printdebugdata
11512: doc-.debugline
11513: 
11514: @cindex filenames in @code{~~} output
11515: @code{~~} (and assertions) will usually print the wrong file name if a
11516: marker is executed in the same file after their occurance.  They will
11517: print @samp{*somewhere*} as file name if a marker is executed in the
11518: same file before their occurance.
11519: 
11520: 
11521: @node Assertions, Singlestep Debugger, Debugging, Programming Tools
11522: @subsection Assertions
11523: @cindex assertions
11524: 
11525: It is a good idea to make your programs self-checking, especially if you
11526: make an assumption that may become invalid during maintenance (for
11527: example, that a certain field of a data structure is never zero). Gforth
11528: supports @dfn{assertions} for this purpose. They are used like this:
11529: 
11530: @example
11531: assert( @i{flag} )
11532: @end example
11533: 
11534: The code between @code{assert(} and @code{)} should compute a flag, that
11535: should be true if everything is alright and false otherwise. It should
11536: not change anything else on the stack. The overall stack effect of the
11537: assertion is @code{( -- )}. E.g.
11538: 
11539: @example
11540: assert( 1 1 + 2 = ) \ what we learn in school
11541: assert( dup 0<> ) \ assert that the top of stack is not zero
11542: assert( false ) \ this code should not be reached
11543: @end example
11544: 
11545: The need for assertions is different at different times. During
11546: debugging, we want more checking, in production we sometimes care more
11547: for speed. Therefore, assertions can be turned off, i.e., the assertion
11548: becomes a comment. Depending on the importance of an assertion and the
11549: time it takes to check it, you may want to turn off some assertions and
11550: keep others turned on. Gforth provides several levels of assertions for
11551: this purpose:
11552: 
11553: 
11554: doc-assert0(
11555: doc-assert1(
11556: doc-assert2(
11557: doc-assert3(
11558: doc-assert(
11559: doc-)
11560: 
11561: 
11562: The variable @code{assert-level} specifies the highest assertions that
11563: are turned on. I.e., at the default @code{assert-level} of one,
11564: @code{assert0(} and @code{assert1(} assertions perform checking, while
11565: @code{assert2(} and @code{assert3(} assertions are treated as comments.
11566: 
11567: The value of @code{assert-level} is evaluated at compile-time, not at
11568: run-time. Therefore you cannot turn assertions on or off at run-time;
11569: you have to set the @code{assert-level} appropriately before compiling a
11570: piece of code. You can compile different pieces of code at different
11571: @code{assert-level}s (e.g., a trusted library at level 1 and
11572: newly-written code at level 3).
11573: 
11574: 
11575: doc-assert-level
11576: 
11577: 
11578: If an assertion fails, a message compatible with Emacs' compilation mode
11579: is produced and the execution is aborted (currently with @code{ABORT"}.
11580: If there is interest, we will introduce a special throw code. But if you
11581: intend to @code{catch} a specific condition, using @code{throw} is
11582: probably more appropriate than an assertion).
11583: 
11584: @cindex filenames in assertion output
11585: Assertions (and @code{~~}) will usually print the wrong file name if a
11586: marker is executed in the same file after their occurance.  They will
11587: print @samp{*somewhere*} as file name if a marker is executed in the
11588: same file before their occurance.
11589: 
11590: Definitions in ANS Forth for these assertion words are provided
11591: in @file{compat/assert.fs}.
11592: 
11593: 
11594: @node Singlestep Debugger,  , Assertions, Programming Tools
11595: @subsection Singlestep Debugger
11596: @cindex singlestep Debugger
11597: @cindex debugging Singlestep
11598: 
11599: The singlestep debugger does not work in this release.
11600: 
11601: When you create a new word there's often the need to check whether it
11602: behaves correctly or not. You can do this by typing @code{dbg
11603: badword}. A debug session might look like this:
11604: 
11605: @example
11606: : badword 0 DO i . LOOP ;  ok
11607: 2 dbg badword 
11608: : badword  
11609: Scanning code...
11610: 
11611: Nesting debugger ready!
11612: 
11613: 400D4738  8049BC4 0              -> [ 2 ] 00002 00000 
11614: 400D4740  8049F68 DO             -> [ 0 ] 
11615: 400D4744  804A0C8 i              -> [ 1 ] 00000 
11616: 400D4748 400C5E60 .              -> 0 [ 0 ] 
11617: 400D474C  8049D0C LOOP           -> [ 0 ] 
11618: 400D4744  804A0C8 i              -> [ 1 ] 00001 
11619: 400D4748 400C5E60 .              -> 1 [ 0 ] 
11620: 400D474C  8049D0C LOOP           -> [ 0 ] 
11621: 400D4758  804B384 ;              ->  ok
11622: @end example
11623: 
11624: Each line displayed is one step. You always have to hit return to
11625: execute the next word that is displayed. If you don't want to execute
11626: the next word in a whole, you have to type @kbd{n} for @code{nest}. Here is
11627: an overview what keys are available:
11628: 
11629: @table @i
11630: 
11631: @item @key{RET}
11632: Next; Execute the next word.
11633: 
11634: @item n
11635: Nest; Single step through next word.
11636: 
11637: @item u
11638: Unnest; Stop debugging and execute rest of word. If we got to this word
11639: with nest, continue debugging with the calling word.
11640: 
11641: @item d
11642: Done; Stop debugging and execute rest.
11643: 
11644: @item s
11645: Stop; Abort immediately.
11646: 
11647: @end table
11648: 
11649: Debugging large application with this mechanism is very difficult, because
11650: you have to nest very deeply into the program before the interesting part
11651: begins. This takes a lot of time. 
11652: 
11653: To do it more directly put a @code{BREAK:} command into your source code.
11654: When program execution reaches @code{BREAK:} the single step debugger is
11655: invoked and you have all the features described above.
11656: 
11657: If you have more than one part to debug it is useful to know where the
11658: program has stopped at the moment. You can do this by the 
11659: @code{BREAK" string"} command. This behaves like @code{BREAK:} except that
11660: string is typed out when the ``breakpoint'' is reached.
11661: 
11662: 
11663: doc-dbg
11664: doc-break:
11665: doc-break"
11666: 
11667: @c ------------------------------------------------------------
11668: @node C Interface, Assembler and Code Words, Programming Tools, Words
11669: @section C Interface
11670: @cindex C interface
11671: @cindex foreign language interface
11672: @cindex interface to C functions
11673: 
11674: Note that the C interface is not yet complete; a better way of
11675: declaring C functions is planned, as well as a way of declaring
11676: structs, unions, and their fields.
11677: 
11678: @menu
11679: * Calling C Functions::         
11680: * Declaring C Functions::       
11681: * Callbacks::                   
11682: @end menu
11683: 
11684: @node Calling C Functions, Declaring C Functions, C Interface, C Interface
11685: @subsection Calling C functions
11686: 
11687: Once a C function is declared (see @pxref{Declaring C Functions}), you
11688: can call it as follows: You push the arguments on the stack(s), and
11689: then call the word for the C function.  The arguments have to be
11690: pushed in the same order as the arguments appear in the C
11691: documentation (i.e., the first argument is deepest on the stack).
11692: Integer and pointer arguments have to be pushed on the data stack,
11693: floating-point arguments on the FP stack; these arguments are consumed
11694: by calling the C function.
11695: 
11696: On returning from the C function, the return value, if any, is pushed
11697: on the appropriate stack: an integer return value is pushed on the
11698: data stack, an FP return value on the FP stack, and a void return
11699: value results in not pushing anything.  Note that most C functions
11700: have a return value, even if that is often not used in C; in Forth,
11701: you have to @code{drop} this return value explicitly if you do not use
11702: it.
11703: 
11704: By default, an integer argument or return value corresponds to a
11705: single cell, and a floating-point argument or return value corresponds
11706: to a Forth float value; the C interface performs the appropriate
11707: conversions where necessary, on a best-effort basis (in some cases,
11708: there may be some loss).
11709: 
11710: As an example, consider the POSIX function @code{lseek()}:
11711: 
11712: @example
11713: off_t lseek(int fd, off_t offset, int whence);
11714: @end example
11715: 
11716: This function takes three integer arguments, and returns an integer
11717: argument, so a Forth call for setting the current file offset to the
11718: start of the file could look like this:
11719: 
11720: @example
11721: fd @@ 0 SEEK_SET lseek -1 = if
11722:   ... \ error handling
11723: then
11724: @end example
11725: 
11726: You might be worried that an @code{off_t} does not fit into a cell, so
11727: you could not pass larger offsets to lseek, and might get only a part
11728: of the return values.  In that case, you should declare the function
11729: to use double-cells for the off_t argument and return value (no matter
11730: how large or small the off_t type actually is), and maybe give the
11731: resulting Forth word a different name, like @code{dlseek}; the result
11732: could be called like this:
11733: 
11734: @example
11735: fd @@ 0. SEEK_SET dlseek -1. d= if
11736:   ... \ error handling
11737: then
11738: @end example
11739: 
11740: Passing and returning structs or unions is currently not supported by
11741: our interface@footnote{If you know the calling convention of your C
11742: compiler, you usually can call such functions in some way, but that
11743: way is usually not portable between platforms, and sometimes not even
11744: between C compilers.}.
11745: 
11746: Calling functions with a variable number of arguments (e.g.,
11747: @code{printf()}) is currently only supported by having you declare one
11748: function-calling word for each argument pattern, and calling the
11749: appropriate word for the desired pattern.
11750: 
11751: @node Declaring C Functions, Callbacks, Calling C Functions, C Interface
11752: @subsection Declaring C Functions
11753: 
11754: Before you can call @code{lseek} or @code{dlseek}, you have to declare
11755: it.  You have to look up in your system what the concrete type for the
11756: abstract type @code{off_t} is; let's assume it is @code{long}.  Then
11757: the declarations for these words are:
11758: 
11759: @example
11760: library libc libc.so.6
11761: libc lseek  int  long int  (long) lseek ( fd noffset whence -- noffset2 )
11762: libc dlseek int dlong int (dlong) lseek ( fd doffset whence -- doffset2 ) 
11763: @end example
11764: 
11765: The first line defines a Forth word @code{libc} for accessing the C
11766: functions in the shared library @file{libc.so.6} (the name of the
11767: shared library depends on the library and the OS; this example is the
11768: standard C library (containing most of the standard C and Unix
11769: functions) for GNU/Linux systems since about 1998).
11770: 
11771: The next two lines define two Forth words for the same C function
11772: @code{lseek()}; the middle line defines @code{lseek ( n1 n2 n3 -- n
11773: )}, and the last line defines @code{dlseek ( n1 d2 n3 -- d)}
11774: 
11775: !!!
11776: 
11777: 
11778: As you can see, the declarations are relatively platform-dependent
11779: (e.g., on one platform @code{off_t} may be a @code{long}, whereas on
11780: another platform it may be a @code{long long}; actually, in this case
11781: you can have this difference even on the same platform), while the
11782: resulting function-calling words are platform-independent, and calls
11783: to them are portable.
11784: 
11785: At some point in the future this interface will be superseded by a
11786: more convenient one with fewer portability issues.  But the resulting
11787: words for the C function will still have the same interface, so will
11788: not need to change the calls.
11789: 
11790: 
11791: @node Callbacks,  , Declaring C Functions, C Interface
11792: @subsection Callbacks
11793: 
11794: 
11795: 
11796: @c -------------------------------------------------------------
11797: @node Assembler and Code Words, Threading Words, C Interface, Words
11798: @section Assembler and Code Words
11799: @cindex assembler
11800: @cindex code words
11801: 
11802: @menu
11803: * Code and ;code::              
11804: * Common Assembler::            Assembler Syntax
11805: * Common Disassembler::         
11806: * 386 Assembler::               Deviations and special cases
11807: * Alpha Assembler::             Deviations and special cases
11808: * MIPS assembler::              Deviations and special cases
11809: * Other assemblers::            How to write them
11810: @end menu
11811: 
11812: @node Code and ;code, Common Assembler, Assembler and Code Words, Assembler and Code Words
11813: @subsection @code{Code} and @code{;code}
11814: 
11815: Gforth provides some words for defining primitives (words written in
11816: machine code), and for defining the machine-code equivalent of
11817: @code{DOES>}-based defining words. However, the machine-independent
11818: nature of Gforth poses a few problems: First of all, Gforth runs on
11819: several architectures, so it can provide no standard assembler. What's
11820: worse is that the register allocation not only depends on the processor,
11821: but also on the @code{gcc} version and options used.
11822: 
11823: The words that Gforth offers encapsulate some system dependences (e.g.,
11824: the header structure), so a system-independent assembler may be used in
11825: Gforth. If you do not have an assembler, you can compile machine code
11826: directly with @code{,} and @code{c,}@footnote{This isn't portable,
11827: because these words emit stuff in @i{data} space; it works because
11828: Gforth has unified code/data spaces. Assembler isn't likely to be
11829: portable anyway.}.
11830: 
11831: 
11832: doc-assembler
11833: doc-init-asm
11834: doc-code
11835: doc-end-code
11836: doc-;code
11837: doc-flush-icache
11838: 
11839: 
11840: If @code{flush-icache} does not work correctly, @code{code} words
11841: etc. will not work (reliably), either.
11842: 
11843: The typical usage of these @code{code} words can be shown most easily by
11844: analogy to the equivalent high-level defining words:
11845: 
11846: @example
11847: : foo                              code foo
11848:    <high-level Forth words>              <assembler>
11849: ;                                  end-code
11850:                                 
11851: : bar                              : bar
11852:    <high-level Forth words>           <high-level Forth words>
11853:    CREATE                             CREATE
11854:       <high-level Forth words>           <high-level Forth words>
11855:    DOES>                              ;code
11856:       <high-level Forth words>           <assembler>
11857: ;                                  end-code
11858: @end example
11859: 
11860: @c anton: the following stuff is also in "Common Assembler", in less detail.
11861: 
11862: @cindex registers of the inner interpreter
11863: In the assembly code you will want to refer to the inner interpreter's
11864: registers (e.g., the data stack pointer) and you may want to use other
11865: registers for temporary storage. Unfortunately, the register allocation
11866: is installation-dependent.
11867: 
11868: In particular, @code{ip} (Forth instruction pointer) and @code{rp}
11869: (return stack pointer) may be in different places in @code{gforth} and
11870: @code{gforth-fast}, or different installations.  This means that you
11871: cannot write a @code{NEXT} routine that works reliably on both versions
11872: or different installations; so for doing @code{NEXT}, I recommend
11873: jumping to @code{' noop >code-address}, which contains nothing but a
11874: @code{NEXT}.
11875: 
11876: For general accesses to the inner interpreter's registers, the easiest
11877: solution is to use explicit register declarations (@pxref{Explicit Reg
11878: Vars, , Variables in Specified Registers, gcc.info, GNU C Manual}) for
11879: all of the inner interpreter's registers: You have to compile Gforth
11880: with @code{-DFORCE_REG} (configure option @code{--enable-force-reg}) and
11881: the appropriate declarations must be present in the @code{machine.h}
11882: file (see @code{mips.h} for an example; you can find a full list of all
11883: declarable register symbols with @code{grep register engine.c}). If you
11884: give explicit registers to all variables that are declared at the
11885: beginning of @code{engine()}, you should be able to use the other
11886: caller-saved registers for temporary storage. Alternatively, you can use
11887: the @code{gcc} option @code{-ffixed-REG} (@pxref{Code Gen Options, ,
11888: Options for Code Generation Conventions, gcc.info, GNU C Manual}) to
11889: reserve a register (however, this restriction on register allocation may
11890: slow Gforth significantly).
11891: 
11892: If this solution is not viable (e.g., because @code{gcc} does not allow
11893: you to explicitly declare all the registers you need), you have to find
11894: out by looking at the code where the inner interpreter's registers
11895: reside and which registers can be used for temporary storage. You can
11896: get an assembly listing of the engine's code with @code{make engine.s}.
11897: 
11898: In any case, it is good practice to abstract your assembly code from the
11899: actual register allocation. E.g., if the data stack pointer resides in
11900: register @code{$17}, create an alias for this register called @code{sp},
11901: and use that in your assembly code.
11902: 
11903: @cindex code words, portable
11904: Another option for implementing normal and defining words efficiently
11905: is to add the desired functionality to the source of Gforth. For normal
11906: words you just have to edit @file{primitives} (@pxref{Automatic
11907: Generation}). Defining words (equivalent to @code{;CODE} words, for fast
11908: defined words) may require changes in @file{engine.c}, @file{kernel.fs},
11909: @file{prims2x.fs}, and possibly @file{cross.fs}.
11910: 
11911: @node Common Assembler, Common Disassembler, Code and ;code, Assembler and Code Words
11912: @subsection Common Assembler
11913: 
11914: The assemblers in Gforth generally use a postfix syntax, i.e., the
11915: instruction name follows the operands.
11916: 
11917: The operands are passed in the usual order (the same that is used in the
11918: manual of the architecture).  Since they all are Forth words, they have
11919: to be separated by spaces; you can also use Forth words to compute the
11920: operands.
11921: 
11922: The instruction names usually end with a @code{,}.  This makes it easier
11923: to visually separate instructions if you put several of them on one
11924: line; it also avoids shadowing other Forth words (e.g., @code{and}).
11925: 
11926: Registers are usually specified by number; e.g., (decimal) @code{11}
11927: specifies registers R11 and F11 on the Alpha architecture (which one,
11928: depends on the instruction).  The usual names are also available, e.g.,
11929: @code{s2} for R11 on Alpha.
11930: 
11931: Control flow is specified similar to normal Forth code (@pxref{Arbitrary
11932: control structures}), with @code{if,}, @code{ahead,}, @code{then,},
11933: @code{begin,}, @code{until,}, @code{again,}, @code{cs-roll},
11934: @code{cs-pick}, @code{else,}, @code{while,}, and @code{repeat,}.  The
11935: conditions are specified in a way specific to each assembler.
11936: 
11937: Note that the register assignments of the Gforth engine can change
11938: between Gforth versions, or even between different compilations of the
11939: same Gforth version (e.g., if you use a different GCC version).  So if
11940: you want to refer to Gforth's registers (e.g., the stack pointer or
11941: TOS), I recommend defining your own words for refering to these
11942: registers, and using them later on; then you can easily adapt to a
11943: changed register assignment.  The stability of the register assignment
11944: is usually better if you build Gforth with @code{--enable-force-reg}.
11945: 
11946: The most common use of these registers is to dispatch to the next word
11947: (the @code{next} routine).  A portable way to do this is to jump to
11948: @code{' noop >code-address} (of course, this is less efficient than
11949: integrating the @code{next} code and scheduling it well).
11950: 
11951: Another difference between Gforth version is that the top of stack is
11952: kept in memory in @code{gforth} and, on most platforms, in a register in
11953: @code{gforth-fast}.
11954: 
11955: @node  Common Disassembler, 386 Assembler, Common Assembler, Assembler and Code Words
11956: @subsection Common Disassembler
11957: @cindex disassembler, general
11958: @cindex gdb disassembler
11959: 
11960: You can disassemble a @code{code} word with @code{see}
11961: (@pxref{Debugging}).  You can disassemble a section of memory with
11962: 
11963: doc-discode
11964: 
11965: There are two kinds of disassembler for Gforth: The Forth disassembler
11966: (available on some CPUs) and the gdb disassembler (available on
11967: platforms with @command{gdb} and @command{mktemp}).  If both are
11968: available, the Forth disassembler is used by default.  If you prefer
11969: the gdb disassembler, say
11970: 
11971: @example
11972: ' disasm-gdb is discode
11973: @end example
11974: 
11975: If neither is available, @code{discode} performs @code{dump}.
11976: 
11977: The Forth disassembler generally produces output that can be fed into the
11978: assembler (i.e., same syntax, etc.).  It also includes additional
11979: information in comments.  In particular, the address of the instruction
11980: is given in a comment before the instruction.
11981: 
11982: The gdb disassembler produces output in the same format as the gdb
11983: @code{disassemble} command (@pxref{Machine Code,,Source and machine
11984: code,gdb,Debugging with GDB}), in the default flavour (AT&T syntax for
11985: the 386 and AMD64 architectures).
11986: 
11987: @code{See} may display more or less than the actual code of the word,
11988: because the recognition of the end of the code is unreliable.  You can
11989: use @code{discode} if it did not display enough.  It may display more, if
11990: the code word is not immediately followed by a named word.  If you have
11991: something else there, you can follow the word with @code{align latest ,}
11992: to ensure that the end is recognized.
11993: 
11994: @node 386 Assembler, Alpha Assembler, Common Disassembler, Assembler and Code Words
11995: @subsection 386 Assembler
11996: 
11997: The 386 assembler included in Gforth was written by Bernd Paysan, it's
11998: available under GPL, and originally part of bigFORTH.
11999: 
12000: The 386 disassembler included in Gforth was written by Andrew McKewan
12001: and is in the public domain.
12002: 
12003: The disassembler displays code in an Intel-like prefix syntax.
12004: 
12005: The assembler uses a postfix syntax with reversed parameters.
12006: 
12007: The assembler includes all instruction of the Athlon, i.e. 486 core
12008: instructions, Pentium and PPro extensions, floating point, MMX, 3Dnow!,
12009: but not ISSE. It's an integrated 16- and 32-bit assembler. Default is 32
12010: bit, you can switch to 16 bit with .86 and back to 32 bit with .386.
12011: 
12012: There are several prefixes to switch between different operation sizes,
12013: @code{.b} for byte accesses, @code{.w} for word accesses, @code{.d} for
12014: double-word accesses. Addressing modes can be switched with @code{.wa}
12015: for 16 bit addresses, and @code{.da} for 32 bit addresses. You don't
12016: need a prefix for byte register names (@code{AL} et al).
12017: 
12018: For floating point operations, the prefixes are @code{.fs} (IEEE
12019: single), @code{.fl} (IEEE double), @code{.fx} (extended), @code{.fw}
12020: (word), @code{.fd} (double-word), and @code{.fq} (quad-word).
12021: 
12022: The MMX opcodes don't have size prefixes, they are spelled out like in
12023: the Intel assembler. Instead of move from and to memory, there are
12024: PLDQ/PLDD and PSTQ/PSTD.
12025: 
12026: The registers lack the 'e' prefix; even in 32 bit mode, eax is called
12027: ax.  Immediate values are indicated by postfixing them with @code{#},
12028: e.g., @code{3 #}.  Here are some examples of addressing modes in various
12029: syntaxes:
12030: 
12031: @example
12032: Gforth          Intel (NASM)   AT&T (gas)      Name
12033: .w ax           ax             %ax             register (16 bit)
12034: ax              eax            %eax            register (32 bit)
12035: 3 #             offset 3       $3              immediate
12036: 1000 #)         byte ptr 1000  1000            displacement
12037: bx )            [ebx]          (%ebx)          base
12038: 100 di d)       100[edi]       100(%edi)       base+displacement
12039: 20 ax *4 i#)    20[eax*4]      20(,%eax,4)     (index*scale)+displacement
12040: di ax *4 i)     [edi][eax*4]   (%edi,%eax,4)   base+(index*scale)
12041: 4 bx cx di)     4[ebx][ecx]    4(%ebx,%ecx)    base+index+displacement
12042: 12 sp ax *2 di) 12[esp][eax*2] 12(%esp,%eax,2) base+(index*scale)+displacement
12043: @end example
12044: 
12045: You can use @code{L)} and @code{LI)} instead of @code{D)} and
12046: @code{DI)} to enforce 32-bit displacement fields (useful for
12047: later patching).
12048: 
12049: Some example of instructions are:
12050: 
12051: @example
12052: ax bx mov             \ move ebx,eax
12053: 3 # ax mov            \ mov eax,3
12054: 100 di d) ax mov      \ mov eax,100[edi]
12055: 4 bx cx di) ax mov    \ mov eax,4[ebx][ecx]
12056: .w ax bx mov          \ mov bx,ax
12057: @end example
12058: 
12059: The following forms are supported for binary instructions:
12060: 
12061: @example
12062: <reg> <reg> <inst>
12063: <n> # <reg> <inst>
12064: <mem> <reg> <inst>
12065: <reg> <mem> <inst>
12066: <n> # <mem> <inst>
12067: @end example
12068: 
12069: The shift/rotate syntax is:
12070: 
12071: @example
12072: <reg/mem> 1 # shl \ shortens to shift without immediate
12073: <reg/mem> 4 # shl
12074: <reg/mem> cl shl
12075: @end example
12076: 
12077: Precede string instructions (@code{movs} etc.) with @code{.b} to get
12078: the byte version.
12079: 
12080: The control structure words @code{IF} @code{UNTIL} etc. must be preceded
12081: by one of these conditions: @code{vs vc u< u>= 0= 0<> u<= u> 0< 0>= ps
12082: pc < >= <= >}. (Note that most of these words shadow some Forth words
12083: when @code{assembler} is in front of @code{forth} in the search path,
12084: e.g., in @code{code} words).  Currently the control structure words use
12085: one stack item, so you have to use @code{roll} instead of @code{cs-roll}
12086: to shuffle them (you can also use @code{swap} etc.).
12087: 
12088: Here is an example of a @code{code} word (assumes that the stack pointer
12089: is in esi and the TOS is in ebx):
12090: 
12091: @example
12092: code my+ ( n1 n2 -- n )
12093:     4 si D) bx add
12094:     4 # si add
12095:     Next
12096: end-code
12097: @end example
12098: 
12099: @node Alpha Assembler, MIPS assembler, 386 Assembler, Assembler and Code Words
12100: @subsection Alpha Assembler
12101: 
12102: The Alpha assembler and disassembler were originally written by Bernd
12103: Thallner.
12104: 
12105: The register names @code{a0}--@code{a5} are not available to avoid
12106: shadowing hex numbers.
12107: 
12108: Immediate forms of arithmetic instructions are distinguished by a
12109: @code{#} just before the @code{,}, e.g., @code{and#,} (note: @code{lda,}
12110: does not count as arithmetic instruction).
12111: 
12112: You have to specify all operands to an instruction, even those that
12113: other assemblers consider optional, e.g., the destination register for
12114: @code{br,}, or the destination register and hint for @code{jmp,}.
12115: 
12116: You can specify conditions for @code{if,} by removing the first @code{b}
12117: and the trailing @code{,} from a branch with a corresponding name; e.g.,
12118: 
12119: @example
12120: 11 fgt if, \ if F11>0e
12121:   ...
12122: endif,
12123: @end example
12124: 
12125: @code{fbgt,} gives @code{fgt}.  
12126: 
12127: @node MIPS assembler, Other assemblers, Alpha Assembler, Assembler and Code Words
12128: @subsection MIPS assembler
12129: 
12130: The MIPS assembler was originally written by Christian Pirker.
12131: 
12132: Currently the assembler and disassembler only cover the MIPS-I
12133: architecture (R3000), and don't support FP instructions.
12134: 
12135: The register names @code{$a0}--@code{$a3} are not available to avoid
12136: shadowing hex numbers.
12137: 
12138: Because there is no way to distinguish registers from immediate values,
12139: you have to explicitly use the immediate forms of instructions, i.e.,
12140: @code{addiu,}, not just @code{addu,} (@command{as} does this
12141: implicitly).
12142: 
12143: If the architecture manual specifies several formats for the instruction
12144: (e.g., for @code{jalr,}), you usually have to use the one with more
12145: arguments (i.e., two for @code{jalr,}).  When in doubt, see
12146: @code{arch/mips/testasm.fs} for an example of correct use.
12147: 
12148: Branches and jumps in the MIPS architecture have a delay slot.  You have
12149: to fill it yourself (the simplest way is to use @code{nop,}), the
12150: assembler does not do it for you (unlike @command{as}).  Even
12151: @code{if,}, @code{ahead,}, @code{until,}, @code{again,}, @code{while,},
12152: @code{else,} and @code{repeat,} need a delay slot.  Since @code{begin,}
12153: and @code{then,} just specify branch targets, they are not affected.
12154: 
12155: Note that you must not put branches, jumps, or @code{li,} into the delay
12156: slot: @code{li,} may expand to several instructions, and control flow
12157: instructions may not be put into the branch delay slot in any case.
12158: 
12159: For branches the argument specifying the target is a relative address;
12160: You have to add the address of the delay slot to get the absolute
12161: address.
12162: 
12163: The MIPS architecture also has load delay slots and restrictions on
12164: using @code{mfhi,} and @code{mflo,}; you have to order the instructions
12165: yourself to satisfy these restrictions, the assembler does not do it for
12166: you.
12167: 
12168: You can specify the conditions for @code{if,} etc. by taking a
12169: conditional branch and leaving away the @code{b} at the start and the
12170: @code{,} at the end.  E.g.,
12171: 
12172: @example
12173: 4 5 eq if,
12174:   ... \ do something if $4 equals $5
12175: then,
12176: @end example
12177: 
12178: @node Other assemblers,  , MIPS assembler, Assembler and Code Words
12179: @subsection Other assemblers
12180: 
12181: If you want to contribute another assembler/disassembler, please contact
12182: us (@email{anton@@mips.complang.tuwien.ac.at}) to check if we have such
12183: an assembler already.  If you are writing them from scratch, please use
12184: a similar syntax style as the one we use (i.e., postfix, commas at the
12185: end of the instruction names, @pxref{Common Assembler}); make the output
12186: of the disassembler be valid input for the assembler, and keep the style
12187: similar to the style we used.
12188: 
12189: Hints on implementation: The most important part is to have a good test
12190: suite that contains all instructions.  Once you have that, the rest is
12191: easy.  For actual coding you can take a look at
12192: @file{arch/mips/disasm.fs} to get some ideas on how to use data for both
12193: the assembler and disassembler, avoiding redundancy and some potential
12194: bugs.  You can also look at that file (and @pxref{Advanced does> usage
12195: example}) to get ideas how to factor a disassembler.
12196: 
12197: Start with the disassembler, because it's easier to reuse data from the
12198: disassembler for the assembler than the other way round.
12199: 
12200: For the assembler, take a look at @file{arch/alpha/asm.fs}, which shows
12201: how simple it can be.
12202: 
12203: @c -------------------------------------------------------------
12204: @node Threading Words, Passing Commands to the OS, Assembler and Code Words, Words
12205: @section Threading Words
12206: @cindex threading words
12207: 
12208: @cindex code address
12209: These words provide access to code addresses and other threading stuff
12210: in Gforth (and, possibly, other interpretive Forths). It more or less
12211: abstracts away the differences between direct and indirect threading
12212: (and, for direct threading, the machine dependences). However, at
12213: present this wordset is still incomplete. It is also pretty low-level;
12214: some day it will hopefully be made unnecessary by an internals wordset
12215: that abstracts implementation details away completely.
12216: 
12217: The terminology used here stems from indirect threaded Forth systems; in
12218: such a system, the XT of a word is represented by the CFA (code field
12219: address) of a word; the CFA points to a cell that contains the code
12220: address.  The code address is the address of some machine code that
12221: performs the run-time action of invoking the word (e.g., the
12222: @code{dovar:} routine pushes the address of the body of the word (a
12223: variable) on the stack
12224: ).
12225: 
12226: @cindex code address
12227: @cindex code field address
12228: In an indirect threaded Forth, you can get the code address of @i{name}
12229: with @code{' @i{name} @@}; in Gforth you can get it with @code{' @i{name}
12230: >code-address}, independent of the threading method.
12231: 
12232: doc-threading-method
12233: doc->code-address
12234: doc-code-address!
12235: 
12236: @cindex @code{does>}-handler
12237: @cindex @code{does>}-code
12238: For a word defined with @code{DOES>}, the code address usually points to
12239: a jump instruction (the @dfn{does-handler}) that jumps to the dodoes
12240: routine (in Gforth on some platforms, it can also point to the dodoes
12241: routine itself).  What you are typically interested in, though, is
12242: whether a word is a @code{DOES>}-defined word, and what Forth code it
12243: executes; @code{>does-code} tells you that.
12244: 
12245: doc->does-code
12246: 
12247: To create a @code{DOES>}-defined word with the following basic words,
12248: you have to set up a @code{DOES>}-handler with @code{does-handler!};
12249: @code{/does-handler} aus behind you have to place your executable Forth
12250: code.  Finally you have to create a word and modify its behaviour with
12251: @code{does-handler!}.
12252: 
12253: doc-does-code!
12254: doc-does-handler!
12255: doc-/does-handler
12256: 
12257: The code addresses produced by various defining words are produced by
12258: the following words:
12259: 
12260: doc-docol:
12261: doc-docon:
12262: doc-dovar:
12263: doc-douser:
12264: doc-dodefer:
12265: doc-dofield:
12266: 
12267: @cindex definer
12268: The following two words generalize @code{>code-address},
12269: @code{>does-code}, @code{code-address!}, and @code{does-code!}:
12270: 
12271: doc->definer
12272: doc-definer!
12273: 
12274: @c -------------------------------------------------------------
12275: @node Passing Commands to the OS, Keeping track of Time, Threading Words, Words
12276: @section Passing Commands to the Operating System
12277: @cindex operating system - passing commands
12278: @cindex shell commands
12279: 
12280: Gforth allows you to pass an arbitrary string to the host operating
12281: system shell (if such a thing exists) for execution.
12282: 
12283: doc-sh
12284: doc-system
12285: doc-$?
12286: doc-getenv
12287: 
12288: @c -------------------------------------------------------------
12289: @node Keeping track of Time, Miscellaneous Words, Passing Commands to the OS, Words
12290: @section Keeping track of Time
12291: @cindex time-related words
12292: 
12293: doc-ms
12294: doc-time&date
12295: doc-utime
12296: doc-cputime
12297: 
12298: 
12299: @c -------------------------------------------------------------
12300: @node Miscellaneous Words,  , Keeping track of Time, Words
12301: @section Miscellaneous Words
12302: @cindex miscellaneous words
12303: 
12304: @comment TODO find homes for these
12305: 
12306: These section lists the ANS Forth words that are not documented
12307: elsewhere in this manual. Ultimately, they all need proper homes.
12308: 
12309: doc-quit
12310: 
12311: The following ANS Forth words are not currently supported by Gforth 
12312: (@pxref{ANS conformance}):
12313: 
12314: @code{EDITOR} 
12315: @code{EMIT?} 
12316: @code{FORGET} 
12317: 
12318: @c ******************************************************************
12319: @node Error messages, Tools, Words, Top
12320: @chapter Error messages
12321: @cindex error messages
12322: @cindex backtrace
12323: 
12324: A typical Gforth error message looks like this:
12325: 
12326: @example
12327: in file included from \evaluated string/:-1
12328: in file included from ./yyy.fs:1
12329: ./xxx.fs:4: Invalid memory address
12330: >>>bar<<<
12331: Backtrace:
12332: $400E664C @@
12333: $400E6664 foo
12334: @end example
12335: 
12336: The message identifying the error is @code{Invalid memory address}.  The
12337: error happened when text-interpreting line 4 of the file
12338: @file{./xxx.fs}. This line is given (it contains @code{bar}), and the
12339: word on the line where the error happened, is pointed out (with
12340: @code{>>>} and @code{<<<}).
12341: 
12342: The file containing the error was included in line 1 of @file{./yyy.fs},
12343: and @file{yyy.fs} was included from a non-file (in this case, by giving
12344: @file{yyy.fs} as command-line parameter to Gforth).
12345: 
12346: At the end of the error message you find a return stack dump that can be
12347: interpreted as a backtrace (possibly empty). On top you find the top of
12348: the return stack when the @code{throw} happened, and at the bottom you
12349: find the return stack entry just above the return stack of the topmost
12350: text interpreter.
12351: 
12352: To the right of most return stack entries you see a guess for the word
12353: that pushed that return stack entry as its return address. This gives a
12354: backtrace. In our case we see that @code{bar} called @code{foo}, and
12355: @code{foo} called @code{@@} (and @code{@@} had an @emph{Invalid memory
12356: address} exception).
12357: 
12358: Note that the backtrace is not perfect: We don't know which return stack
12359: entries are return addresses (so we may get false positives); and in
12360: some cases (e.g., for @code{abort"}) we cannot determine from the return
12361: address the word that pushed the return address, so for some return
12362: addresses you see no names in the return stack dump.
12363: 
12364: @cindex @code{catch} and backtraces
12365: The return stack dump represents the return stack at the time when a
12366: specific @code{throw} was executed.  In programs that make use of
12367: @code{catch}, it is not necessarily clear which @code{throw} should be
12368: used for the return stack dump (e.g., consider one @code{throw} that
12369: indicates an error, which is caught, and during recovery another error
12370: happens; which @code{throw} should be used for the stack dump?).  Gforth
12371: presents the return stack dump for the first @code{throw} after the last
12372: executed (not returned-to) @code{catch}; this works well in the usual
12373: case.
12374: 
12375: @cindex @code{gforth-fast} and backtraces
12376: @cindex @code{gforth-fast}, difference from @code{gforth}
12377: @cindex backtraces with @code{gforth-fast}
12378: @cindex return stack dump with @code{gforth-fast}
12379: @code{Gforth} is able to do a return stack dump for throws generated
12380: from primitives (e.g., invalid memory address, stack empty etc.);
12381: @code{gforth-fast} is only able to do a return stack dump from a
12382: directly called @code{throw} (including @code{abort} etc.).  Given an
12383: exception caused by a primitive in @code{gforth-fast}, you will
12384: typically see no return stack dump at all; however, if the exception is
12385: caught by @code{catch} (e.g., for restoring some state), and then
12386: @code{throw}n again, the return stack dump will be for the first such
12387: @code{throw}.
12388: 
12389: @c ******************************************************************
12390: @node Tools, ANS conformance, Error messages, Top
12391: @chapter Tools
12392: 
12393: @menu
12394: * ANS Report::                  Report the words used, sorted by wordset.
12395: * Stack depth changes::         Where does this stack item come from?
12396: @end menu
12397: 
12398: See also @ref{Emacs and Gforth}.
12399: 
12400: @node ANS Report, Stack depth changes, Tools, Tools
12401: @section @file{ans-report.fs}: Report the words used, sorted by wordset
12402: @cindex @file{ans-report.fs}
12403: @cindex report the words used in your program
12404: @cindex words used in your program
12405: 
12406: If you want to label a Forth program as ANS Forth Program, you must
12407: document which wordsets the program uses; for extension wordsets, it is
12408: helpful to list the words the program requires from these wordsets
12409: (because Forth systems are allowed to provide only some words of them).
12410: 
12411: The @file{ans-report.fs} tool makes it easy for you to determine which
12412: words from which wordset and which non-ANS words your application
12413: uses. You simply have to include @file{ans-report.fs} before loading the
12414: program you want to check. After loading your program, you can get the
12415: report with @code{print-ans-report}. A typical use is to run this as
12416: batch job like this:
12417: @example
12418: gforth ans-report.fs myprog.fs -e "print-ans-report bye"
12419: @end example
12420: 
12421: The output looks like this (for @file{compat/control.fs}):
12422: @example
12423: The program uses the following words
12424: from CORE :
12425: : POSTPONE THEN ; immediate ?dup IF 0= 
12426: from BLOCK-EXT :
12427: \ 
12428: from FILE :
12429: ( 
12430: @end example
12431: 
12432: @subsection Caveats
12433: 
12434: Note that @file{ans-report.fs} just checks which words are used, not whether
12435: they are used in an ANS Forth conforming way!
12436: 
12437: Some words are defined in several wordsets in the
12438: standard. @file{ans-report.fs} reports them for only one of the
12439: wordsets, and not necessarily the one you expect. It depends on usage
12440: which wordset is the right one to specify. E.g., if you only use the
12441: compilation semantics of @code{S"}, it is a Core word; if you also use
12442: its interpretation semantics, it is a File word.
12443: 
12444: 
12445: @node Stack depth changes,  , ANS Report, Tools
12446: @section Stack depth changes during interpretation
12447: @cindex @file{depth-changes.fs}
12448: @cindex depth changes during interpretation
12449: @cindex stack depth changes during interpretation
12450: @cindex items on the stack after interpretation
12451: 
12452: Sometimes you notice that, after loading a file, there are items left
12453: on the stack.  The tool @file{depth-changes.fs} helps you find out
12454: quickly where in the file these stack items are coming from.
12455: 
12456: The simplest way of using @file{depth-changes.fs} is to include it
12457: before the file(s) you want to check, e.g.:
12458: 
12459: @example
12460: gforth depth-changes.fs my-file.fs
12461: @end example
12462: 
12463: This will compare the stack depths of the data and FP stack at every
12464: empty line (in interpretation state) against these depths at the last
12465: empty line (in interpretation state).  If the depths are not equal,
12466: the position in the file and the stack contents are printed with
12467: @code{~~} (@pxref{Debugging}).  This indicates that a stack depth
12468: change has occured in the paragraph of non-empty lines before the
12469: indicated line.  It is a good idea to leave an empty line at the end
12470: of the file, so the last paragraph is checked, too.
12471: 
12472: Checking only at empty lines usually works well, but sometimes you
12473: have big blocks of non-empty lines (e.g., when building a big table),
12474: and you want to know where in this block the stack depth changed.  You
12475: can check all interpreted lines with
12476: 
12477: @example
12478: gforth depth-changes.fs -e "' all-lines is depth-changes-filter" my-file.fs
12479: @end example
12480: 
12481: This checks the stack depth at every end-of-line.  So the depth change
12482: occured in the line reported by the @code{~~} (not in the line
12483: before).
12484: 
12485: Note that, while this offers better accuracy in indicating where the
12486: stack depth changes, it will often report many intentional stack depth
12487: changes (e.g., when an interpreted computation stretches across
12488: several lines).  You can suppress the checking of some lines by
12489: putting backslashes at the end of these lines (not followed by white
12490: space), and using
12491: 
12492: @example
12493: gforth depth-changes.fs -e "' most-lines is depth-changes-filter" my-file.fs
12494: @end example
12495: 
12496: @c ******************************************************************
12497: @node ANS conformance, Standard vs Extensions, Tools, Top
12498: @chapter ANS conformance
12499: @cindex ANS conformance of Gforth
12500: 
12501: To the best of our knowledge, Gforth is an
12502: 
12503: ANS Forth System
12504: @itemize @bullet
12505: @item providing the Core Extensions word set
12506: @item providing the Block word set
12507: @item providing the Block Extensions word set
12508: @item providing the Double-Number word set
12509: @item providing the Double-Number Extensions word set
12510: @item providing the Exception word set
12511: @item providing the Exception Extensions word set
12512: @item providing the Facility word set
12513: @item providing @code{EKEY}, @code{EKEY>CHAR}, @code{EKEY?}, @code{MS} and @code{TIME&DATE} from the Facility Extensions word set
12514: @item providing the File Access word set
12515: @item providing the File Access Extensions word set
12516: @item providing the Floating-Point word set
12517: @item providing the Floating-Point Extensions word set
12518: @item providing the Locals word set
12519: @item providing the Locals Extensions word set
12520: @item providing the Memory-Allocation word set
12521: @item providing the Memory-Allocation Extensions word set (that one's easy)
12522: @item providing the Programming-Tools word set
12523: @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
12524: @item providing the Search-Order word set
12525: @item providing the Search-Order Extensions word set
12526: @item providing the String word set
12527: @item providing the String Extensions word set (another easy one)
12528: @end itemize
12529: 
12530: Gforth has the following environmental restrictions:
12531: 
12532: @cindex environmental restrictions
12533: @itemize @bullet
12534: @item
12535: While processing the OS command line, if an exception is not caught,
12536: Gforth exits with a non-zero exit code instyead of performing QUIT.
12537: 
12538: @item
12539: When an @code{throw} is performed after a @code{query}, Gforth does not
12540: allways restore the input source specification in effect at the
12541: corresponding catch.
12542: 
12543: @end itemize
12544: 
12545: 
12546: @cindex system documentation
12547: In addition, ANS Forth systems are required to document certain
12548: implementation choices. This chapter tries to meet these
12549: requirements. In many cases it gives a way to ask the system for the
12550: information instead of providing the information directly, in
12551: particular, if the information depends on the processor, the operating
12552: system or the installation options chosen, or if they are likely to
12553: change during the maintenance of Gforth.
12554: 
12555: @comment The framework for the rest has been taken from pfe.
12556: 
12557: @menu
12558: * The Core Words::              
12559: * The optional Block word set::  
12560: * The optional Double Number word set::  
12561: * The optional Exception word set::  
12562: * The optional Facility word set::  
12563: * The optional File-Access word set::  
12564: * The optional Floating-Point word set::  
12565: * The optional Locals word set::  
12566: * The optional Memory-Allocation word set::  
12567: * The optional Programming-Tools word set::  
12568: * The optional Search-Order word set::  
12569: @end menu
12570: 
12571: 
12572: @c =====================================================================
12573: @node The Core Words, The optional Block word set, ANS conformance, ANS conformance
12574: @comment  node-name,  next,  previous,  up
12575: @section The Core Words
12576: @c =====================================================================
12577: @cindex core words, system documentation
12578: @cindex system documentation, core words
12579: 
12580: @menu
12581: * core-idef::                   Implementation Defined Options                   
12582: * core-ambcond::                Ambiguous Conditions                
12583: * core-other::                  Other System Documentation                  
12584: @end menu
12585: 
12586: @c ---------------------------------------------------------------------
12587: @node core-idef, core-ambcond, The Core Words, The Core Words
12588: @subsection Implementation Defined Options
12589: @c ---------------------------------------------------------------------
12590: @cindex core words, implementation-defined options
12591: @cindex implementation-defined options, core words
12592: 
12593: 
12594: @table @i
12595: @item (Cell) aligned addresses:
12596: @cindex cell-aligned addresses
12597: @cindex aligned addresses
12598: processor-dependent. Gforth's alignment words perform natural alignment
12599: (e.g., an address aligned for a datum of size 8 is divisible by
12600: 8). Unaligned accesses usually result in a @code{-23 THROW}.
12601: 
12602: @item @code{EMIT} and non-graphic characters:
12603: @cindex @code{EMIT} and non-graphic characters
12604: @cindex non-graphic characters and @code{EMIT}
12605: The character is output using the C library function (actually, macro)
12606: @code{putc}.
12607: 
12608: @item character editing of @code{ACCEPT} and @code{EXPECT}:
12609: @cindex character editing of @code{ACCEPT} and @code{EXPECT}
12610: @cindex editing in @code{ACCEPT} and @code{EXPECT}
12611: @cindex @code{ACCEPT}, editing
12612: @cindex @code{EXPECT}, editing
12613: This is modeled on the GNU readline library (@pxref{Readline
12614: Interaction, , Command Line Editing, readline, The GNU Readline
12615: Library}) with Emacs-like key bindings. @kbd{Tab} deviates a little by
12616: producing a full word completion every time you type it (instead of
12617: producing the common prefix of all completions). @xref{Command-line editing}.
12618: 
12619: @item character set:
12620: @cindex character set
12621: The character set of your computer and display device. Gforth is
12622: 8-bit-clean (but some other component in your system may make trouble).
12623: 
12624: @item Character-aligned address requirements:
12625: @cindex character-aligned address requirements
12626: installation-dependent. Currently a character is represented by a C
12627: @code{unsigned char}; in the future we might switch to @code{wchar_t}
12628: (Comments on that requested).
12629: 
12630: @item character-set extensions and matching of names:
12631: @cindex character-set extensions and matching of names
12632: @cindex case-sensitivity for name lookup
12633: @cindex name lookup, case-sensitivity
12634: @cindex locale and case-sensitivity
12635: Any character except the ASCII NUL character can be used in a
12636: name. Matching is case-insensitive (except in @code{TABLE}s). The
12637: matching is performed using the C library function @code{strncasecmp}, whose
12638: function is probably influenced by the locale. E.g., the @code{C} locale
12639: does not know about accents and umlauts, so they are matched
12640: case-sensitively in that locale. For portability reasons it is best to
12641: write programs such that they work in the @code{C} locale. Then one can
12642: use libraries written by a Polish programmer (who might use words
12643: containing ISO Latin-2 encoded characters) and by a French programmer
12644: (ISO Latin-1) in the same program (of course, @code{WORDS} will produce
12645: funny results for some of the words (which ones, depends on the font you
12646: are using)). Also, the locale you prefer may not be available in other
12647: operating systems. Hopefully, Unicode will solve these problems one day.
12648: 
12649: @item conditions under which control characters match a space delimiter:
12650: @cindex space delimiters
12651: @cindex control characters as delimiters
12652: If @code{word} is called with the space character as a delimiter, all
12653: white-space characters (as identified by the C macro @code{isspace()})
12654: are delimiters. @code{Parse}, on the other hand, treats space like other
12655: delimiters.  @code{Parse-name}, which is used by the outer
12656: interpreter (aka text interpreter) by default, treats all white-space
12657: characters as delimiters.
12658: 
12659: @item format of the control-flow stack:
12660: @cindex control-flow stack, format
12661: The data stack is used as control-flow stack. The size of a control-flow
12662: stack item in cells is given by the constant @code{cs-item-size}. At the
12663: time of this writing, an item consists of a (pointer to a) locals list
12664: (third), an address in the code (second), and a tag for identifying the
12665: item (TOS). The following tags are used: @code{defstart},
12666: @code{live-orig}, @code{dead-orig}, @code{dest}, @code{do-dest},
12667: @code{scopestart}.
12668: 
12669: @item conversion of digits > 35
12670: @cindex digits > 35
12671: The characters @code{[\]^_'} are the digits with the decimal value
12672: 36@minus{}41. There is no way to input many of the larger digits.
12673: 
12674: @item display after input terminates in @code{ACCEPT} and @code{EXPECT}:
12675: @cindex @code{EXPECT}, display after end of input
12676: @cindex @code{ACCEPT}, display after end of input
12677: The cursor is moved to the end of the entered string. If the input is
12678: terminated using the @kbd{Return} key, a space is typed.
12679: 
12680: @item exception abort sequence of @code{ABORT"}:
12681: @cindex exception abort sequence of @code{ABORT"}
12682: @cindex @code{ABORT"}, exception abort sequence
12683: The error string is stored into the variable @code{"error} and a
12684: @code{-2 throw} is performed.
12685: 
12686: @item input line terminator:
12687: @cindex input line terminator
12688: @cindex line terminator on input
12689: @cindex newline character on input
12690: For interactive input, @kbd{C-m} (CR) and @kbd{C-j} (LF) terminate
12691: lines. One of these characters is typically produced when you type the
12692: @kbd{Enter} or @kbd{Return} key.
12693: 
12694: @item maximum size of a counted string:
12695: @cindex maximum size of a counted string
12696: @cindex counted string, maximum size
12697: @code{s" /counted-string" environment? drop .}. Currently 255 characters
12698: on all platforms, but this may change.
12699: 
12700: @item maximum size of a parsed string:
12701: @cindex maximum size of a parsed string
12702: @cindex parsed string, maximum size
12703: Given by the constant @code{/line}. Currently 255 characters.
12704: 
12705: @item maximum size of a definition name, in characters:
12706: @cindex maximum size of a definition name, in characters
12707: @cindex name, maximum length
12708: MAXU/8
12709: 
12710: @item maximum string length for @code{ENVIRONMENT?}, in characters:
12711: @cindex maximum string length for @code{ENVIRONMENT?}, in characters
12712: @cindex @code{ENVIRONMENT?} string length, maximum
12713: MAXU/8
12714: 
12715: @item method of selecting the user input device:
12716: @cindex user input device, method of selecting
12717: The user input device is the standard input. There is currently no way to
12718: change it from within Gforth. However, the input can typically be
12719: redirected in the command line that starts Gforth.
12720: 
12721: @item method of selecting the user output device:
12722: @cindex user output device, method of selecting
12723: @code{EMIT} and @code{TYPE} output to the file-id stored in the value
12724: @code{outfile-id} (@code{stdout} by default). Gforth uses unbuffered
12725: output when the user output device is a terminal, otherwise the output
12726: is buffered.
12727: 
12728: @item methods of dictionary compilation:
12729: What are we expected to document here?
12730: 
12731: @item number of bits in one address unit:
12732: @cindex number of bits in one address unit
12733: @cindex address unit, size in bits
12734: @code{s" address-units-bits" environment? drop .}. 8 in all current
12735: platforms.
12736: 
12737: @item number representation and arithmetic:
12738: @cindex number representation and arithmetic
12739: Processor-dependent. Binary two's complement on all current platforms.
12740: 
12741: @item ranges for integer types:
12742: @cindex ranges for integer types
12743: @cindex integer types, ranges
12744: Installation-dependent. Make environmental queries for @code{MAX-N},
12745: @code{MAX-U}, @code{MAX-D} and @code{MAX-UD}. The lower bounds for
12746: unsigned (and positive) types is 0. The lower bound for signed types on
12747: two's complement and one's complement machines machines can be computed
12748: by adding 1 to the upper bound.
12749: 
12750: @item read-only data space regions:
12751: @cindex read-only data space regions
12752: @cindex data-space, read-only regions
12753: The whole Forth data space is writable.
12754: 
12755: @item size of buffer at @code{WORD}:
12756: @cindex size of buffer at @code{WORD}
12757: @cindex @code{WORD} buffer size
12758: @code{PAD HERE - .}. 104 characters on 32-bit machines. The buffer is
12759: shared with the pictured numeric output string. If overwriting
12760: @code{PAD} is acceptable, it is as large as the remaining dictionary
12761: space, although only as much can be sensibly used as fits in a counted
12762: string.
12763: 
12764: @item size of one cell in address units:
12765: @cindex cell size
12766: @code{1 cells .}.
12767: 
12768: @item size of one character in address units:
12769: @cindex char size
12770: @code{1 chars .}. 1 on all current platforms.
12771: 
12772: @item size of the keyboard terminal buffer:
12773: @cindex size of the keyboard terminal buffer
12774: @cindex terminal buffer, size
12775: Varies. You can determine the size at a specific time using @code{lp@@
12776: tib - .}. It is shared with the locals stack and TIBs of files that
12777: include the current file. You can change the amount of space for TIBs
12778: and locals stack at Gforth startup with the command line option
12779: @code{-l}.
12780: 
12781: @item size of the pictured numeric output buffer:
12782: @cindex size of the pictured numeric output buffer
12783: @cindex pictured numeric output buffer, size
12784: @code{PAD HERE - .}. 104 characters on 32-bit machines. The buffer is
12785: shared with @code{WORD}.
12786: 
12787: @item size of the scratch area returned by @code{PAD}:
12788: @cindex size of the scratch area returned by @code{PAD}
12789: @cindex @code{PAD} size
12790: The remainder of dictionary space. @code{unused pad here - - .}.
12791: 
12792: @item system case-sensitivity characteristics:
12793: @cindex case-sensitivity characteristics
12794: Dictionary searches are case-insensitive (except in
12795: @code{TABLE}s). However, as explained above under @i{character-set
12796: extensions}, the matching for non-ASCII characters is determined by the
12797: locale you are using. In the default @code{C} locale all non-ASCII
12798: characters are matched case-sensitively.
12799: 
12800: @item system prompt:
12801: @cindex system prompt
12802: @cindex prompt
12803: @code{ ok} in interpret state, @code{ compiled} in compile state.
12804: 
12805: @item division rounding:
12806: @cindex division rounding
12807: installation dependent. @code{s" floored" environment? drop .}. We leave
12808: the choice to @code{gcc} (what to use for @code{/}) and to you (whether
12809: to use @code{fm/mod}, @code{sm/rem} or simply @code{/}).
12810: 
12811: @item values of @code{STATE} when true:
12812: @cindex @code{STATE} values
12813: -1.
12814: 
12815: @item values returned after arithmetic overflow:
12816: On two's complement machines, arithmetic is performed modulo
12817: 2**bits-per-cell for single arithmetic and 4**bits-per-cell for double
12818: arithmetic (with appropriate mapping for signed types). Division by zero
12819: typically results in a @code{-55 throw} (Floating-point unidentified
12820: fault) or @code{-10 throw} (divide by zero).
12821: 
12822: @item whether the current definition can be found after @t{DOES>}:
12823: @cindex @t{DOES>}, visibility of current definition
12824: No.
12825: 
12826: @end table
12827: 
12828: @c ---------------------------------------------------------------------
12829: @node core-ambcond, core-other, core-idef, The Core Words
12830: @subsection Ambiguous conditions
12831: @c ---------------------------------------------------------------------
12832: @cindex core words, ambiguous conditions
12833: @cindex ambiguous conditions, core words
12834: 
12835: @table @i
12836: 
12837: @item a name is neither a word nor a number:
12838: @cindex name not found
12839: @cindex undefined word
12840: @code{-13 throw} (Undefined word).
12841: 
12842: @item a definition name exceeds the maximum length allowed:
12843: @cindex word name too long
12844: @code{-19 throw} (Word name too long)
12845: 
12846: @item addressing a region not inside the various data spaces of the forth system:
12847: @cindex Invalid memory address
12848: The stacks, code space and header space are accessible. Machine code space is
12849: typically readable. Accessing other addresses gives results dependent on
12850: the operating system. On decent systems: @code{-9 throw} (Invalid memory
12851: address).
12852: 
12853: @item argument type incompatible with parameter:
12854: @cindex argument type mismatch
12855: This is usually not caught. Some words perform checks, e.g., the control
12856: flow words, and issue a @code{ABORT"} or @code{-12 THROW} (Argument type
12857: mismatch).
12858: 
12859: @item attempting to obtain the execution token of a word with undefined execution semantics:
12860: @cindex Interpreting a compile-only word, for @code{'} etc.
12861: @cindex execution token of words with undefined execution semantics
12862: @code{-14 throw} (Interpreting a compile-only word). In some cases, you
12863: get an execution token for @code{compile-only-error} (which performs a
12864: @code{-14 throw} when executed).
12865: 
12866: @item dividing by zero:
12867: @cindex dividing by zero
12868: @cindex floating point unidentified fault, integer division
12869: On some platforms, this produces a @code{-10 throw} (Division by
12870: zero); on other systems, this typically results in a @code{-55 throw}
12871: (Floating-point unidentified fault).
12872: 
12873: @item insufficient data stack or return stack space:
12874: @cindex insufficient data stack or return stack space
12875: @cindex stack overflow
12876: @cindex address alignment exception, stack overflow
12877: @cindex Invalid memory address, stack overflow
12878: Depending on the operating system, the installation, and the invocation
12879: of Gforth, this is either checked by the memory management hardware, or
12880: it is not checked. If it is checked, you typically get a @code{-3 throw}
12881: (Stack overflow), @code{-5 throw} (Return stack overflow), or @code{-9
12882: throw} (Invalid memory address) (depending on the platform and how you
12883: achieved the overflow) as soon as the overflow happens. If it is not
12884: checked, overflows typically result in mysterious illegal memory
12885: accesses, producing @code{-9 throw} (Invalid memory address) or
12886: @code{-23 throw} (Address alignment exception); they might also destroy
12887: the internal data structure of @code{ALLOCATE} and friends, resulting in
12888: various errors in these words.
12889: 
12890: @item insufficient space for loop control parameters:
12891: @cindex insufficient space for loop control parameters
12892: Like other return stack overflows.
12893: 
12894: @item insufficient space in the dictionary:
12895: @cindex insufficient space in the dictionary
12896: @cindex dictionary overflow
12897: If you try to allot (either directly with @code{allot}, or indirectly
12898: with @code{,}, @code{create} etc.) more memory than available in the
12899: dictionary, you get a @code{-8 throw} (Dictionary overflow). If you try
12900: to access memory beyond the end of the dictionary, the results are
12901: similar to stack overflows.
12902: 
12903: @item interpreting a word with undefined interpretation semantics:
12904: @cindex interpreting a word with undefined interpretation semantics
12905: @cindex Interpreting a compile-only word
12906: For some words, we have defined interpretation semantics. For the
12907: others: @code{-14 throw} (Interpreting a compile-only word).
12908: 
12909: @item modifying the contents of the input buffer or a string literal:
12910: @cindex modifying the contents of the input buffer or a string literal
12911: These are located in writable memory and can be modified.
12912: 
12913: @item overflow of the pictured numeric output string:
12914: @cindex overflow of the pictured numeric output string
12915: @cindex pictured numeric output string, overflow
12916: @code{-17 throw} (Pictured numeric ouput string overflow).
12917: 
12918: @item parsed string overflow:
12919: @cindex parsed string overflow
12920: @code{PARSE} cannot overflow. @code{WORD} does not check for overflow.
12921: 
12922: @item producing a result out of range:
12923: @cindex result out of range
12924: On two's complement machines, arithmetic is performed modulo
12925: 2**bits-per-cell for single arithmetic and 4**bits-per-cell for double
12926: arithmetic (with appropriate mapping for signed types). Division by zero
12927: typically results in a @code{-10 throw} (divide by zero) or @code{-55
12928: throw} (floating point unidentified fault). @code{convert} and
12929: @code{>number} currently overflow silently.
12930: 
12931: @item reading from an empty data or return stack:
12932: @cindex stack empty
12933: @cindex stack underflow
12934: @cindex return stack underflow
12935: The data stack is checked by the outer (aka text) interpreter after
12936: every word executed. If it has underflowed, a @code{-4 throw} (Stack
12937: underflow) is performed. Apart from that, stacks may be checked or not,
12938: depending on operating system, installation, and invocation. If they are
12939: caught by a check, they typically result in @code{-4 throw} (Stack
12940: underflow), @code{-6 throw} (Return stack underflow) or @code{-9 throw}
12941: (Invalid memory address), depending on the platform and which stack
12942: underflows and by how much. Note that even if the system uses checking
12943: (through the MMU), your program may have to underflow by a significant
12944: number of stack items to trigger the reaction (the reason for this is
12945: that the MMU, and therefore the checking, works with a page-size
12946: granularity).  If there is no checking, the symptoms resulting from an
12947: underflow are similar to those from an overflow.  Unbalanced return
12948: stack errors can result in a variety of symptoms, including @code{-9 throw}
12949: (Invalid memory address) and Illegal Instruction (typically @code{-260
12950: throw}).
12951: 
12952: @item unexpected end of the input buffer, resulting in an attempt to use a zero-length string as a name:
12953: @cindex unexpected end of the input buffer
12954: @cindex zero-length string as a name
12955: @cindex Attempt to use zero-length string as a name
12956: @code{Create} and its descendants perform a @code{-16 throw} (Attempt to
12957: use zero-length string as a name). Words like @code{'} probably will not
12958: find what they search. Note that it is possible to create zero-length
12959: names with @code{nextname} (should it not?).
12960: 
12961: @item @code{>IN} greater than input buffer:
12962: @cindex @code{>IN} greater than input buffer
12963: The next invocation of a parsing word returns a string with length 0.
12964: 
12965: @item @code{RECURSE} appears after @code{DOES>}:
12966: @cindex @code{RECURSE} appears after @code{DOES>}
12967: Compiles a recursive call to the defining word, not to the defined word.
12968: 
12969: @item argument input source different than current input source for @code{RESTORE-INPUT}:
12970: @cindex argument input source different than current input source for @code{RESTORE-INPUT}
12971: @cindex argument type mismatch, @code{RESTORE-INPUT}
12972: @cindex @code{RESTORE-INPUT}, Argument type mismatch
12973: @code{-12 THROW}. Note that, once an input file is closed (e.g., because
12974: the end of the file was reached), its source-id may be
12975: reused. Therefore, restoring an input source specification referencing a
12976: closed file may lead to unpredictable results instead of a @code{-12
12977: THROW}.
12978: 
12979: In the future, Gforth may be able to restore input source specifications
12980: from other than the current input source.
12981: 
12982: @item data space containing definitions gets de-allocated:
12983: @cindex data space containing definitions gets de-allocated
12984: Deallocation with @code{allot} is not checked. This typically results in
12985: memory access faults or execution of illegal instructions.
12986: 
12987: @item data space read/write with incorrect alignment:
12988: @cindex data space read/write with incorrect alignment
12989: @cindex alignment faults
12990: @cindex address alignment exception
12991: Processor-dependent. Typically results in a @code{-23 throw} (Address
12992: alignment exception). Under Linux-Intel on a 486 or later processor with
12993: alignment turned on, incorrect alignment results in a @code{-9 throw}
12994: (Invalid memory address). There are reportedly some processors with
12995: alignment restrictions that do not report violations.
12996: 
12997: @item data space pointer not properly aligned, @code{,}, @code{C,}:
12998: @cindex data space pointer not properly aligned, @code{,}, @code{C,}
12999: Like other alignment errors.
13000: 
13001: @item less than u+2 stack items (@code{PICK} and @code{ROLL}):
13002: Like other stack underflows.
13003: 
13004: @item loop control parameters not available:
13005: @cindex loop control parameters not available
13006: Not checked. The counted loop words simply assume that the top of return
13007: stack items are loop control parameters and behave accordingly.
13008: 
13009: @item most recent definition does not have a name (@code{IMMEDIATE}):
13010: @cindex most recent definition does not have a name (@code{IMMEDIATE})
13011: @cindex last word was headerless
13012: @code{abort" last word was headerless"}.
13013: 
13014: @item name not defined by @code{VALUE} used by @code{TO}:
13015: @cindex name not defined by @code{VALUE} used by @code{TO}
13016: @cindex @code{TO} on non-@code{VALUE}s
13017: @cindex Invalid name argument, @code{TO}
13018: @code{-32 throw} (Invalid name argument) (unless name is a local or was
13019: defined by @code{CONSTANT}; in the latter case it just changes the constant).
13020: 
13021: @item name not found (@code{'}, @code{POSTPONE}, @code{[']}, @code{[COMPILE]}):
13022: @cindex name not found (@code{'}, @code{POSTPONE}, @code{[']}, @code{[COMPILE]})
13023: @cindex undefined word, @code{'}, @code{POSTPONE}, @code{[']}, @code{[COMPILE]}
13024: @code{-13 throw} (Undefined word)
13025: 
13026: @item parameters are not of the same type (@code{DO}, @code{?DO}, @code{WITHIN}):
13027: @cindex parameters are not of the same type (@code{DO}, @code{?DO}, @code{WITHIN})
13028: Gforth behaves as if they were of the same type. I.e., you can predict
13029: the behaviour by interpreting all parameters as, e.g., signed.
13030: 
13031: @item @code{POSTPONE} or @code{[COMPILE]} applied to @code{TO}:
13032: @cindex @code{POSTPONE} or @code{[COMPILE]} applied to @code{TO}
13033: Assume @code{: X POSTPONE TO ; IMMEDIATE}. @code{X} performs the
13034: compilation semantics of @code{TO}.
13035: 
13036: @item String longer than a counted string returned by @code{WORD}:
13037: @cindex string longer than a counted string returned by @code{WORD}
13038: @cindex @code{WORD}, string overflow
13039: Not checked. The string will be ok, but the count will, of course,
13040: contain only the least significant bits of the length.
13041: 
13042: @item u greater than or equal to the number of bits in a cell (@code{LSHIFT}, @code{RSHIFT}):
13043: @cindex @code{LSHIFT}, large shift counts
13044: @cindex @code{RSHIFT}, large shift counts
13045: Processor-dependent. Typical behaviours are returning 0 and using only
13046: the low bits of the shift count.
13047: 
13048: @item word not defined via @code{CREATE}:
13049: @cindex @code{>BODY} of non-@code{CREATE}d words
13050: @code{>BODY} produces the PFA of the word no matter how it was defined.
13051: 
13052: @cindex @code{DOES>} of non-@code{CREATE}d words
13053: @code{DOES>} changes the execution semantics of the last defined word no
13054: matter how it was defined. E.g., @code{CONSTANT DOES>} is equivalent to
13055: @code{CREATE , DOES>}.
13056: 
13057: @item words improperly used outside @code{<#} and @code{#>}:
13058: Not checked. As usual, you can expect memory faults.
13059: 
13060: @end table
13061: 
13062: 
13063: @c ---------------------------------------------------------------------
13064: @node core-other,  , core-ambcond, The Core Words
13065: @subsection Other system documentation
13066: @c ---------------------------------------------------------------------
13067: @cindex other system documentation, core words
13068: @cindex core words, other system documentation
13069: 
13070: @table @i
13071: @item nonstandard words using @code{PAD}:
13072: @cindex @code{PAD} use by nonstandard words
13073: None.
13074: 
13075: @item operator's terminal facilities available:
13076: @cindex operator's terminal facilities available
13077: After processing the OS's command line, Gforth goes into interactive mode,
13078: and you can give commands to Gforth interactively. The actual facilities
13079: available depend on how you invoke Gforth.
13080: 
13081: @item program data space available:
13082: @cindex program data space available
13083: @cindex data space available
13084: @code{UNUSED .} gives the remaining dictionary space. The total
13085: dictionary space can be specified with the @code{-m} switch
13086: (@pxref{Invoking Gforth}) when Gforth starts up.
13087: 
13088: @item return stack space available:
13089: @cindex return stack space available
13090: You can compute the total return stack space in cells with
13091: @code{s" RETURN-STACK-CELLS" environment? drop .}. You can specify it at
13092: startup time with the @code{-r} switch (@pxref{Invoking Gforth}).
13093: 
13094: @item stack space available:
13095: @cindex stack space available
13096: You can compute the total data stack space in cells with
13097: @code{s" STACK-CELLS" environment? drop .}. You can specify it at
13098: startup time with the @code{-d} switch (@pxref{Invoking Gforth}).
13099: 
13100: @item system dictionary space required, in address units:
13101: @cindex system dictionary space required, in address units
13102: Type @code{here forthstart - .} after startup. At the time of this
13103: writing, this gives 80080 (bytes) on a 32-bit system.
13104: @end table
13105: 
13106: 
13107: @c =====================================================================
13108: @node The optional Block word set, The optional Double Number word set, The Core Words, ANS conformance
13109: @section The optional Block word set
13110: @c =====================================================================
13111: @cindex system documentation, block words
13112: @cindex block words, system documentation
13113: 
13114: @menu
13115: * block-idef::                  Implementation Defined Options
13116: * block-ambcond::               Ambiguous Conditions               
13117: * block-other::                 Other System Documentation                 
13118: @end menu
13119: 
13120: 
13121: @c ---------------------------------------------------------------------
13122: @node block-idef, block-ambcond, The optional Block word set, The optional Block word set
13123: @subsection Implementation Defined Options
13124: @c ---------------------------------------------------------------------
13125: @cindex implementation-defined options, block words
13126: @cindex block words, implementation-defined options
13127: 
13128: @table @i
13129: @item the format for display by @code{LIST}:
13130: @cindex @code{LIST} display format
13131: First the screen number is displayed, then 16 lines of 64 characters,
13132: each line preceded by the line number.
13133: 
13134: @item the length of a line affected by @code{\}:
13135: @cindex length of a line affected by @code{\}
13136: @cindex @code{\}, line length in blocks
13137: 64 characters.
13138: @end table
13139: 
13140: 
13141: @c ---------------------------------------------------------------------
13142: @node block-ambcond, block-other, block-idef, The optional Block word set
13143: @subsection Ambiguous conditions
13144: @c ---------------------------------------------------------------------
13145: @cindex block words, ambiguous conditions
13146: @cindex ambiguous conditions, block words
13147: 
13148: @table @i
13149: @item correct block read was not possible:
13150: @cindex block read not possible
13151: Typically results in a @code{throw} of some OS-derived value (between
13152: -512 and -2048). If the blocks file was just not long enough, blanks are
13153: supplied for the missing portion.
13154: 
13155: @item I/O exception in block transfer:
13156: @cindex I/O exception in block transfer
13157: @cindex block transfer, I/O exception
13158: Typically results in a @code{throw} of some OS-derived value (between
13159: -512 and -2048).
13160: 
13161: @item invalid block number:
13162: @cindex invalid block number
13163: @cindex block number invalid
13164: @code{-35 throw} (Invalid block number)
13165: 
13166: @item a program directly alters the contents of @code{BLK}:
13167: @cindex @code{BLK}, altering @code{BLK}
13168: The input stream is switched to that other block, at the same
13169: position. If the storing to @code{BLK} happens when interpreting
13170: non-block input, the system will get quite confused when the block ends.
13171: 
13172: @item no current block buffer for @code{UPDATE}:
13173: @cindex @code{UPDATE}, no current block buffer
13174: @code{UPDATE} has no effect.
13175: 
13176: @end table
13177: 
13178: @c ---------------------------------------------------------------------
13179: @node block-other,  , block-ambcond, The optional Block word set
13180: @subsection Other system documentation
13181: @c ---------------------------------------------------------------------
13182: @cindex other system documentation, block words
13183: @cindex block words, other system documentation
13184: 
13185: @table @i
13186: @item any restrictions a multiprogramming system places on the use of buffer addresses:
13187: No restrictions (yet).
13188: 
13189: @item the number of blocks available for source and data:
13190: depends on your disk space.
13191: 
13192: @end table
13193: 
13194: 
13195: @c =====================================================================
13196: @node The optional Double Number word set, The optional Exception word set, The optional Block word set, ANS conformance
13197: @section The optional Double Number word set
13198: @c =====================================================================
13199: @cindex system documentation, double words
13200: @cindex double words, system documentation
13201: 
13202: @menu
13203: * double-ambcond::              Ambiguous Conditions              
13204: @end menu
13205: 
13206: 
13207: @c ---------------------------------------------------------------------
13208: @node double-ambcond,  , The optional Double Number word set, The optional Double Number word set
13209: @subsection Ambiguous conditions
13210: @c ---------------------------------------------------------------------
13211: @cindex double words, ambiguous conditions
13212: @cindex ambiguous conditions, double words
13213: 
13214: @table @i
13215: @item @i{d} outside of range of @i{n} in @code{D>S}:
13216: @cindex @code{D>S}, @i{d} out of range of @i{n} 
13217: The least significant cell of @i{d} is produced.
13218: 
13219: @end table
13220: 
13221: 
13222: @c =====================================================================
13223: @node The optional Exception word set, The optional Facility word set, The optional Double Number word set, ANS conformance
13224: @section The optional Exception word set
13225: @c =====================================================================
13226: @cindex system documentation, exception words
13227: @cindex exception words, system documentation
13228: 
13229: @menu
13230: * exception-idef::              Implementation Defined Options              
13231: @end menu
13232: 
13233: 
13234: @c ---------------------------------------------------------------------
13235: @node exception-idef,  , The optional Exception word set, The optional Exception word set
13236: @subsection Implementation Defined Options
13237: @c ---------------------------------------------------------------------
13238: @cindex implementation-defined options, exception words
13239: @cindex exception words, implementation-defined options
13240: 
13241: @table @i
13242: @item @code{THROW}-codes used in the system:
13243: @cindex @code{THROW}-codes used in the system
13244: The codes -256@minus{}-511 are used for reporting signals. The mapping
13245: from OS signal numbers to throw codes is -256@minus{}@i{signal}. The
13246: codes -512@minus{}-2047 are used for OS errors (for file and memory
13247: allocation operations). The mapping from OS error numbers to throw codes
13248: is -512@minus{}@code{errno}. One side effect of this mapping is that
13249: undefined OS errors produce a message with a strange number; e.g.,
13250: @code{-1000 THROW} results in @code{Unknown error 488} on my system.
13251: @end table
13252: 
13253: @c =====================================================================
13254: @node The optional Facility word set, The optional File-Access word set, The optional Exception word set, ANS conformance
13255: @section The optional Facility word set
13256: @c =====================================================================
13257: @cindex system documentation, facility words
13258: @cindex facility words, system documentation
13259: 
13260: @menu
13261: * facility-idef::               Implementation Defined Options               
13262: * facility-ambcond::            Ambiguous Conditions            
13263: @end menu
13264: 
13265: 
13266: @c ---------------------------------------------------------------------
13267: @node facility-idef, facility-ambcond, The optional Facility word set, The optional Facility word set
13268: @subsection Implementation Defined Options
13269: @c ---------------------------------------------------------------------
13270: @cindex implementation-defined options, facility words
13271: @cindex facility words, implementation-defined options
13272: 
13273: @table @i
13274: @item encoding of keyboard events (@code{EKEY}):
13275: @cindex keyboard events, encoding in @code{EKEY}
13276: @cindex @code{EKEY}, encoding of keyboard events
13277: Keys corresponding to ASCII characters are encoded as ASCII characters.
13278: Other keys are encoded with the constants @code{k-left}, @code{k-right},
13279: @code{k-up}, @code{k-down}, @code{k-home}, @code{k-end}, @code{k1},
13280: @code{k2}, @code{k3}, @code{k4}, @code{k5}, @code{k6}, @code{k7},
13281: @code{k8}, @code{k9}, @code{k10}, @code{k11}, @code{k12}.
13282: 
13283: 
13284: @item duration of a system clock tick:
13285: @cindex duration of a system clock tick
13286: @cindex clock tick duration
13287: System dependent. With respect to @code{MS}, the time is specified in
13288: microseconds. How well the OS and the hardware implement this, is
13289: another question.
13290: 
13291: @item repeatability to be expected from the execution of @code{MS}:
13292: @cindex repeatability to be expected from the execution of @code{MS}
13293: @cindex @code{MS}, repeatability to be expected
13294: System dependent. On Unix, a lot depends on load. If the system is
13295: lightly loaded, and the delay is short enough that Gforth does not get
13296: swapped out, the performance should be acceptable. Under MS-DOS and
13297: other single-tasking systems, it should be good.
13298: 
13299: @end table
13300: 
13301: 
13302: @c ---------------------------------------------------------------------
13303: @node facility-ambcond,  , facility-idef, The optional Facility word set
13304: @subsection Ambiguous conditions
13305: @c ---------------------------------------------------------------------
13306: @cindex facility words, ambiguous conditions
13307: @cindex ambiguous conditions, facility words
13308: 
13309: @table @i
13310: @item @code{AT-XY} can't be performed on user output device:
13311: @cindex @code{AT-XY} can't be performed on user output device
13312: Largely terminal dependent. No range checks are done on the arguments.
13313: No errors are reported. You may see some garbage appearing, you may see
13314: simply nothing happen.
13315: 
13316: @end table
13317: 
13318: 
13319: @c =====================================================================
13320: @node The optional File-Access word set, The optional Floating-Point word set, The optional Facility word set, ANS conformance
13321: @section The optional File-Access word set
13322: @c =====================================================================
13323: @cindex system documentation, file words
13324: @cindex file words, system documentation
13325: 
13326: @menu
13327: * file-idef::                   Implementation Defined Options
13328: * file-ambcond::                Ambiguous Conditions                
13329: @end menu
13330: 
13331: @c ---------------------------------------------------------------------
13332: @node file-idef, file-ambcond, The optional File-Access word set, The optional File-Access word set
13333: @subsection Implementation Defined Options
13334: @c ---------------------------------------------------------------------
13335: @cindex implementation-defined options, file words
13336: @cindex file words, implementation-defined options
13337: 
13338: @table @i
13339: @item file access methods used:
13340: @cindex file access methods used
13341: @code{R/O}, @code{R/W} and @code{BIN} work as you would
13342: expect. @code{W/O} translates into the C file opening mode @code{w} (or
13343: @code{wb}): The file is cleared, if it exists, and created, if it does
13344: not (with both @code{open-file} and @code{create-file}).  Under Unix
13345: @code{create-file} creates a file with 666 permissions modified by your
13346: umask.
13347: 
13348: @item file exceptions:
13349: @cindex file exceptions
13350: The file words do not raise exceptions (except, perhaps, memory access
13351: faults when you pass illegal addresses or file-ids).
13352: 
13353: @item file line terminator:
13354: @cindex file line terminator
13355: System-dependent. Gforth uses C's newline character as line
13356: terminator. What the actual character code(s) of this are is
13357: system-dependent.
13358: 
13359: @item file name format:
13360: @cindex file name format
13361: System dependent. Gforth just uses the file name format of your OS.
13362: 
13363: @item information returned by @code{FILE-STATUS}:
13364: @cindex @code{FILE-STATUS}, returned information
13365: @code{FILE-STATUS} returns the most powerful file access mode allowed
13366: for the file: Either @code{R/O}, @code{W/O} or @code{R/W}. If the file
13367: cannot be accessed, @code{R/O BIN} is returned. @code{BIN} is applicable
13368: along with the returned mode.
13369: 
13370: @item input file state after an exception when including source:
13371: @cindex exception when including source
13372: All files that are left via the exception are closed.
13373: 
13374: @item @i{ior} values and meaning:
13375: @cindex @i{ior} values and meaning
13376: @cindex @i{wior} values and meaning
13377: The @i{ior}s returned by the file and memory allocation words are
13378: intended as throw codes. They typically are in the range
13379: -512@minus{}-2047 of OS errors.  The mapping from OS error numbers to
13380: @i{ior}s is -512@minus{}@i{errno}.
13381: 
13382: @item maximum depth of file input nesting:
13383: @cindex maximum depth of file input nesting
13384: @cindex file input nesting, maximum depth
13385: limited by the amount of return stack, locals/TIB stack, and the number
13386: of open files available. This should not give you troubles.
13387: 
13388: @item maximum size of input line:
13389: @cindex maximum size of input line
13390: @cindex input line size, maximum
13391: @code{/line}. Currently 255.
13392: 
13393: @item methods of mapping block ranges to files:
13394: @cindex mapping block ranges to files
13395: @cindex files containing blocks
13396: @cindex blocks in files
13397: By default, blocks are accessed in the file @file{blocks.fb} in the
13398: current working directory. The file can be switched with @code{USE}.
13399: 
13400: @item number of string buffers provided by @code{S"}:
13401: @cindex @code{S"}, number of string buffers
13402: 1
13403: 
13404: @item size of string buffer used by @code{S"}:
13405: @cindex @code{S"}, size of string buffer
13406: @code{/line}. currently 255.
13407: 
13408: @end table
13409: 
13410: @c ---------------------------------------------------------------------
13411: @node file-ambcond,  , file-idef, The optional File-Access word set
13412: @subsection Ambiguous conditions
13413: @c ---------------------------------------------------------------------
13414: @cindex file words, ambiguous conditions
13415: @cindex ambiguous conditions, file words
13416: 
13417: @table @i
13418: @item attempting to position a file outside its boundaries:
13419: @cindex @code{REPOSITION-FILE}, outside the file's boundaries
13420: @code{REPOSITION-FILE} is performed as usual: Afterwards,
13421: @code{FILE-POSITION} returns the value given to @code{REPOSITION-FILE}.
13422: 
13423: @item attempting to read from file positions not yet written:
13424: @cindex reading from file positions not yet written
13425: End-of-file, i.e., zero characters are read and no error is reported.
13426: 
13427: @item @i{file-id} is invalid (@code{INCLUDE-FILE}):
13428: @cindex @code{INCLUDE-FILE}, @i{file-id} is invalid 
13429: An appropriate exception may be thrown, but a memory fault or other
13430: problem is more probable.
13431: 
13432: @item I/O exception reading or closing @i{file-id} (@code{INCLUDE-FILE}, @code{INCLUDED}):
13433: @cindex @code{INCLUDE-FILE}, I/O exception reading or closing @i{file-id}
13434: @cindex @code{INCLUDED}, I/O exception reading or closing @i{file-id}
13435: The @i{ior} produced by the operation, that discovered the problem, is
13436: thrown.
13437: 
13438: @item named file cannot be opened (@code{INCLUDED}):
13439: @cindex @code{INCLUDED}, named file cannot be opened
13440: The @i{ior} produced by @code{open-file} is thrown.
13441: 
13442: @item requesting an unmapped block number:
13443: @cindex unmapped block numbers
13444: There are no unmapped legal block numbers. On some operating systems,
13445: writing a block with a large number may overflow the file system and
13446: have an error message as consequence.
13447: 
13448: @item using @code{source-id} when @code{blk} is non-zero:
13449: @cindex @code{SOURCE-ID}, behaviour when @code{BLK} is non-zero
13450: @code{source-id} performs its function. Typically it will give the id of
13451: the source which loaded the block. (Better ideas?)
13452: 
13453: @end table
13454: 
13455: 
13456: @c =====================================================================
13457: @node  The optional Floating-Point word set, The optional Locals word set, The optional File-Access word set, ANS conformance
13458: @section The optional Floating-Point word set
13459: @c =====================================================================
13460: @cindex system documentation, floating-point words
13461: @cindex floating-point words, system documentation
13462: 
13463: @menu
13464: * floating-idef::               Implementation Defined Options
13465: * floating-ambcond::            Ambiguous Conditions            
13466: @end menu
13467: 
13468: 
13469: @c ---------------------------------------------------------------------
13470: @node floating-idef, floating-ambcond, The optional Floating-Point word set, The optional Floating-Point word set
13471: @subsection Implementation Defined Options
13472: @c ---------------------------------------------------------------------
13473: @cindex implementation-defined options, floating-point words
13474: @cindex floating-point words, implementation-defined options
13475: 
13476: @table @i
13477: @item format and range of floating point numbers:
13478: @cindex format and range of floating point numbers
13479: @cindex floating point numbers, format and range
13480: System-dependent; the @code{double} type of C.
13481: 
13482: @item results of @code{REPRESENT} when @i{float} is out of range:
13483: @cindex  @code{REPRESENT}, results when @i{float} is out of range
13484: System dependent; @code{REPRESENT} is implemented using the C library
13485: function @code{ecvt()} and inherits its behaviour in this respect.
13486: 
13487: @item rounding or truncation of floating-point numbers:
13488: @cindex rounding of floating-point numbers
13489: @cindex truncation of floating-point numbers
13490: @cindex floating-point numbers, rounding or truncation
13491: System dependent; the rounding behaviour is inherited from the hosting C
13492: compiler. IEEE-FP-based (i.e., most) systems by default round to
13493: nearest, and break ties by rounding to even (i.e., such that the last
13494: bit of the mantissa is 0).
13495: 
13496: @item size of floating-point stack:
13497: @cindex floating-point stack size
13498: @code{s" FLOATING-STACK" environment? drop .} gives the total size of
13499: the floating-point stack (in floats). You can specify this on startup
13500: with the command-line option @code{-f} (@pxref{Invoking Gforth}).
13501: 
13502: @item width of floating-point stack:
13503: @cindex floating-point stack width 
13504: @code{1 floats}.
13505: 
13506: @end table
13507: 
13508: 
13509: @c ---------------------------------------------------------------------
13510: @node floating-ambcond,  , floating-idef, The optional Floating-Point word set
13511: @subsection Ambiguous conditions
13512: @c ---------------------------------------------------------------------
13513: @cindex floating-point words, ambiguous conditions
13514: @cindex ambiguous conditions, floating-point words
13515: 
13516: @table @i
13517: @item @code{df@@} or @code{df!} used with an address that is not double-float  aligned:
13518: @cindex @code{df@@} or @code{df!} used with an address that is not double-float  aligned
13519: System-dependent. Typically results in a @code{-23 THROW} like other
13520: alignment violations.
13521: 
13522: @item @code{f@@} or @code{f!} used with an address that is not float  aligned:
13523: @cindex @code{f@@} used with an address that is not float aligned
13524: @cindex @code{f!} used with an address that is not float aligned
13525: System-dependent. Typically results in a @code{-23 THROW} like other
13526: alignment violations.
13527: 
13528: @item floating-point result out of range:
13529: @cindex floating-point result out of range
13530: System-dependent. Can result in a @code{-43 throw} (floating point
13531: overflow), @code{-54 throw} (floating point underflow), @code{-41 throw}
13532: (floating point inexact result), @code{-55 THROW} (Floating-point
13533: unidentified fault), or can produce a special value representing, e.g.,
13534: Infinity.
13535: 
13536: @item @code{sf@@} or @code{sf!} used with an address that is not single-float  aligned:
13537: @cindex @code{sf@@} or @code{sf!} used with an address that is not single-float  aligned
13538: System-dependent. Typically results in an alignment fault like other
13539: alignment violations.
13540: 
13541: @item @code{base} is not decimal (@code{REPRESENT}, @code{F.}, @code{FE.}, @code{FS.}):
13542: @cindex @code{base} is not decimal (@code{REPRESENT}, @code{F.}, @code{FE.}, @code{FS.})
13543: The floating-point number is converted into decimal nonetheless.
13544: 
13545: @item Both arguments are equal to zero (@code{FATAN2}):
13546: @cindex @code{FATAN2}, both arguments are equal to zero
13547: System-dependent. @code{FATAN2} is implemented using the C library
13548: function @code{atan2()}.
13549: 
13550: @item Using @code{FTAN} on an argument @i{r1} where cos(@i{r1}) is zero:
13551: @cindex @code{FTAN} on an argument @i{r1} where cos(@i{r1}) is zero
13552: System-dependent. Anyway, typically the cos of @i{r1} will not be zero
13553: because of small errors and the tan will be a very large (or very small)
13554: but finite number.
13555: 
13556: @item @i{d} cannot be presented precisely as a float in @code{D>F}:
13557: @cindex @code{D>F}, @i{d} cannot be presented precisely as a float
13558: The result is rounded to the nearest float.
13559: 
13560: @item dividing by zero:
13561: @cindex dividing by zero, floating-point
13562: @cindex floating-point dividing by zero
13563: @cindex floating-point unidentified fault, FP divide-by-zero
13564: Platform-dependent; can produce an Infinity, NaN, @code{-42 throw}
13565: (floating point divide by zero) or @code{-55 throw} (Floating-point
13566: unidentified fault).
13567: 
13568: @item exponent too big for conversion (@code{DF!}, @code{DF@@}, @code{SF!}, @code{SF@@}):
13569: @cindex exponent too big for conversion (@code{DF!}, @code{DF@@}, @code{SF!}, @code{SF@@})
13570: System dependent. On IEEE-FP based systems the number is converted into
13571: an infinity.
13572: 
13573: @item @i{float}<1 (@code{FACOSH}):
13574: @cindex @code{FACOSH}, @i{float}<1
13575: @cindex floating-point unidentified fault, @code{FACOSH}
13576: Platform-dependent; on IEEE-FP systems typically produces a NaN.
13577: 
13578: @item @i{float}=<-1 (@code{FLNP1}):
13579: @cindex @code{FLNP1}, @i{float}=<-1
13580: @cindex floating-point unidentified fault, @code{FLNP1}
13581: Platform-dependent; on IEEE-FP systems typically produces a NaN (or a
13582: negative infinity for @i{float}=-1).
13583: 
13584: @item @i{float}=<0 (@code{FLN}, @code{FLOG}):
13585: @cindex @code{FLN}, @i{float}=<0
13586: @cindex @code{FLOG}, @i{float}=<0
13587: @cindex floating-point unidentified fault, @code{FLN} or @code{FLOG}
13588: Platform-dependent; on IEEE-FP systems typically produces a NaN (or a
13589: negative infinity for @i{float}=0).
13590: 
13591: @item @i{float}<0 (@code{FASINH}, @code{FSQRT}):
13592: @cindex @code{FASINH}, @i{float}<0
13593: @cindex @code{FSQRT}, @i{float}<0
13594: @cindex floating-point unidentified fault, @code{FASINH} or @code{FSQRT}
13595: Platform-dependent; for @code{fsqrt} this typically gives a NaN, for
13596: @code{fasinh} some platforms produce a NaN, others a number (bug in the
13597: C library?).
13598: 
13599: @item |@i{float}|>1 (@code{FACOS}, @code{FASIN}, @code{FATANH}):
13600: @cindex @code{FACOS}, |@i{float}|>1
13601: @cindex @code{FASIN}, |@i{float}|>1
13602: @cindex @code{FATANH}, |@i{float}|>1
13603: @cindex floating-point unidentified fault, @code{FACOS}, @code{FASIN} or @code{FATANH}
13604: Platform-dependent; IEEE-FP systems typically produce a NaN.
13605: 
13606: @item integer part of float cannot be represented by @i{d} in @code{F>D}:
13607: @cindex @code{F>D}, integer part of float cannot be represented by @i{d}
13608: @cindex floating-point unidentified fault, @code{F>D}
13609: Platform-dependent; typically, some double number is produced and no
13610: error is reported.
13611: 
13612: @item string larger than pictured numeric output area (@code{f.}, @code{fe.}, @code{fs.}):
13613: @cindex string larger than pictured numeric output area (@code{f.}, @code{fe.}, @code{fs.})
13614: @code{Precision} characters of the numeric output area are used.  If
13615: @code{precision} is too high, these words will smash the data or code
13616: close to @code{here}.
13617: @end table
13618: 
13619: @c =====================================================================
13620: @node  The optional Locals word set, The optional Memory-Allocation word set, The optional Floating-Point word set, ANS conformance
13621: @section The optional Locals word set
13622: @c =====================================================================
13623: @cindex system documentation, locals words
13624: @cindex locals words, system documentation
13625: 
13626: @menu
13627: * locals-idef::                 Implementation Defined Options                 
13628: * locals-ambcond::              Ambiguous Conditions              
13629: @end menu
13630: 
13631: 
13632: @c ---------------------------------------------------------------------
13633: @node locals-idef, locals-ambcond, The optional Locals word set, The optional Locals word set
13634: @subsection Implementation Defined Options
13635: @c ---------------------------------------------------------------------
13636: @cindex implementation-defined options, locals words
13637: @cindex locals words, implementation-defined options
13638: 
13639: @table @i
13640: @item maximum number of locals in a definition:
13641: @cindex maximum number of locals in a definition
13642: @cindex locals, maximum number in a definition
13643: @code{s" #locals" environment? drop .}. Currently 15. This is a lower
13644: bound, e.g., on a 32-bit machine there can be 41 locals of up to 8
13645: characters. The number of locals in a definition is bounded by the size
13646: of locals-buffer, which contains the names of the locals.
13647: 
13648: @end table
13649: 
13650: 
13651: @c ---------------------------------------------------------------------
13652: @node locals-ambcond,  , locals-idef, The optional Locals word set
13653: @subsection Ambiguous conditions
13654: @c ---------------------------------------------------------------------
13655: @cindex locals words, ambiguous conditions
13656: @cindex ambiguous conditions, locals words
13657: 
13658: @table @i
13659: @item executing a named local in interpretation state:
13660: @cindex local in interpretation state
13661: @cindex Interpreting a compile-only word, for a local
13662: Locals have no interpretation semantics. If you try to perform the
13663: interpretation semantics, you will get a @code{-14 throw} somewhere
13664: (Interpreting a compile-only word). If you perform the compilation
13665: semantics, the locals access will be compiled (irrespective of state).
13666: 
13667: @item @i{name} not defined by @code{VALUE} or @code{(LOCAL)} (@code{TO}):
13668: @cindex name not defined by @code{VALUE} or @code{(LOCAL)} used by @code{TO}
13669: @cindex @code{TO} on non-@code{VALUE}s and non-locals
13670: @cindex Invalid name argument, @code{TO}
13671: @code{-32 throw} (Invalid name argument)
13672: 
13673: @end table
13674: 
13675: 
13676: @c =====================================================================
13677: @node  The optional Memory-Allocation word set, The optional Programming-Tools word set, The optional Locals word set, ANS conformance
13678: @section The optional Memory-Allocation word set
13679: @c =====================================================================
13680: @cindex system documentation, memory-allocation words
13681: @cindex memory-allocation words, system documentation
13682: 
13683: @menu
13684: * memory-idef::                 Implementation Defined Options                 
13685: @end menu
13686: 
13687: 
13688: @c ---------------------------------------------------------------------
13689: @node memory-idef,  , The optional Memory-Allocation word set, The optional Memory-Allocation word set
13690: @subsection Implementation Defined Options
13691: @c ---------------------------------------------------------------------
13692: @cindex implementation-defined options, memory-allocation words
13693: @cindex memory-allocation words, implementation-defined options
13694: 
13695: @table @i
13696: @item values and meaning of @i{ior}:
13697: @cindex  @i{ior} values and meaning
13698: The @i{ior}s returned by the file and memory allocation words are
13699: intended as throw codes. They typically are in the range
13700: -512@minus{}-2047 of OS errors.  The mapping from OS error numbers to
13701: @i{ior}s is -512@minus{}@i{errno}.
13702: 
13703: @end table
13704: 
13705: @c =====================================================================
13706: @node  The optional Programming-Tools word set, The optional Search-Order word set, The optional Memory-Allocation word set, ANS conformance
13707: @section The optional Programming-Tools word set
13708: @c =====================================================================
13709: @cindex system documentation, programming-tools words
13710: @cindex programming-tools words, system documentation
13711: 
13712: @menu
13713: * programming-idef::            Implementation Defined Options            
13714: * programming-ambcond::         Ambiguous Conditions         
13715: @end menu
13716: 
13717: 
13718: @c ---------------------------------------------------------------------
13719: @node programming-idef, programming-ambcond, The optional Programming-Tools word set, The optional Programming-Tools word set
13720: @subsection Implementation Defined Options
13721: @c ---------------------------------------------------------------------
13722: @cindex implementation-defined options, programming-tools words
13723: @cindex programming-tools words, implementation-defined options
13724: 
13725: @table @i
13726: @item ending sequence for input following @code{;CODE} and @code{CODE}:
13727: @cindex @code{;CODE} ending sequence
13728: @cindex @code{CODE} ending sequence
13729: @code{END-CODE}
13730: 
13731: @item manner of processing input following @code{;CODE} and @code{CODE}:
13732: @cindex @code{;CODE}, processing input
13733: @cindex @code{CODE}, processing input
13734: The @code{ASSEMBLER} vocabulary is pushed on the search order stack, and
13735: the input is processed by the text interpreter, (starting) in interpret
13736: state.
13737: 
13738: @item search order capability for @code{EDITOR} and @code{ASSEMBLER}:
13739: @cindex @code{ASSEMBLER}, search order capability
13740: The ANS Forth search order word set.
13741: 
13742: @item source and format of display by @code{SEE}:
13743: @cindex @code{SEE}, source and format of output
13744: The source for @code{see} is the executable code used by the inner
13745: interpreter.  The current @code{see} tries to output Forth source code
13746: (and on some platforms, assembly code for primitives) as well as
13747: possible.
13748: 
13749: @end table
13750: 
13751: @c ---------------------------------------------------------------------
13752: @node programming-ambcond,  , programming-idef, The optional Programming-Tools word set
13753: @subsection Ambiguous conditions
13754: @c ---------------------------------------------------------------------
13755: @cindex programming-tools words, ambiguous conditions
13756: @cindex ambiguous conditions, programming-tools words
13757: 
13758: @table @i
13759: 
13760: @item deleting the compilation word list (@code{FORGET}):
13761: @cindex @code{FORGET}, deleting the compilation word list
13762: Not implemented (yet).
13763: 
13764: @item fewer than @i{u}+1 items on the control-flow stack (@code{CS-PICK}, @code{CS-ROLL}):
13765: @cindex @code{CS-PICK}, fewer than @i{u}+1 items on the control flow-stack
13766: @cindex @code{CS-ROLL}, fewer than @i{u}+1 items on the control flow-stack
13767: @cindex control-flow stack underflow
13768: This typically results in an @code{abort"} with a descriptive error
13769: message (may change into a @code{-22 throw} (Control structure mismatch)
13770: in the future). You may also get a memory access error. If you are
13771: unlucky, this ambiguous condition is not caught.
13772: 
13773: @item @i{name} can't be found (@code{FORGET}):
13774: @cindex @code{FORGET}, @i{name} can't be found
13775: Not implemented (yet).
13776: 
13777: @item @i{name} not defined via @code{CREATE}:
13778: @cindex @code{;CODE}, @i{name} not defined via @code{CREATE}
13779: @code{;CODE} behaves like @code{DOES>} in this respect, i.e., it changes
13780: the execution semantics of the last defined word no matter how it was
13781: defined.
13782: 
13783: @item @code{POSTPONE} applied to @code{[IF]}:
13784: @cindex @code{POSTPONE} applied to @code{[IF]}
13785: @cindex @code{[IF]} and @code{POSTPONE}
13786: After defining @code{: X POSTPONE [IF] ; IMMEDIATE}. @code{X} is
13787: equivalent to @code{[IF]}.
13788: 
13789: @item reaching the end of the input source before matching @code{[ELSE]} or @code{[THEN]}:
13790: @cindex @code{[IF]}, end of the input source before matching @code{[ELSE]} or @code{[THEN]}
13791: Continue in the same state of conditional compilation in the next outer
13792: input source. Currently there is no warning to the user about this.
13793: 
13794: @item removing a needed definition (@code{FORGET}):
13795: @cindex @code{FORGET}, removing a needed definition
13796: Not implemented (yet).
13797: 
13798: @end table
13799: 
13800: 
13801: @c =====================================================================
13802: @node  The optional Search-Order word set,  , The optional Programming-Tools word set, ANS conformance
13803: @section The optional Search-Order word set
13804: @c =====================================================================
13805: @cindex system documentation, search-order words
13806: @cindex search-order words, system documentation
13807: 
13808: @menu
13809: * search-idef::                 Implementation Defined Options                 
13810: * search-ambcond::              Ambiguous Conditions              
13811: @end menu
13812: 
13813: 
13814: @c ---------------------------------------------------------------------
13815: @node search-idef, search-ambcond, The optional Search-Order word set, The optional Search-Order word set
13816: @subsection Implementation Defined Options
13817: @c ---------------------------------------------------------------------
13818: @cindex implementation-defined options, search-order words
13819: @cindex search-order words, implementation-defined options
13820: 
13821: @table @i
13822: @item maximum number of word lists in search order:
13823: @cindex maximum number of word lists in search order
13824: @cindex search order, maximum depth
13825: @code{s" wordlists" environment? drop .}. Currently 16.
13826: 
13827: @item minimum search order:
13828: @cindex minimum search order
13829: @cindex search order, minimum
13830: @code{root root}.
13831: 
13832: @end table
13833: 
13834: @c ---------------------------------------------------------------------
13835: @node search-ambcond,  , search-idef, The optional Search-Order word set
13836: @subsection Ambiguous conditions
13837: @c ---------------------------------------------------------------------
13838: @cindex search-order words, ambiguous conditions
13839: @cindex ambiguous conditions, search-order words
13840: 
13841: @table @i
13842: @item changing the compilation word list (during compilation):
13843: @cindex changing the compilation word list (during compilation)
13844: @cindex compilation word list, change before definition ends
13845: The word is entered into the word list that was the compilation word list
13846: at the start of the definition. Any changes to the name field (e.g.,
13847: @code{immediate}) or the code field (e.g., when executing @code{DOES>})
13848: are applied to the latest defined word (as reported by @code{latest} or
13849: @code{latestxt}), if possible, irrespective of the compilation word list.
13850: 
13851: @item search order empty (@code{previous}):
13852: @cindex @code{previous}, search order empty
13853: @cindex vocstack empty, @code{previous}
13854: @code{abort" Vocstack empty"}.
13855: 
13856: @item too many word lists in search order (@code{also}):
13857: @cindex @code{also}, too many word lists in search order
13858: @cindex vocstack full, @code{also}
13859: @code{abort" Vocstack full"}.
13860: 
13861: @end table
13862: 
13863: @c ***************************************************************
13864: @node Standard vs Extensions, Model, ANS conformance, Top
13865: @chapter Should I use Gforth extensions?
13866: @cindex Gforth extensions
13867: 
13868: As you read through the rest of this manual, you will see documentation
13869: for @i{Standard} words, and documentation for some appealing Gforth
13870: @i{extensions}. You might ask yourself the question: @i{``Should I
13871: restrict myself to the standard, or should I use the extensions?''}
13872: 
13873: The answer depends on the goals you have for the program you are working
13874: on:
13875: 
13876: @itemize @bullet
13877: 
13878: @item Is it just for yourself or do you want to share it with others?
13879: 
13880: @item
13881: If you want to share it, do the others all use Gforth?
13882: 
13883: @item
13884: If it is just for yourself, do you want to restrict yourself to Gforth?
13885: 
13886: @end itemize
13887: 
13888: If restricting the program to Gforth is ok, then there is no reason not
13889: to use extensions.  It is still a good idea to keep to the standard
13890: where it is easy, in case you want to reuse these parts in another
13891: program that you want to be portable.
13892: 
13893: If you want to be able to port the program to other Forth systems, there
13894: are the following points to consider:
13895: 
13896: @itemize @bullet
13897: 
13898: @item
13899: Most Forth systems that are being maintained support the ANS Forth
13900: standard.  So if your program complies with the standard, it will be
13901: portable among many systems.
13902: 
13903: @item
13904: A number of the Gforth extensions can be implemented in ANS Forth using
13905: public-domain files provided in the @file{compat/} directory. These are
13906: mentioned in the text in passing.  There is no reason not to use these
13907: extensions, your program will still be ANS Forth compliant; just include
13908: the appropriate compat files with your program.
13909: 
13910: @item
13911: The tool @file{ans-report.fs} (@pxref{ANS Report}) makes it easy to
13912: analyse your program and determine what non-Standard words it relies
13913: upon.  However, it does not check whether you use standard words in a
13914: non-standard way.
13915: 
13916: @item
13917: Some techniques are not standardized by ANS Forth, and are hard or
13918: impossible to implement in a standard way, but can be implemented in
13919: most Forth systems easily, and usually in similar ways (e.g., accessing
13920: word headers).  Forth has a rich historical precedent for programmers
13921: taking advantage of implementation-dependent features of their tools
13922: (for example, relying on a knowledge of the dictionary
13923: structure). Sometimes these techniques are necessary to extract every
13924: last bit of performance from the hardware, sometimes they are just a
13925: programming shorthand.
13926: 
13927: @item
13928: Does using a Gforth extension save more work than the porting this part
13929: to other Forth systems (if any) will cost?
13930: 
13931: @item
13932: Is the additional functionality worth the reduction in portability and
13933: the additional porting problems?
13934: 
13935: @end itemize
13936: 
13937: In order to perform these consideratios, you need to know what's
13938: standard and what's not.  This manual generally states if something is
13939: non-standard, but the authoritative source is the
13940: @uref{http://www.taygeta.com/forth/dpans.html,standard document}.
13941: Appendix A of the Standard (@var{Rationale}) provides a valuable insight
13942: into the thought processes of the technical committee.
13943: 
13944: Note also that portability between Forth systems is not the only
13945: portability issue; there is also the issue of portability between
13946: different platforms (processor/OS combinations).
13947: 
13948: @c ***************************************************************
13949: @node Model, Integrating Gforth, Standard vs Extensions, Top
13950: @chapter Model
13951: 
13952: This chapter has yet to be written. It will contain information, on
13953: which internal structures you can rely.
13954: 
13955: @c ***************************************************************
13956: @node Integrating Gforth, Emacs and Gforth, Model, Top
13957: @chapter Integrating Gforth into C programs
13958: 
13959: This is not yet implemented.
13960: 
13961: Several people like to use Forth as scripting language for applications
13962: that are otherwise written in C, C++, or some other language.
13963: 
13964: The Forth system ATLAST provides facilities for embedding it into
13965: applications; unfortunately it has several disadvantages: most
13966: importantly, it is not based on ANS Forth, and it is apparently dead
13967: (i.e., not developed further and not supported). The facilities
13968: provided by Gforth in this area are inspired by ATLAST's facilities, so
13969: making the switch should not be hard.
13970: 
13971: We also tried to design the interface such that it can easily be
13972: implemented by other Forth systems, so that we may one day arrive at a
13973: standardized interface. Such a standard interface would allow you to
13974: replace the Forth system without having to rewrite C code.
13975: 
13976: You embed the Gforth interpreter by linking with the library
13977: @code{libgforth.a} (give the compiler the option @code{-lgforth}).  All
13978: global symbols in this library that belong to the interface, have the
13979: prefix @code{forth_}. (Global symbols that are used internally have the
13980: prefix @code{gforth_}).
13981: 
13982: You can include the declarations of Forth types and the functions and
13983: variables of the interface with @code{#include <forth.h>}.
13984: 
13985: Types.
13986: 
13987: Variables.
13988: 
13989: Data and FP Stack pointer. Area sizes.
13990: 
13991: functions.
13992: 
13993: forth_init(imagefile)
13994: forth_evaluate(string) exceptions?
13995: forth_goto(address) (or forth_execute(xt)?)
13996: forth_continue() (a corountining mechanism)
13997: 
13998: Adding primitives.
13999: 
14000: No checking.
14001: 
14002: Signals?
14003: 
14004: Accessing the Stacks
14005: 
14006: @c ******************************************************************
14007: @node Emacs and Gforth, Image Files, Integrating Gforth, Top
14008: @chapter Emacs and Gforth
14009: @cindex Emacs and Gforth
14010: 
14011: @cindex @file{gforth.el}
14012: @cindex @file{forth.el}
14013: @cindex Rydqvist, Goran
14014: @cindex Kuehling, David
14015: @cindex comment editing commands
14016: @cindex @code{\}, editing with Emacs
14017: @cindex debug tracer editing commands
14018: @cindex @code{~~}, removal with Emacs
14019: @cindex Forth mode in Emacs
14020: 
14021: Gforth comes with @file{gforth.el}, an improved version of
14022: @file{forth.el} by Goran Rydqvist (included in the TILE package). The
14023: improvements are:
14024: 
14025: @itemize @bullet
14026: @item
14027: A better handling of indentation.
14028: @item
14029: A custom hilighting engine for Forth-code.
14030: @item
14031: Comment paragraph filling (@kbd{M-q})
14032: @item
14033: Commenting (@kbd{C-x \}) and uncommenting (@kbd{C-u C-x \}) of regions
14034: @item
14035: Removal of debugging tracers (@kbd{C-x ~}, @pxref{Debugging}).
14036: @item
14037: Support of the @code{info-lookup} feature for looking up the
14038: documentation of a word.
14039: @item
14040: Support for reading and writing blocks files.
14041: @end itemize
14042: 
14043: To get a basic description of these features, enter Forth mode and
14044: type @kbd{C-h m}.
14045: 
14046: @cindex source location of error or debugging output in Emacs
14047: @cindex error output, finding the source location in Emacs
14048: @cindex debugging output, finding the source location in Emacs
14049: In addition, Gforth supports Emacs quite well: The source code locations
14050: given in error messages, debugging output (from @code{~~}) and failed
14051: assertion messages are in the right format for Emacs' compilation mode
14052: (@pxref{Compilation, , Running Compilations under Emacs, emacs, Emacs
14053: Manual}) so the source location corresponding to an error or other
14054: message is only a few keystrokes away (@kbd{C-x `} for the next error,
14055: @kbd{C-c C-c} for the error under the cursor).
14056: 
14057: @cindex viewing the documentation of a word in Emacs
14058: @cindex context-sensitive help
14059: Moreover, for words documented in this manual, you can look up the
14060: glossary entry quickly by using @kbd{C-h TAB}
14061: (@code{info-lookup-symbol}, @pxref{Documentation, ,Documentation
14062: Commands, emacs, Emacs Manual}).  This feature requires Emacs 20.3 or
14063: later and does not work for words containing @code{:}.
14064: 
14065: @menu
14066: * Installing gforth.el::        Making Emacs aware of Forth.
14067: * Emacs Tags::                  Viewing the source of a word in Emacs.
14068: * Hilighting::                  Making Forth code look prettier.
14069: * Auto-Indentation::            Customizing auto-indentation.
14070: * Blocks Files::                Reading and writing blocks files.
14071: @end menu
14072: 
14073: @c ----------------------------------
14074: @node Installing gforth.el, Emacs Tags, Emacs and Gforth, Emacs and Gforth
14075: @section Installing gforth.el
14076: @cindex @file{.emacs}
14077: @cindex @file{gforth.el}, installation
14078: To make the features from @file{gforth.el} available in Emacs, add
14079: the following lines to your @file{.emacs} file:
14080: 
14081: @example
14082: (autoload 'forth-mode "gforth.el")
14083: (setq auto-mode-alist (cons '("\\.fs\\'" . forth-mode) 
14084: 			    auto-mode-alist))
14085: (autoload 'forth-block-mode "gforth.el")
14086: (setq auto-mode-alist (cons '("\\.fb\\'" . forth-block-mode) 
14087: 			    auto-mode-alist))
14088: (add-hook 'forth-mode-hook (function (lambda ()
14089:    ;; customize variables here:
14090:    (setq forth-indent-level 4)
14091:    (setq forth-minor-indent-level 2)
14092:    (setq forth-hilight-level 3)
14093:    ;;; ...
14094: )))
14095: @end example
14096: 
14097: @c ----------------------------------
14098: @node Emacs Tags, Hilighting, Installing gforth.el, Emacs and Gforth
14099: @section Emacs Tags
14100: @cindex @file{TAGS} file
14101: @cindex @file{etags.fs}
14102: @cindex viewing the source of a word in Emacs
14103: @cindex @code{require}, placement in files
14104: @cindex @code{include}, placement in files
14105: If you @code{require} @file{etags.fs}, a new @file{TAGS} file will be
14106: produced (@pxref{Tags, , Tags Tables, emacs, Emacs Manual}) that
14107: contains the definitions of all words defined afterwards. You can then
14108: find the source for a word using @kbd{M-.}. Note that Emacs can use
14109: several tags files at the same time (e.g., one for the Gforth sources
14110: and one for your program, @pxref{Select Tags Table,,Selecting a Tags
14111: Table,emacs, Emacs Manual}). The TAGS file for the preloaded words is
14112: @file{$(datadir)/gforth/$(VERSION)/TAGS} (e.g.,
14113: @file{/usr/local/share/gforth/0.2.0/TAGS}).  To get the best behaviour
14114: with @file{etags.fs}, you should avoid putting definitions both before
14115: and after @code{require} etc., otherwise you will see the same file
14116: visited several times by commands like @code{tags-search}.
14117: 
14118: @c ----------------------------------
14119: @node Hilighting, Auto-Indentation, Emacs Tags, Emacs and Gforth
14120: @section Hilighting
14121: @cindex hilighting Forth code in Emacs
14122: @cindex highlighting Forth code in Emacs
14123: @file{gforth.el} comes with a custom source hilighting engine.  When
14124: you open a file in @code{forth-mode}, it will be completely parsed,
14125: assigning faces to keywords, comments, strings etc.  While you edit
14126: the file, modified regions get parsed and updated on-the-fly. 
14127: 
14128: Use the variable `forth-hilight-level' to change the level of
14129: decoration from 0 (no hilighting at all) to 3 (the default).  Even if
14130: you set the hilighting level to 0, the parser will still work in the
14131: background, collecting information about whether regions of text are
14132: ``compiled'' or ``interpreted''.  Those information are required for
14133: auto-indentation to work properly.  Set `forth-disable-parser' to
14134: non-nil if your computer is too slow to handle parsing.  This will
14135: have an impact on the smartness of the auto-indentation engine,
14136: though.
14137: 
14138: Sometimes Forth sources define new features that should be hilighted,
14139: new control structures, defining-words etc.  You can use the variable
14140: `forth-custom-words' to make @code{forth-mode} hilight additional
14141: words and constructs.  See the docstring of `forth-words' for details
14142: (in Emacs, type @kbd{C-h v forth-words}).
14143: 
14144: `forth-custom-words' is meant to be customized in your
14145: @file{.emacs} file.  To customize hilighing in a file-specific manner,
14146: set `forth-local-words' in a local-variables section at the end of
14147: your source file (@pxref{Local Variables in Files,, Variables, emacs, Emacs Manual}).
14148: 
14149: Example:
14150: @example
14151: 0 [IF]
14152:    Local Variables:
14153:    forth-local-words:
14154:       ((("t:") definition-starter (font-lock-keyword-face . 1)
14155:         "[ \t\n]" t name (font-lock-function-name-face . 3))
14156:        ((";t") definition-ender (font-lock-keyword-face . 1)))
14157:    End:
14158: [THEN]
14159: @end example
14160: 
14161: @c ----------------------------------
14162: @node Auto-Indentation, Blocks Files, Hilighting, Emacs and Gforth
14163: @section Auto-Indentation
14164: @cindex auto-indentation of Forth code in Emacs
14165: @cindex indentation of Forth code in Emacs
14166: @code{forth-mode} automatically tries to indent lines in a smart way,
14167: whenever you type @key{TAB} or break a line with @kbd{C-m}.
14168: 
14169: Simple customization can be achieved by setting
14170: `forth-indent-level' and `forth-minor-indent-level' in your
14171: @file{.emacs} file. For historical reasons @file{gforth.el} indents
14172: per default by multiples of 4 columns.  To use the more traditional
14173: 3-column indentation, add the following lines to your @file{.emacs}:
14174: 
14175: @example
14176: (add-hook 'forth-mode-hook (function (lambda ()
14177:    ;; customize variables here:
14178:    (setq forth-indent-level 3)
14179:    (setq forth-minor-indent-level 1)
14180: )))
14181: @end example
14182: 
14183: If you want indentation to recognize non-default words, customize it
14184: by setting `forth-custom-indent-words' in your @file{.emacs}.  See the
14185: docstring of `forth-indent-words' for details (in Emacs, type @kbd{C-h
14186: v forth-indent-words}).
14187: 
14188: To customize indentation in a file-specific manner, set
14189: `forth-local-indent-words' in a local-variables section at the end of
14190: your source file (@pxref{Local Variables in Files, Variables,,emacs,
14191: Emacs Manual}).
14192: 
14193: Example:
14194: @example
14195: 0 [IF]
14196:    Local Variables:
14197:    forth-local-indent-words:
14198:       ((("t:") (0 . 2) (0 . 2))
14199:        ((";t") (-2 . 0) (0 . -2)))
14200:    End:
14201: [THEN]
14202: @end example
14203: 
14204: @c ----------------------------------
14205: @node Blocks Files,  , Auto-Indentation, Emacs and Gforth
14206: @section Blocks Files
14207: @cindex blocks files, use with Emacs
14208: @code{forth-mode} Autodetects blocks files by checking whether the
14209: length of the first line exceeds 1023 characters.  It then tries to
14210: convert the file into normal text format.  When you save the file, it
14211: will be written to disk as normal stream-source file.
14212: 
14213: If you want to write blocks files, use @code{forth-blocks-mode}.  It
14214: inherits all the features from @code{forth-mode}, plus some additions:
14215: 
14216: @itemize @bullet
14217: @item
14218: Files are written to disk in blocks file format.
14219: @item
14220: Screen numbers are displayed in the mode line (enumerated beginning
14221: with the value of `forth-block-base')
14222: @item
14223: Warnings are displayed when lines exceed 64 characters.
14224: @item
14225: The beginning of the currently edited block is marked with an
14226: overlay-arrow. 
14227: @end itemize
14228: 
14229: There are some restrictions you should be aware of.  When you open a
14230: blocks file that contains tabulator or newline characters, these
14231: characters will be translated into spaces when the file is written
14232: back to disk.  If tabs or newlines are encountered during blocks file
14233: reading, an error is output to the echo area. So have a look at the
14234: `*Messages*' buffer, when Emacs' bell rings during reading.
14235: 
14236: Please consult the docstring of @code{forth-blocks-mode} for more
14237: information by typing @kbd{C-h v forth-blocks-mode}).
14238: 
14239: @c ******************************************************************
14240: @node Image Files, Engine, Emacs and Gforth, Top
14241: @chapter Image Files
14242: @cindex image file
14243: @cindex @file{.fi} files
14244: @cindex precompiled Forth code
14245: @cindex dictionary in persistent form
14246: @cindex persistent form of dictionary
14247: 
14248: An image file is a file containing an image of the Forth dictionary,
14249: i.e., compiled Forth code and data residing in the dictionary.  By
14250: convention, we use the extension @code{.fi} for image files.
14251: 
14252: @menu
14253: * Image Licensing Issues::      Distribution terms for images.
14254: * Image File Background::       Why have image files?
14255: * Non-Relocatable Image Files::  don't always work.
14256: * Data-Relocatable Image Files::  are better.
14257: * Fully Relocatable Image Files::  better yet.
14258: * Stack and Dictionary Sizes::  Setting the default sizes for an image.
14259: * Running Image Files::         @code{gforth -i @i{file}} or @i{file}.
14260: * Modifying the Startup Sequence::  and turnkey applications.
14261: @end menu
14262: 
14263: @node Image Licensing Issues, Image File Background, Image Files, Image Files
14264: @section Image Licensing Issues
14265: @cindex license for images
14266: @cindex image license
14267: 
14268: An image created with @code{gforthmi} (@pxref{gforthmi}) or
14269: @code{savesystem} (@pxref{Non-Relocatable Image Files}) includes the
14270: original image; i.e., according to copyright law it is a derived work of
14271: the original image.
14272: 
14273: Since Gforth is distributed under the GNU GPL, the newly created image
14274: falls under the GNU GPL, too. In particular, this means that if you
14275: distribute the image, you have to make all of the sources for the image
14276: available, including those you wrote.  For details see @ref{Copying, ,
14277: GNU General Public License (Section 3)}.
14278: 
14279: If you create an image with @code{cross} (@pxref{cross.fs}), the image
14280: contains only code compiled from the sources you gave it; if none of
14281: these sources is under the GPL, the terms discussed above do not apply
14282: to the image. However, if your image needs an engine (a gforth binary)
14283: that is under the GPL, you should make sure that you distribute both in
14284: a way that is at most a @emph{mere aggregation}, if you don't want the
14285: terms of the GPL to apply to the image.
14286: 
14287: @node Image File Background, Non-Relocatable Image Files, Image Licensing Issues, Image Files
14288: @section Image File Background
14289: @cindex image file background
14290: 
14291: Gforth consists not only of primitives (in the engine), but also of
14292: definitions written in Forth. Since the Forth compiler itself belongs to
14293: those definitions, it is not possible to start the system with the
14294: engine and the Forth source alone. Therefore we provide the Forth
14295: code as an image file in nearly executable form. When Gforth starts up,
14296: a C routine loads the image file into memory, optionally relocates the
14297: addresses, then sets up the memory (stacks etc.) according to
14298: information in the image file, and (finally) starts executing Forth
14299: code.
14300: 
14301: The image file variants represent different compromises between the
14302: goals of making it easy to generate image files and making them
14303: portable.
14304: 
14305: @cindex relocation at run-time
14306: Win32Forth 3.4 and Mitch Bradley's @code{cforth} use relocation at
14307: run-time. This avoids many of the complications discussed below (image
14308: files are data relocatable without further ado), but costs performance
14309: (one addition per memory access).
14310: 
14311: @cindex relocation at load-time
14312: By contrast, the Gforth loader performs relocation at image load time. The
14313: loader also has to replace tokens that represent primitive calls with the
14314: appropriate code-field addresses (or code addresses in the case of
14315: direct threading).
14316: 
14317: There are three kinds of image files, with different degrees of
14318: relocatability: non-relocatable, data-relocatable, and fully relocatable
14319: image files.
14320: 
14321: @cindex image file loader
14322: @cindex relocating loader
14323: @cindex loader for image files
14324: These image file variants have several restrictions in common; they are
14325: caused by the design of the image file loader:
14326: 
14327: @itemize @bullet
14328: @item
14329: There is only one segment; in particular, this means, that an image file
14330: cannot represent @code{ALLOCATE}d memory chunks (and pointers to
14331: them). The contents of the stacks are not represented, either.
14332: 
14333: @item
14334: The only kinds of relocation supported are: adding the same offset to
14335: all cells that represent data addresses; and replacing special tokens
14336: with code addresses or with pieces of machine code.
14337: 
14338: If any complex computations involving addresses are performed, the
14339: results cannot be represented in the image file. Several applications that
14340: use such computations come to mind:
14341: @itemize @minus
14342: @item
14343: Hashing addresses (or data structures which contain addresses) for table
14344: lookup. If you use Gforth's @code{table}s or @code{wordlist}s for this
14345: purpose, you will have no problem, because the hash tables are
14346: recomputed automatically when the system is started. If you use your own
14347: hash tables, you will have to do something similar.
14348: 
14349: @item
14350: There's a cute implementation of doubly-linked lists that uses
14351: @code{XOR}ed addresses. You could represent such lists as singly-linked
14352: in the image file, and restore the doubly-linked representation on
14353: startup.@footnote{In my opinion, though, you should think thrice before
14354: using a doubly-linked list (whatever implementation).}
14355: 
14356: @item
14357: The code addresses of run-time routines like @code{docol:} cannot be
14358: represented in the image file (because their tokens would be replaced by
14359: machine code in direct threaded implementations). As a workaround,
14360: compute these addresses at run-time with @code{>code-address} from the
14361: executions tokens of appropriate words (see the definitions of
14362: @code{docol:} and friends in @file{kernel/getdoers.fs}).
14363: 
14364: @item
14365: On many architectures addresses are represented in machine code in some
14366: shifted or mangled form. You cannot put @code{CODE} words that contain
14367: absolute addresses in this form in a relocatable image file. Workarounds
14368: are representing the address in some relative form (e.g., relative to
14369: the CFA, which is present in some register), or loading the address from
14370: a place where it is stored in a non-mangled form.
14371: @end itemize
14372: @end itemize
14373: 
14374: @node  Non-Relocatable Image Files, Data-Relocatable Image Files, Image File Background, Image Files
14375: @section Non-Relocatable Image Files
14376: @cindex non-relocatable image files
14377: @cindex image file, non-relocatable
14378: 
14379: These files are simple memory dumps of the dictionary. They are specific
14380: to the executable (i.e., @file{gforth} file) they were created
14381: with. What's worse, they are specific to the place on which the
14382: dictionary resided when the image was created. Now, there is no
14383: guarantee that the dictionary will reside at the same place the next
14384: time you start Gforth, so there's no guarantee that a non-relocatable
14385: image will work the next time (Gforth will complain instead of crashing,
14386: though).
14387: 
14388: You can create a non-relocatable image file with
14389: 
14390: 
14391: doc-savesystem
14392: 
14393: 
14394: @node Data-Relocatable Image Files, Fully Relocatable Image Files, Non-Relocatable Image Files, Image Files
14395: @section Data-Relocatable Image Files
14396: @cindex data-relocatable image files
14397: @cindex image file, data-relocatable
14398: 
14399: These files contain relocatable data addresses, but fixed code addresses
14400: (instead of tokens). They are specific to the executable (i.e.,
14401: @file{gforth} file) they were created with. For direct threading on some
14402: architectures (e.g., the i386), data-relocatable images do not work. You
14403: get a data-relocatable image, if you use @file{gforthmi} with a
14404: Gforth binary that is not doubly indirect threaded (@pxref{Fully
14405: Relocatable Image Files}).
14406: 
14407: @node Fully Relocatable Image Files, Stack and Dictionary Sizes, Data-Relocatable Image Files, Image Files
14408: @section Fully Relocatable Image Files
14409: @cindex fully relocatable image files
14410: @cindex image file, fully relocatable
14411: 
14412: @cindex @file{kern*.fi}, relocatability
14413: @cindex @file{gforth.fi}, relocatability
14414: These image files have relocatable data addresses, and tokens for code
14415: addresses. They can be used with different binaries (e.g., with and
14416: without debugging) on the same machine, and even across machines with
14417: the same data formats (byte order, cell size, floating point
14418: format). However, they are usually specific to the version of Gforth
14419: they were created with. The files @file{gforth.fi} and @file{kernl*.fi}
14420: are fully relocatable.
14421: 
14422: There are two ways to create a fully relocatable image file:
14423: 
14424: @menu
14425: * gforthmi::                    The normal way
14426: * cross.fs::                    The hard way
14427: @end menu
14428: 
14429: @node gforthmi, cross.fs, Fully Relocatable Image Files, Fully Relocatable Image Files
14430: @subsection @file{gforthmi}
14431: @cindex @file{comp-i.fs}
14432: @cindex @file{gforthmi}
14433: 
14434: You will usually use @file{gforthmi}. If you want to create an
14435: image @i{file} that contains everything you would load by invoking
14436: Gforth with @code{gforth @i{options}}, you simply say:
14437: @example
14438: gforthmi @i{file} @i{options}
14439: @end example
14440: 
14441: E.g., if you want to create an image @file{asm.fi} that has the file
14442: @file{asm.fs} loaded in addition to the usual stuff, you could do it
14443: like this:
14444: 
14445: @example
14446: gforthmi asm.fi asm.fs
14447: @end example
14448: 
14449: @file{gforthmi} is implemented as a sh script and works like this: It
14450: produces two non-relocatable images for different addresses and then
14451: compares them. Its output reflects this: first you see the output (if
14452: any) of the two Gforth invocations that produce the non-relocatable image
14453: files, then you see the output of the comparing program: It displays the
14454: offset used for data addresses and the offset used for code addresses;
14455: moreover, for each cell that cannot be represented correctly in the
14456: image files, it displays a line like this:
14457: 
14458: @example
14459:      78DC         BFFFFA50         BFFFFA40
14460: @end example
14461: 
14462: This means that at offset $78dc from @code{forthstart}, one input image
14463: contains $bffffa50, and the other contains $bffffa40. Since these cells
14464: cannot be represented correctly in the output image, you should examine
14465: these places in the dictionary and verify that these cells are dead
14466: (i.e., not read before they are written).
14467: 
14468: @cindex --application, @code{gforthmi} option
14469: If you insert the option @code{--application} in front of the image file
14470: name, you will get an image that uses the @code{--appl-image} option
14471: instead of the @code{--image-file} option (@pxref{Invoking
14472: Gforth}). When you execute such an image on Unix (by typing the image
14473: name as command), the Gforth engine will pass all options to the image
14474: instead of trying to interpret them as engine options.
14475: 
14476: If you type @file{gforthmi} with no arguments, it prints some usage
14477: instructions.
14478: 
14479: @cindex @code{savesystem} during @file{gforthmi}
14480: @cindex @code{bye} during @file{gforthmi}
14481: @cindex doubly indirect threaded code
14482: @cindex environment variables
14483: @cindex @code{GFORTHD} -- environment variable
14484: @cindex @code{GFORTH} -- environment variable
14485: @cindex @code{gforth-ditc}
14486: There are a few wrinkles: After processing the passed @i{options}, the
14487: words @code{savesystem} and @code{bye} must be visible. A special doubly
14488: indirect threaded version of the @file{gforth} executable is used for
14489: creating the non-relocatable images; you can pass the exact filename of
14490: this executable through the environment variable @code{GFORTHD}
14491: (default: @file{gforth-ditc}); if you pass a version that is not doubly
14492: indirect threaded, you will not get a fully relocatable image, but a
14493: data-relocatable image (because there is no code address offset). The
14494: normal @file{gforth} executable is used for creating the relocatable
14495: image; you can pass the exact filename of this executable through the
14496: environment variable @code{GFORTH}.
14497: 
14498: @node cross.fs,  , gforthmi, Fully Relocatable Image Files
14499: @subsection @file{cross.fs}
14500: @cindex @file{cross.fs}
14501: @cindex cross-compiler
14502: @cindex metacompiler
14503: @cindex target compiler
14504: 
14505: You can also use @code{cross}, a batch compiler that accepts a Forth-like
14506: programming language (@pxref{Cross Compiler}).
14507: 
14508: @code{cross} allows you to create image files for machines with
14509: different data sizes and data formats than the one used for generating
14510: the image file. You can also use it to create an application image that
14511: does not contain a Forth compiler. These features are bought with
14512: restrictions and inconveniences in programming. E.g., addresses have to
14513: be stored in memory with special words (@code{A!}, @code{A,}, etc.) in
14514: order to make the code relocatable.
14515: 
14516: 
14517: @node Stack and Dictionary Sizes, Running Image Files, Fully Relocatable Image Files, Image Files
14518: @section Stack and Dictionary Sizes
14519: @cindex image file, stack and dictionary sizes
14520: @cindex dictionary size default
14521: @cindex stack size default
14522: 
14523: If you invoke Gforth with a command line flag for the size
14524: (@pxref{Invoking Gforth}), the size you specify is stored in the
14525: dictionary. If you save the dictionary with @code{savesystem} or create
14526: an image with @file{gforthmi}, this size will become the default
14527: for the resulting image file. E.g., the following will create a
14528: fully relocatable version of @file{gforth.fi} with a 1MB dictionary:
14529: 
14530: @example
14531: gforthmi gforth.fi -m 1M
14532: @end example
14533: 
14534: In other words, if you want to set the default size for the dictionary
14535: and the stacks of an image, just invoke @file{gforthmi} with the
14536: appropriate options when creating the image.
14537: 
14538: @cindex stack size, cache-friendly
14539: Note: For cache-friendly behaviour (i.e., good performance), you should
14540: make the sizes of the stacks modulo, say, 2K, somewhat different. E.g.,
14541: the default stack sizes are: data: 16k (mod 2k=0); fp: 15.5k (mod
14542: 2k=1.5k); return: 15k(mod 2k=1k); locals: 14.5k (mod 2k=0.5k).
14543: 
14544: @node Running Image Files, Modifying the Startup Sequence, Stack and Dictionary Sizes, Image Files
14545: @section Running Image Files
14546: @cindex running image files
14547: @cindex invoking image files
14548: @cindex image file invocation
14549: 
14550: @cindex -i, invoke image file
14551: @cindex --image file, invoke image file
14552: You can invoke Gforth with an image file @i{image} instead of the
14553: default @file{gforth.fi} with the @code{-i} flag (@pxref{Invoking Gforth}):
14554: @example
14555: gforth -i @i{image}
14556: @end example
14557: 
14558: @cindex executable image file
14559: @cindex image file, executable
14560: If your operating system supports starting scripts with a line of the
14561: form @code{#! ...}, you just have to type the image file name to start
14562: Gforth with this image file (note that the file extension @code{.fi} is
14563: just a convention). I.e., to run Gforth with the image file @i{image},
14564: you can just type @i{image} instead of @code{gforth -i @i{image}}.
14565: This works because every @code{.fi} file starts with a line of this
14566: format:
14567: 
14568: @example
14569: #! /usr/local/bin/gforth-0.4.0 -i
14570: @end example
14571: 
14572: The file and pathname for the Gforth engine specified on this line is
14573: the specific Gforth executable that it was built against; i.e. the value
14574: of the environment variable @code{GFORTH} at the time that
14575: @file{gforthmi} was executed.
14576: 
14577: You can make use of the same shell capability to make a Forth source
14578: file into an executable. For example, if you place this text in a file:
14579: 
14580: @example
14581: #! /usr/local/bin/gforth
14582: 
14583: ." Hello, world" CR
14584: bye
14585: @end example
14586: 
14587: @noindent
14588: and then make the file executable (chmod +x in Unix), you can run it
14589: directly from the command line. The sequence @code{#!} is used in two
14590: ways; firstly, it is recognised as a ``magic sequence'' by the operating
14591: system@footnote{The Unix kernel actually recognises two types of files:
14592: executable files and files of data, where the data is processed by an
14593: interpreter that is specified on the ``interpreter line'' -- the first
14594: line of the file, starting with the sequence #!. There may be a small
14595: limit (e.g., 32) on the number of characters that may be specified on
14596: the interpreter line.} secondly it is treated as a comment character by
14597: Gforth. Because of the second usage, a space is required between
14598: @code{#!} and the path to the executable (moreover, some Unixes
14599: require the sequence @code{#! /}).
14600: 
14601: The disadvantage of this latter technique, compared with using
14602: @file{gforthmi}, is that it is slightly slower; the Forth source code is
14603: compiled on-the-fly, each time the program is invoked.
14604: 
14605: doc-#!
14606: 
14607: 
14608: @node Modifying the Startup Sequence,  , Running Image Files, Image Files
14609: @section Modifying the Startup Sequence
14610: @cindex startup sequence for image file
14611: @cindex image file initialization sequence
14612: @cindex initialization sequence of image file
14613: 
14614: You can add your own initialization to the startup sequence of an image
14615: through the deferred word @code{'cold}. @code{'cold} is invoked just
14616: before the image-specific command line processing (i.e., loading files
14617: and evaluating (@code{-e}) strings) starts.
14618: 
14619: A sequence for adding your initialization usually looks like this:
14620: 
14621: @example
14622: :noname
14623:     Defers 'cold \ do other initialization stuff (e.g., rehashing wordlists)
14624:     ... \ your stuff
14625: ; IS 'cold
14626: @end example
14627: 
14628: @cindex turnkey image files
14629: @cindex image file, turnkey applications
14630: You can make a turnkey image by letting @code{'cold} execute a word
14631: (your turnkey application) that never returns; instead, it exits Gforth
14632: via @code{bye} or @code{throw}.
14633: 
14634: You can access the (image-specific) command-line arguments through
14635: @code{argc}, @code{argv} and @code{arg} (@pxref{OS command line
14636: arguments}).
14637: 
14638: If @code{'cold} exits normally, Gforth processes the command-line
14639: arguments as files to be loaded and strings to be evaluated.  Therefore,
14640: @code{'cold} should remove the arguments it has used in this case.
14641: 
14642: doc-'cold
14643: 
14644: @c ******************************************************************
14645: @node Engine, Cross Compiler, Image Files, Top
14646: @chapter Engine
14647: @cindex engine
14648: @cindex virtual machine
14649: 
14650: Reading this chapter is not necessary for programming with Gforth. It
14651: may be helpful for finding your way in the Gforth sources.
14652: 
14653: The ideas in this section have also been published in the following
14654: papers: Bernd Paysan, @cite{ANS fig/GNU/??? Forth} (in German),
14655: Forth-Tagung '93; M. Anton Ertl,
14656: @cite{@uref{http://www.complang.tuwien.ac.at/papers/ertl93.ps.Z, A
14657: Portable Forth Engine}}, EuroForth '93; M. Anton Ertl,
14658: @cite{@uref{http://www.complang.tuwien.ac.at/papers/ertl02.ps.gz,
14659: Threaded code variations and optimizations (extended version)}},
14660: Forth-Tagung '02.
14661: 
14662: @menu
14663: * Portability::                 
14664: * Threading::                   
14665: * Primitives::                  
14666: * Performance::                 
14667: @end menu
14668: 
14669: @node Portability, Threading, Engine, Engine
14670: @section Portability
14671: @cindex engine portability
14672: 
14673: An important goal of the Gforth Project is availability across a wide
14674: range of personal machines. fig-Forth, and, to a lesser extent, F83,
14675: achieved this goal by manually coding the engine in assembly language
14676: for several then-popular processors. This approach is very
14677: labor-intensive and the results are short-lived due to progress in
14678: computer architecture.
14679: 
14680: @cindex C, using C for the engine
14681: Others have avoided this problem by coding in C, e.g., Mitch Bradley
14682: (cforth), Mikael Patel (TILE) and Dirk Zoller (pfe). This approach is
14683: particularly popular for UNIX-based Forths due to the large variety of
14684: architectures of UNIX machines. Unfortunately an implementation in C
14685: does not mix well with the goals of efficiency and with using
14686: traditional techniques: Indirect or direct threading cannot be expressed
14687: in C, and switch threading, the fastest technique available in C, is
14688: significantly slower. Another problem with C is that it is very
14689: cumbersome to express double integer arithmetic.
14690: 
14691: @cindex GNU C for the engine
14692: @cindex long long
14693: Fortunately, there is a portable language that does not have these
14694: limitations: GNU C, the version of C processed by the GNU C compiler
14695: (@pxref{C Extensions, , Extensions to the C Language Family, gcc.info,
14696: GNU C Manual}). Its labels as values feature (@pxref{Labels as Values, ,
14697: Labels as Values, gcc.info, GNU C Manual}) makes direct and indirect
14698: threading possible, its @code{long long} type (@pxref{Long Long, ,
14699: Double-Word Integers, gcc.info, GNU C Manual}) corresponds to Forth's
14700: double numbers on many systems.  GNU C is freely available on all
14701: important (and many unimportant) UNIX machines, VMS, 80386s running
14702: MS-DOS, the Amiga, and the Atari ST, so a Forth written in GNU C can run
14703: on all these machines.
14704: 
14705: Writing in a portable language has the reputation of producing code that
14706: is slower than assembly. For our Forth engine we repeatedly looked at
14707: the code produced by the compiler and eliminated most compiler-induced
14708: inefficiencies by appropriate changes in the source code.
14709: 
14710: @cindex explicit register declarations
14711: @cindex --enable-force-reg, configuration flag
14712: @cindex -DFORCE_REG
14713: However, register allocation cannot be portably influenced by the
14714: programmer, leading to some inefficiencies on register-starved
14715: machines. We use explicit register declarations (@pxref{Explicit Reg
14716: Vars, , Variables in Specified Registers, gcc.info, GNU C Manual}) to
14717: improve the speed on some machines. They are turned on by using the
14718: configuration flag @code{--enable-force-reg} (@code{gcc} switch
14719: @code{-DFORCE_REG}). Unfortunately, this feature not only depends on the
14720: machine, but also on the compiler version: On some machines some
14721: compiler versions produce incorrect code when certain explicit register
14722: declarations are used. So by default @code{-DFORCE_REG} is not used.
14723: 
14724: @node Threading, Primitives, Portability, Engine
14725: @section Threading
14726: @cindex inner interpreter implementation
14727: @cindex threaded code implementation
14728: 
14729: @cindex labels as values
14730: GNU C's labels as values extension (available since @code{gcc-2.0},
14731: @pxref{Labels as Values, , Labels as Values, gcc.info, GNU C Manual})
14732: makes it possible to take the address of @i{label} by writing
14733: @code{&&@i{label}}.  This address can then be used in a statement like
14734: @code{goto *@i{address}}. I.e., @code{goto *&&x} is the same as
14735: @code{goto x}.
14736: 
14737: @cindex @code{NEXT}, indirect threaded
14738: @cindex indirect threaded inner interpreter
14739: @cindex inner interpreter, indirect threaded
14740: With this feature an indirect threaded @code{NEXT} looks like:
14741: @example
14742: cfa = *ip++;
14743: ca = *cfa;
14744: goto *ca;
14745: @end example
14746: @cindex instruction pointer
14747: For those unfamiliar with the names: @code{ip} is the Forth instruction
14748: pointer; the @code{cfa} (code-field address) corresponds to ANS Forths
14749: execution token and points to the code field of the next word to be
14750: executed; The @code{ca} (code address) fetched from there points to some
14751: executable code, e.g., a primitive or the colon definition handler
14752: @code{docol}.
14753: 
14754: @cindex @code{NEXT}, direct threaded
14755: @cindex direct threaded inner interpreter
14756: @cindex inner interpreter, direct threaded
14757: Direct threading is even simpler:
14758: @example
14759: ca = *ip++;
14760: goto *ca;
14761: @end example
14762: 
14763: Of course we have packaged the whole thing neatly in macros called
14764: @code{NEXT} and @code{NEXT1} (the part of @code{NEXT} after fetching the cfa).
14765: 
14766: @menu
14767: * Scheduling::                  
14768: * Direct or Indirect Threaded?::  
14769: * Dynamic Superinstructions::   
14770: * DOES>::                       
14771: @end menu
14772: 
14773: @node Scheduling, Direct or Indirect Threaded?, Threading, Threading
14774: @subsection Scheduling
14775: @cindex inner interpreter optimization
14776: 
14777: There is a little complication: Pipelined and superscalar processors,
14778: i.e., RISC and some modern CISC machines can process independent
14779: instructions while waiting for the results of an instruction. The
14780: compiler usually reorders (schedules) the instructions in a way that
14781: achieves good usage of these delay slots. However, on our first tries
14782: the compiler did not do well on scheduling primitives. E.g., for
14783: @code{+} implemented as
14784: @example
14785: n=sp[0]+sp[1];
14786: sp++;
14787: sp[0]=n;
14788: NEXT;
14789: @end example
14790: the @code{NEXT} comes strictly after the other code, i.e., there is
14791: nearly no scheduling. After a little thought the problem becomes clear:
14792: The compiler cannot know that @code{sp} and @code{ip} point to different
14793: addresses (and the version of @code{gcc} we used would not know it even
14794: if it was possible), so it could not move the load of the cfa above the
14795: store to the TOS. Indeed the pointers could be the same, if code on or
14796: very near the top of stack were executed. In the interest of speed we
14797: chose to forbid this probably unused ``feature'' and helped the compiler
14798: in scheduling: @code{NEXT} is divided into several parts:
14799: @code{NEXT_P0}, @code{NEXT_P1} and @code{NEXT_P2}). @code{+} now looks
14800: like:
14801: @example
14802: NEXT_P0;
14803: n=sp[0]+sp[1];
14804: sp++;
14805: NEXT_P1;
14806: sp[0]=n;
14807: NEXT_P2;
14808: @end example
14809: 
14810: There are various schemes that distribute the different operations of
14811: NEXT between these parts in several ways; in general, different schemes
14812: perform best on different processors.  We use a scheme for most
14813: architectures that performs well for most processors of this
14814: architecture; in the future we may switch to benchmarking and chosing
14815: the scheme on installation time.
14816: 
14817: 
14818: @node Direct or Indirect Threaded?, Dynamic Superinstructions, Scheduling, Threading
14819: @subsection Direct or Indirect Threaded?
14820: @cindex threading, direct or indirect?
14821: 
14822: Threaded forth code consists of references to primitives (simple machine
14823: code routines like @code{+}) and to non-primitives (e.g., colon
14824: definitions, variables, constants); for a specific class of
14825: non-primitives (e.g., variables) there is one code routine (e.g.,
14826: @code{dovar}), but each variable needs a separate reference to its data.
14827: 
14828: Traditionally Forth has been implemented as indirect threaded code,
14829: because this allows to use only one cell to reference a non-primitive
14830: (basically you point to the data, and find the code address there).
14831: 
14832: @cindex primitive-centric threaded code
14833: However, threaded code in Gforth (since 0.6.0) uses two cells for
14834: non-primitives, one for the code address, and one for the data address;
14835: the data pointer is an immediate argument for the virtual machine
14836: instruction represented by the code address.  We call this
14837: @emph{primitive-centric} threaded code, because all code addresses point
14838: to simple primitives.  E.g., for a variable, the code address is for
14839: @code{lit} (also used for integer literals like @code{99}).
14840: 
14841: Primitive-centric threaded code allows us to use (faster) direct
14842: threading as dispatch method, completely portably (direct threaded code
14843: in Gforth before 0.6.0 required architecture-specific code).  It also
14844: eliminates the performance problems related to I-cache consistency that
14845: 386 implementations have with direct threaded code, and allows
14846: additional optimizations.
14847: 
14848: @cindex hybrid direct/indirect threaded code
14849: There is a catch, however: the @var{xt} parameter of @code{execute} can
14850: occupy only one cell, so how do we pass non-primitives with their code
14851: @emph{and} data addresses to them?  Our answer is to use indirect
14852: threaded dispatch for @code{execute} and other words that use a
14853: single-cell xt.  So, normal threaded code in colon definitions uses
14854: direct threading, and @code{execute} and similar words, which dispatch
14855: to xts on the data stack, use indirect threaded code.  We call this
14856: @emph{hybrid direct/indirect} threaded code.
14857: 
14858: @cindex engines, gforth vs. gforth-fast vs. gforth-itc
14859: @cindex gforth engine
14860: @cindex gforth-fast engine
14861: The engines @command{gforth} and @command{gforth-fast} use hybrid
14862: direct/indirect threaded code.  This means that with these engines you
14863: cannot use @code{,} to compile an xt.  Instead, you have to use
14864: @code{compile,}.
14865: 
14866: @cindex gforth-itc engine
14867: If you want to compile xts with @code{,}, use @command{gforth-itc}.
14868: This engine uses plain old indirect threaded code.  It still compiles in
14869: a primitive-centric style, so you cannot use @code{compile,} instead of
14870: @code{,} (e.g., for producing tables of xts with @code{] word1 word2
14871: ... [}).  If you want to do that, you have to use @command{gforth-itc}
14872: and execute @code{' , is compile,}.  Your program can check if it is
14873: running on a hybrid direct/indirect threaded engine or a pure indirect
14874: threaded engine with @code{threading-method} (@pxref{Threading Words}).
14875: 
14876: 
14877: @node Dynamic Superinstructions, DOES>, Direct or Indirect Threaded?, Threading
14878: @subsection Dynamic Superinstructions
14879: @cindex Dynamic superinstructions with replication
14880: @cindex Superinstructions
14881: @cindex Replication
14882: 
14883: The engines @command{gforth} and @command{gforth-fast} use another
14884: optimization: Dynamic superinstructions with replication.  As an
14885: example, consider the following colon definition:
14886: 
14887: @example
14888: : squared ( n1 -- n2 )
14889:   dup * ;
14890: @end example
14891: 
14892: Gforth compiles this into the threaded code sequence
14893: 
14894: @example
14895: dup
14896: *
14897: ;s
14898: @end example
14899: 
14900: In normal direct threaded code there is a code address occupying one
14901: cell for each of these primitives.  Each code address points to a
14902: machine code routine, and the interpreter jumps to this machine code in
14903: order to execute the primitive.  The routines for these three
14904: primitives are (in @command{gforth-fast} on the 386):
14905: 
14906: @example
14907: Code dup  
14908: ( $804B950 )  add     esi , # -4  \ $83 $C6 $FC 
14909: ( $804B953 )  add     ebx , # 4  \ $83 $C3 $4 
14910: ( $804B956 )  mov     dword ptr 4 [esi] , ecx  \ $89 $4E $4 
14911: ( $804B959 )  jmp     dword ptr FC [ebx]  \ $FF $63 $FC 
14912: end-code
14913: Code *  
14914: ( $804ACC4 )  mov     eax , dword ptr 4 [esi]  \ $8B $46 $4 
14915: ( $804ACC7 )  add     esi , # 4  \ $83 $C6 $4 
14916: ( $804ACCA )  add     ebx , # 4  \ $83 $C3 $4 
14917: ( $804ACCD )  imul    ecx , eax  \ $F $AF $C8 
14918: ( $804ACD0 )  jmp     dword ptr FC [ebx]  \ $FF $63 $FC 
14919: end-code
14920: Code ;s  
14921: ( $804A693 )  mov     eax , dword ptr [edi]  \ $8B $7 
14922: ( $804A695 )  add     edi , # 4  \ $83 $C7 $4 
14923: ( $804A698 )  lea     ebx , dword ptr 4 [eax]  \ $8D $58 $4 
14924: ( $804A69B )  jmp     dword ptr FC [ebx]  \ $FF $63 $FC 
14925: end-code
14926: @end example
14927: 
14928: With dynamic superinstructions and replication the compiler does not
14929: just lay down the threaded code, but also copies the machine code
14930: fragments, usually without the jump at the end.
14931: 
14932: @example
14933: ( $4057D27D )  add     esi , # -4  \ $83 $C6 $FC 
14934: ( $4057D280 )  add     ebx , # 4  \ $83 $C3 $4 
14935: ( $4057D283 )  mov     dword ptr 4 [esi] , ecx  \ $89 $4E $4 
14936: ( $4057D286 )  mov     eax , dword ptr 4 [esi]  \ $8B $46 $4 
14937: ( $4057D289 )  add     esi , # 4  \ $83 $C6 $4 
14938: ( $4057D28C )  add     ebx , # 4  \ $83 $C3 $4 
14939: ( $4057D28F )  imul    ecx , eax  \ $F $AF $C8 
14940: ( $4057D292 )  mov     eax , dword ptr [edi]  \ $8B $7 
14941: ( $4057D294 )  add     edi , # 4  \ $83 $C7 $4 
14942: ( $4057D297 )  lea     ebx , dword ptr 4 [eax]  \ $8D $58 $4 
14943: ( $4057D29A )  jmp     dword ptr FC [ebx]  \ $FF $63 $FC 
14944: @end example
14945: 
14946: Only when a threaded-code control-flow change happens (e.g., in
14947: @code{;s}), the jump is appended.  This optimization eliminates many of
14948: these jumps and makes the rest much more predictable.  The speedup
14949: depends on the processor and the application; on the Athlon and Pentium
14950: III this optimization typically produces a speedup by a factor of 2.
14951: 
14952: The code addresses in the direct-threaded code are set to point to the
14953: appropriate points in the copied machine code, in this example like
14954: this:
14955: 
14956: @example
14957: primitive  code address
14958:    dup       $4057D27D
14959:    *         $4057D286
14960:    ;s        $4057D292
14961: @end example
14962: 
14963: Thus there can be threaded-code jumps to any place in this piece of
14964: code.  This also simplifies decompilation quite a bit.
14965: 
14966: @cindex --no-dynamic command-line option
14967: @cindex --no-super command-line option
14968: You can disable this optimization with @option{--no-dynamic}.  You can
14969: use the copying without eliminating the jumps (i.e., dynamic
14970: replication, but without superinstructions) with @option{--no-super};
14971: this gives the branch prediction benefit alone; the effect on
14972: performance depends on the CPU; on the Athlon and Pentium III the
14973: speedup is a little less than for dynamic superinstructions with
14974: replication.
14975: 
14976: @cindex patching threaded code
14977: One use of these options is if you want to patch the threaded code.
14978: With superinstructions, many of the dispatch jumps are eliminated, so
14979: patching often has no effect.  These options preserve all the dispatch
14980: jumps.
14981: 
14982: @cindex --dynamic command-line option
14983: On some machines dynamic superinstructions are disabled by default,
14984: because it is unsafe on these machines.  However, if you feel
14985: adventurous, you can enable it with @option{--dynamic}.
14986: 
14987: @node DOES>,  , Dynamic Superinstructions, Threading
14988: @subsection DOES>
14989: @cindex @code{DOES>} implementation
14990: 
14991: @cindex @code{dodoes} routine
14992: @cindex @code{DOES>}-code
14993: One of the most complex parts of a Forth engine is @code{dodoes}, i.e.,
14994: the chunk of code executed by every word defined by a
14995: @code{CREATE}...@code{DOES>} pair; actually with primitive-centric code,
14996: this is only needed if the xt of the word is @code{execute}d. The main
14997: problem here is: How to find the Forth code to be executed, i.e. the
14998: code after the @code{DOES>} (the @code{DOES>}-code)? There are two
14999: solutions:
15000: 
15001: In fig-Forth the code field points directly to the @code{dodoes} and the
15002: @code{DOES>}-code address is stored in the cell after the code address
15003: (i.e. at @code{@i{CFA} cell+}). It may seem that this solution is
15004: illegal in the Forth-79 and all later standards, because in fig-Forth
15005: this address lies in the body (which is illegal in these
15006: standards). However, by making the code field larger for all words this
15007: solution becomes legal again.  We use this approach.  Leaving a cell
15008: unused in most words is a bit wasteful, but on the machines we are
15009: targeting this is hardly a problem.
15010: 
15011: 
15012: @node Primitives, Performance, Threading, Engine
15013: @section Primitives
15014: @cindex primitives, implementation
15015: @cindex virtual machine instructions, implementation
15016: 
15017: @menu
15018: * Automatic Generation::        
15019: * TOS Optimization::            
15020: * Produced code::               
15021: @end menu
15022: 
15023: @node Automatic Generation, TOS Optimization, Primitives, Primitives
15024: @subsection Automatic Generation
15025: @cindex primitives, automatic generation
15026: 
15027: @cindex @file{prims2x.fs}
15028: 
15029: Since the primitives are implemented in a portable language, there is no
15030: longer any need to minimize the number of primitives. On the contrary,
15031: having many primitives has an advantage: speed. In order to reduce the
15032: number of errors in primitives and to make programming them easier, we
15033: provide a tool, the primitive generator (@file{prims2x.fs} aka Vmgen,
15034: @pxref{Top, Vmgen, Introduction, vmgen, Vmgen}), that automatically
15035: generates most (and sometimes all) of the C code for a primitive from
15036: the stack effect notation.  The source for a primitive has the following
15037: form:
15038: 
15039: @cindex primitive source format
15040: @format
15041: @i{Forth-name}  ( @i{stack-effect} )        @i{category}    [@i{pronounc.}]
15042: [@code{""}@i{glossary entry}@code{""}]
15043: @i{C code}
15044: [@code{:}
15045: @i{Forth code}]
15046: @end format
15047: 
15048: The items in brackets are optional. The category and glossary fields
15049: are there for generating the documentation, the Forth code is there
15050: for manual implementations on machines without GNU C. E.g., the source
15051: for the primitive @code{+} is:
15052: @example
15053: +    ( n1 n2 -- n )   core    plus
15054: n = n1+n2;
15055: @end example
15056: 
15057: This looks like a specification, but in fact @code{n = n1+n2} is C
15058: code. Our primitive generation tool extracts a lot of information from
15059: the stack effect notations@footnote{We use a one-stack notation, even
15060: though we have separate data and floating-point stacks; The separate
15061: notation can be generated easily from the unified notation.}: The number
15062: of items popped from and pushed on the stack, their type, and by what
15063: name they are referred to in the C code. It then generates a C code
15064: prelude and postlude for each primitive. The final C code for @code{+}
15065: looks like this:
15066: 
15067: @example
15068: I_plus: /* + ( n1 n2 -- n ) */  /* label, stack effect */
15069: /*  */                          /* documentation */
15070: NAME("+")                       /* debugging output (with -DDEBUG) */
15071: @{
15072: DEF_CA                          /* definition of variable ca (indirect threading) */
15073: Cell n1;                        /* definitions of variables */
15074: Cell n2;
15075: Cell n;
15076: NEXT_P0;                        /* NEXT part 0 */
15077: n1 = (Cell) sp[1];              /* input */
15078: n2 = (Cell) TOS;
15079: sp += 1;                        /* stack adjustment */
15080: @{
15081: n = n1+n2;                      /* C code taken from the source */
15082: @}
15083: NEXT_P1;                        /* NEXT part 1 */
15084: TOS = (Cell)n;                  /* output */
15085: NEXT_P2;                        /* NEXT part 2 */
15086: @}
15087: @end example
15088: 
15089: This looks long and inefficient, but the GNU C compiler optimizes quite
15090: well and produces optimal code for @code{+} on, e.g., the R3000 and the
15091: HP RISC machines: Defining the @code{n}s does not produce any code, and
15092: using them as intermediate storage also adds no cost.
15093: 
15094: There are also other optimizations that are not illustrated by this
15095: example: assignments between simple variables are usually for free (copy
15096: propagation). If one of the stack items is not used by the primitive
15097: (e.g.  in @code{drop}), the compiler eliminates the load from the stack
15098: (dead code elimination). On the other hand, there are some things that
15099: the compiler does not do, therefore they are performed by
15100: @file{prims2x.fs}: The compiler does not optimize code away that stores
15101: a stack item to the place where it just came from (e.g., @code{over}).
15102: 
15103: While programming a primitive is usually easy, there are a few cases
15104: where the programmer has to take the actions of the generator into
15105: account, most notably @code{?dup}, but also words that do not (always)
15106: fall through to @code{NEXT}.
15107: 
15108: For more information
15109: 
15110: @node TOS Optimization, Produced code, Automatic Generation, Primitives
15111: @subsection TOS Optimization
15112: @cindex TOS optimization for primitives
15113: @cindex primitives, keeping the TOS in a register
15114: 
15115: An important optimization for stack machine emulators, e.g., Forth
15116: engines, is keeping  one or more of the top stack items in
15117: registers.  If a word has the stack effect @i{in1}...@i{inx} @code{--}
15118: @i{out1}...@i{outy}, keeping the top @i{n} items in registers
15119: @itemize @bullet
15120: @item
15121: is better than keeping @i{n-1} items, if @i{x>=n} and @i{y>=n},
15122: due to fewer loads from and stores to the stack.
15123: @item is slower than keeping @i{n-1} items, if @i{x<>y} and @i{x<n} and
15124: @i{y<n}, due to additional moves between registers.
15125: @end itemize
15126: 
15127: @cindex -DUSE_TOS
15128: @cindex -DUSE_NO_TOS
15129: In particular, keeping one item in a register is never a disadvantage,
15130: if there are enough registers. Keeping two items in registers is a
15131: disadvantage for frequent words like @code{?branch}, constants,
15132: variables, literals and @code{i}. Therefore our generator only produces
15133: code that keeps zero or one items in registers. The generated C code
15134: covers both cases; the selection between these alternatives is made at
15135: C-compile time using the switch @code{-DUSE_TOS}. @code{TOS} in the C
15136: code for @code{+} is just a simple variable name in the one-item case,
15137: otherwise it is a macro that expands into @code{sp[0]}. Note that the
15138: GNU C compiler tries to keep simple variables like @code{TOS} in
15139: registers, and it usually succeeds, if there are enough registers.
15140: 
15141: @cindex -DUSE_FTOS
15142: @cindex -DUSE_NO_FTOS
15143: The primitive generator performs the TOS optimization for the
15144: floating-point stack, too (@code{-DUSE_FTOS}). For floating-point
15145: operations the benefit of this optimization is even larger:
15146: floating-point operations take quite long on most processors, but can be
15147: performed in parallel with other operations as long as their results are
15148: not used. If the FP-TOS is kept in a register, this works. If
15149: it is kept on the stack, i.e., in memory, the store into memory has to
15150: wait for the result of the floating-point operation, lengthening the
15151: execution time of the primitive considerably.
15152: 
15153: The TOS optimization makes the automatic generation of primitives a
15154: bit more complicated. Just replacing all occurrences of @code{sp[0]} by
15155: @code{TOS} is not sufficient. There are some special cases to
15156: consider:
15157: @itemize @bullet
15158: @item In the case of @code{dup ( w -- w w )} the generator must not
15159: eliminate the store to the original location of the item on the stack,
15160: if the TOS optimization is turned on.
15161: @item Primitives with stack effects of the form @code{--}
15162: @i{out1}...@i{outy} must store the TOS to the stack at the start.
15163: Likewise, primitives with the stack effect @i{in1}...@i{inx} @code{--}
15164: must load the TOS from the stack at the end. But for the null stack
15165: effect @code{--} no stores or loads should be generated.
15166: @end itemize
15167: 
15168: @node Produced code,  , TOS Optimization, Primitives
15169: @subsection Produced code
15170: @cindex primitives, assembly code listing
15171: 
15172: @cindex @file{engine.s}
15173: To see what assembly code is produced for the primitives on your machine
15174: with your compiler and your flag settings, type @code{make engine.s} and
15175: look at the resulting file @file{engine.s}.  Alternatively, you can also
15176: disassemble the code of primitives with @code{see} on some architectures.
15177: 
15178: @node  Performance,  , Primitives, Engine
15179: @section Performance
15180: @cindex performance of some Forth interpreters
15181: @cindex engine performance
15182: @cindex benchmarking Forth systems
15183: @cindex Gforth performance
15184: 
15185: On RISCs the Gforth engine is very close to optimal; i.e., it is usually
15186: impossible to write a significantly faster threaded-code engine.
15187: 
15188: On register-starved machines like the 386 architecture processors
15189: improvements are possible, because @code{gcc} does not utilize the
15190: registers as well as a human, even with explicit register declarations;
15191: e.g., Bernd Beuster wrote a Forth system fragment in assembly language
15192: and hand-tuned it for the 486; this system is 1.19 times faster on the
15193: Sieve benchmark on a 486DX2/66 than Gforth compiled with
15194: @code{gcc-2.6.3} with @code{-DFORCE_REG}.  The situation has improved
15195: with gcc-2.95 and gforth-0.4.9; now the most important virtual machine
15196: registers fit in real registers (and we can even afford to use the TOS
15197: optimization), resulting in a speedup of 1.14 on the sieve over the
15198: earlier results.  And dynamic superinstructions provide another speedup
15199: (but only around a factor 1.2 on the 486).
15200: 
15201: @cindex Win32Forth performance
15202: @cindex NT Forth performance
15203: @cindex eforth performance
15204: @cindex ThisForth performance
15205: @cindex PFE performance
15206: @cindex TILE performance
15207: The potential advantage of assembly language implementations is not
15208: necessarily realized in complete Forth systems: We compared Gforth-0.5.9
15209: (direct threaded, compiled with @code{gcc-2.95.1} and
15210: @code{-DFORCE_REG}) with Win32Forth 1.2093 (newer versions are
15211: reportedly much faster), LMI's NT Forth (Beta, May 1994) and Eforth
15212: (with and without peephole (aka pinhole) optimization of the threaded
15213: code); all these systems were written in assembly language. We also
15214: compared Gforth with three systems written in C: PFE-0.9.14 (compiled
15215: with @code{gcc-2.6.3} with the default configuration for Linux:
15216: @code{-O2 -fomit-frame-pointer -DUSE_REGS -DUNROLL_NEXT}), ThisForth
15217: Beta (compiled with @code{gcc-2.6.3 -O3 -fomit-frame-pointer}; ThisForth
15218: employs peephole optimization of the threaded code) and TILE (compiled
15219: with @code{make opt}). We benchmarked Gforth, PFE, ThisForth and TILE on
15220: a 486DX2/66 under Linux. Kenneth O'Heskin kindly provided the results
15221: for Win32Forth and NT Forth on a 486DX2/66 with similar memory
15222: performance under Windows NT. Marcel Hendrix ported Eforth to Linux,
15223: then extended it to run the benchmarks, added the peephole optimizer,
15224: ran the benchmarks and reported the results.
15225: 
15226: We used four small benchmarks: the ubiquitous Sieve; bubble-sorting and
15227: matrix multiplication come from the Stanford integer benchmarks and have
15228: been translated into Forth by Martin Fraeman; we used the versions
15229: included in the TILE Forth package, but with bigger data set sizes; and
15230: a recursive Fibonacci number computation for benchmarking calling
15231: performance. The following table shows the time taken for the benchmarks
15232: scaled by the time taken by Gforth (in other words, it shows the speedup
15233: factor that Gforth achieved over the other systems).
15234: 
15235: @example
15236: relative       Win32-    NT       eforth       This-      
15237: time     Gforth Forth Forth eforth  +opt   PFE Forth  TILE
15238: sieve      1.00  2.16  1.78   2.16  1.32  2.46  4.96 13.37
15239: bubble     1.00  1.93  2.07   2.18  1.29  2.21        5.70
15240: matmul     1.00  1.92  1.76   1.90  0.96  2.06        5.32
15241: fib        1.00  2.32  2.03   1.86  1.31  2.64  4.55  6.54
15242: @end example
15243: 
15244: You may be quite surprised by the good performance of Gforth when
15245: compared with systems written in assembly language. One important reason
15246: for the disappointing performance of these other systems is probably
15247: that they are not written optimally for the 486 (e.g., they use the
15248: @code{lods} instruction). In addition, Win32Forth uses a comfortable,
15249: but costly method for relocating the Forth image: like @code{cforth}, it
15250: computes the actual addresses at run time, resulting in two address
15251: computations per @code{NEXT} (@pxref{Image File Background}).
15252: 
15253: The speedup of Gforth over PFE, ThisForth and TILE can be easily
15254: explained with the self-imposed restriction of the latter systems to
15255: standard C, which makes efficient threading impossible (however, the
15256: measured implementation of PFE uses a GNU C extension: @pxref{Global Reg
15257: Vars, , Defining Global Register Variables, gcc.info, GNU C Manual}).
15258: Moreover, current C compilers have a hard time optimizing other aspects
15259: of the ThisForth and the TILE source.
15260: 
15261: The performance of Gforth on 386 architecture processors varies widely
15262: with the version of @code{gcc} used. E.g., @code{gcc-2.5.8} failed to
15263: allocate any of the virtual machine registers into real machine
15264: registers by itself and would not work correctly with explicit register
15265: declarations, giving a significantly slower engine (on a 486DX2/66
15266: running the Sieve) than the one measured above.
15267: 
15268: Note that there have been several releases of Win32Forth since the
15269: release presented here, so the results presented above may have little
15270: predictive value for the performance of Win32Forth today (results for
15271: the current release on an i486DX2/66 are welcome).
15272: 
15273: @cindex @file{Benchres}
15274: In
15275: @cite{@uref{http://www.complang.tuwien.ac.at/papers/ertl&maierhofer95.ps.gz,
15276: Translating Forth to Efficient C}} by M. Anton Ertl and Martin
15277: Maierhofer (presented at EuroForth '95), an indirect threaded version of
15278: Gforth is compared with Win32Forth, NT Forth, PFE, ThisForth, and
15279: several native code systems; that version of Gforth is slower on a 486
15280: than the version used here. You can find a newer version of these
15281: measurements at
15282: @uref{http://www.complang.tuwien.ac.at/forth/performance.html}. You can
15283: find numbers for Gforth on various machines in @file{Benchres}.
15284: 
15285: @c ******************************************************************
15286: @c @node Binding to System Library, Cross Compiler, Engine, Top
15287: @c @chapter Binding to System Library
15288: 
15289: @c ****************************************************************
15290: @node Cross Compiler, Bugs, Engine, Top
15291: @chapter Cross Compiler
15292: @cindex @file{cross.fs}
15293: @cindex cross-compiler
15294: @cindex metacompiler
15295: @cindex target compiler
15296: 
15297: The cross compiler is used to bootstrap a Forth kernel. Since Gforth is
15298: mostly written in Forth, including crucial parts like the outer
15299: interpreter and compiler, it needs compiled Forth code to get
15300: started. The cross compiler allows to create new images for other
15301: architectures, even running under another Forth system.
15302: 
15303: @menu
15304: * Using the Cross Compiler::    
15305: * How the Cross Compiler Works::  
15306: @end menu
15307: 
15308: @node Using the Cross Compiler, How the Cross Compiler Works, Cross Compiler, Cross Compiler
15309: @section Using the Cross Compiler
15310: 
15311: The cross compiler uses a language that resembles Forth, but isn't. The
15312: main difference is that you can execute Forth code after definition,
15313: while you usually can't execute the code compiled by cross, because the
15314: code you are compiling is typically for a different computer than the
15315: one you are compiling on.
15316: 
15317: @c anton: This chapter is somewhat different from waht I would expect: I
15318: @c would expect an explanation of the cross language and how to create an
15319: @c application image with it.  The section explains some aspects of
15320: @c creating a Gforth kernel.
15321: 
15322: The Makefile is already set up to allow you to create kernels for new
15323: architectures with a simple make command. The generic kernels using the
15324: GCC compiled virtual machine are created in the normal build process
15325: with @code{make}. To create a embedded Gforth executable for e.g. the
15326: 8086 processor (running on a DOS machine), type
15327: 
15328: @example
15329: make kernl-8086.fi
15330: @end example
15331: 
15332: This will use the machine description from the @file{arch/8086}
15333: directory to create a new kernel. A machine file may look like that:
15334: 
15335: @example
15336: \ Parameter for target systems                         06oct92py
15337: 
15338:     4 Constant cell             \ cell size in bytes
15339:     2 Constant cell<<           \ cell shift to bytes
15340:     5 Constant cell>bit         \ cell shift to bits
15341:     8 Constant bits/char        \ bits per character
15342:     8 Constant bits/byte        \ bits per byte [default: 8]
15343:     8 Constant float            \ bytes per float
15344:     8 Constant /maxalign        \ maximum alignment in bytes
15345: false Constant bigendian        \ byte order
15346: ( true=big, false=little )
15347: 
15348: include machpc.fs               \ feature list
15349: @end example
15350: 
15351: This part is obligatory for the cross compiler itself, the feature list
15352: is used by the kernel to conditionally compile some features in and out,
15353: depending on whether the target supports these features.
15354: 
15355: There are some optional features, if you define your own primitives,
15356: have an assembler, or need special, nonstandard preparation to make the
15357: boot process work. @code{asm-include} includes an assembler,
15358: @code{prims-include} includes primitives, and @code{>boot} prepares for
15359: booting.
15360: 
15361: @example
15362: : asm-include    ." Include assembler" cr
15363:   s" arch/8086/asm.fs" included ;
15364: 
15365: : prims-include  ." Include primitives" cr
15366:   s" arch/8086/prim.fs" included ;
15367: 
15368: : >boot          ." Prepare booting" cr
15369:   s" ' boot >body into-forth 1+ !" evaluate ;
15370: @end example
15371: 
15372: These words are used as sort of macro during the cross compilation in
15373: the file @file{kernel/main.fs}. Instead of using these macros, it would
15374: be possible --- but more complicated --- to write a new kernel project
15375: file, too.
15376: 
15377: @file{kernel/main.fs} expects the machine description file name on the
15378: stack; the cross compiler itself (@file{cross.fs}) assumes that either
15379: @code{mach-file} leaves a counted string on the stack, or
15380: @code{machine-file} leaves an address, count pair of the filename on the
15381: stack.
15382: 
15383: The feature list is typically controlled using @code{SetValue}, generic
15384: files that are used by several projects can use @code{DefaultValue}
15385: instead. Both functions work like @code{Value}, when the value isn't
15386: defined, but @code{SetValue} works like @code{to} if the value is
15387: defined, and @code{DefaultValue} doesn't set anything, if the value is
15388: defined.
15389: 
15390: @example
15391: \ generic mach file for pc gforth                       03sep97jaw
15392: 
15393: true DefaultValue NIL  \ relocating
15394: 
15395: >ENVIRON
15396: 
15397: true DefaultValue file          \ controls the presence of the
15398:                                 \ file access wordset
15399: true DefaultValue OS            \ flag to indicate a operating system
15400: 
15401: true DefaultValue prims         \ true: primitives are c-code
15402: 
15403: true DefaultValue floating      \ floating point wordset is present
15404: 
15405: true DefaultValue glocals       \ gforth locals are present
15406:                                 \ will be loaded
15407: true DefaultValue dcomps        \ double number comparisons
15408: 
15409: true DefaultValue hash          \ hashing primitives are loaded/present
15410: 
15411: true DefaultValue xconds        \ used together with glocals,
15412:                                 \ special conditionals supporting gforths'
15413:                                 \ local variables
15414: true DefaultValue header        \ save a header information
15415: 
15416: true DefaultValue backtrace     \ enables backtrace code
15417: 
15418: false DefaultValue ec
15419: false DefaultValue crlf
15420: 
15421: cell 2 = [IF] &32 [ELSE] &256 [THEN] KB DefaultValue kernel-size
15422: 
15423: &16 KB          DefaultValue stack-size
15424: &15 KB &512 +   DefaultValue fstack-size
15425: &15 KB          DefaultValue rstack-size
15426: &14 KB &512 +   DefaultValue lstack-size
15427: @end example
15428: 
15429: @node How the Cross Compiler Works,  , Using the Cross Compiler, Cross Compiler
15430: @section How the Cross Compiler Works
15431: 
15432: @node Bugs, Origin, Cross Compiler, Top
15433: @appendix Bugs
15434: @cindex bug reporting
15435: 
15436: Known bugs are described in the file @file{BUGS} in the Gforth distribution.
15437: 
15438: If you find a bug, please submit a bug report through
15439: @uref{https://savannah.gnu.org/bugs/?func=addbug&group=gforth}.
15440: 
15441: @itemize @bullet
15442: @item
15443: A program (or a sequence of keyboard commands) that reproduces the bug.
15444: @item
15445: A description of what you think constitutes the buggy behaviour.
15446: @item
15447: The Gforth version used (it is announced at the start of an
15448: interactive Gforth session).
15449: @item
15450: The machine and operating system (on Unix
15451: systems @code{uname -a} will report this information).
15452: @item
15453: The installation options (you can find the configure options at the
15454: start of @file{config.status}) and configuration (@code{configure}
15455: output or @file{config.cache}).
15456: @item
15457: A complete list of changes (if any) you (or your installer) have made to the
15458: Gforth sources.
15459: @end itemize
15460: 
15461: For a thorough guide on reporting bugs read @ref{Bug Reporting, , How
15462: to Report Bugs, gcc.info, GNU C Manual}.
15463: 
15464: 
15465: @node Origin, Forth-related information, Bugs, Top
15466: @appendix Authors and Ancestors of Gforth
15467: 
15468: @section Authors and Contributors
15469: @cindex authors of Gforth
15470: @cindex contributors to Gforth
15471: 
15472: The Gforth project was started in mid-1992 by Bernd Paysan and Anton
15473: Ertl. The third major author was Jens Wilke.  Neal Crook contributed a
15474: lot to the manual.  Assemblers and disassemblers were contributed by
15475: Andrew McKewan, Christian Pirker, and Bernd Thallner.  Lennart Benschop
15476: (who was one of Gforth's first users, in mid-1993) and Stuart Ramsden
15477: inspired us with their continuous feedback. Lennart Benshop contributed
15478: @file{glosgen.fs}, while Stuart Ramsden has been working on automatic
15479: support for calling C libraries. Helpful comments also came from Paul
15480: Kleinrubatscher, Christian Pirker, Dirk Zoller, Marcel Hendrix, John
15481: Wavrik, Barrie Stott, Marc de Groot, Jorge Acerada, Bruce Hoyt, Robert
15482: Epprecht, Dennis Ruffer and David N. Williams. Since the release of
15483: Gforth-0.2.1 there were also helpful comments from many others; thank
15484: you all, sorry for not listing you here (but digging through my mailbox
15485: to extract your names is on my to-do list).
15486: 
15487: Gforth also owes a lot to the authors of the tools we used (GCC, CVS,
15488: and autoconf, among others), and to the creators of the Internet: Gforth
15489: was developed across the Internet, and its authors did not meet
15490: physically for the first 4 years of development.
15491: 
15492: @section Pedigree
15493: @cindex pedigree of Gforth
15494: 
15495: Gforth descends from bigFORTH (1993) and fig-Forth.  Of course, a
15496: significant part of the design of Gforth was prescribed by ANS Forth.
15497: 
15498: Bernd Paysan wrote bigFORTH, a descendent from TurboForth, an unreleased
15499: 32 bit native code version of VolksForth for the Atari ST, written
15500: mostly by Dietrich Weineck.
15501: 
15502: VolksForth was written by Klaus Schleisiek, Bernd Pennemann, Georg
15503: Rehfeld and Dietrich Weineck for the C64 (called UltraForth there) in
15504: the mid-80s and ported to the Atari ST in 1986.  It descends from fig-Forth.
15505: 
15506: @c Henry Laxen and Mike Perry wrote F83 as a model implementation of the
15507: @c Forth-83 standard. !! Pedigree? When?
15508: 
15509: A team led by Bill Ragsdale implemented fig-Forth on many processors in
15510: 1979. Robert Selzer and Bill Ragsdale developed the original
15511: implementation of fig-Forth for the 6502 based on microForth.
15512: 
15513: The principal architect of microForth was Dean Sanderson. microForth was
15514: FORTH, Inc.'s first off-the-shelf product. It was developed in 1976 for
15515: the 1802, and subsequently implemented on the 8080, the 6800 and the
15516: Z80.
15517: 
15518: All earlier Forth systems were custom-made, usually by Charles Moore,
15519: who discovered (as he puts it) Forth during the late 60s. The first full
15520: Forth existed in 1971.
15521: 
15522: A part of the information in this section comes from
15523: @cite{@uref{http://www.forth.com/Content/History/History1.htm,The
15524: Evolution of Forth}} by Elizabeth D. Rather, Donald R. Colburn and
15525: Charles H. Moore, presented at the HOPL-II conference and preprinted
15526: in SIGPLAN Notices 28(3), 1993.  You can find more historical and
15527: genealogical information about Forth there.  For a more general (and
15528: graphical) Forth family tree look see
15529: @cite{@uref{http://www.complang.tuwien.ac.at/forth/family-tree/},
15530: Forth Family Tree and Timeline}.
15531: 
15532: @c ------------------------------------------------------------------
15533: @node Forth-related information, Licenses, Origin, Top
15534: @appendix Other Forth-related information
15535: @cindex Forth-related information
15536: 
15537: @c anton: I threw most of this stuff out, because it can be found through
15538: @c the FAQ and the FAQ is more likely to be up-to-date.
15539: 
15540: @cindex comp.lang.forth
15541: @cindex frequently asked questions
15542: There is an active news group (comp.lang.forth) discussing Forth
15543: (including Gforth) and Forth-related issues. Its
15544: @uref{http://www.complang.tuwien.ac.at/forth/faq/faq-general-2.html,FAQs}
15545: (frequently asked questions and their answers) contains a lot of
15546: information on Forth.  You should read it before posting to
15547: comp.lang.forth.
15548: 
15549: The ANS Forth standard is most usable in its
15550: @uref{http://www.taygeta.com/forth/dpans.html, HTML form}.
15551: 
15552: @c ---------------------------------------------------
15553: @node  Licenses, Word Index, Forth-related information, Top
15554: @appendix Licenses
15555: 
15556: @menu
15557: * GNU Free Documentation License::  License for copying this manual.
15558: * Copying::                         GPL (for copying this software).
15559: @end menu
15560: 
15561: @include fdl.texi
15562: 
15563: @include gpl.texi
15564: 
15565: 
15566: 
15567: @c ------------------------------------------------------------------
15568: @node Word Index, Concept Index, Licenses, Top
15569: @unnumbered Word Index
15570: 
15571: This index is a list of Forth words that have ``glossary'' entries
15572: within this manual. Each word is listed with its stack effect and
15573: wordset.
15574: 
15575: @printindex fn
15576: 
15577: @c anton: the name index seems superfluous given the word and concept indices.
15578: 
15579: @c @node Name Index, Concept Index, Word Index, Top
15580: @c @unnumbered Name Index
15581: 
15582: @c This index is a list of Forth words that have ``glossary'' entries
15583: @c within this manual.
15584: 
15585: @c @printindex ky
15586: 
15587: @c -------------------------------------------------------
15588: @node Concept Index,  , Word Index, Top
15589: @unnumbered Concept and Word Index
15590: 
15591: Not all entries listed in this index are present verbatim in the
15592: text. This index also duplicates, in abbreviated form, all of the words
15593: listed in the Word Index (only the names are listed for the words here).
15594: 
15595: @printindex cp
15596: 
15597: @bye
15598: 
15599: 
15600: 

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