File:  [gforth] / gforth / doc / gforth.ds
Revision 1.158: download - view: text, annotated - select for diffs
Sun May 7 05:46:47 2006 UTC (17 years, 10 months ago) by anton
Branches: MAIN
CVS tags: HEAD
documentation changes

    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: C Interface
  404: 
  405: * Calling C Functions::         
  406: * Declaring C Functions::       
  407: * Callbacks::                   
  408: * Low-Level C Interface Words::  
  409: 
  410: Assembler and Code Words
  411: 
  412: * Code and ;code::              
  413: * Common Assembler::            Assembler Syntax
  414: * Common Disassembler::         
  415: * 386 Assembler::               Deviations and special cases
  416: * Alpha Assembler::             Deviations and special cases
  417: * MIPS assembler::              Deviations and special cases
  418: * Other assemblers::            How to write them
  419: 
  420: Tools
  421: 
  422: * ANS Report::                  Report the words used, sorted by wordset.
  423: * Stack depth changes::         Where does this stack item come from?
  424: 
  425: ANS conformance
  426: 
  427: * The Core Words::              
  428: * The optional Block word set::  
  429: * The optional Double Number word set::  
  430: * The optional Exception word set::  
  431: * The optional Facility word set::  
  432: * The optional File-Access word set::  
  433: * The optional Floating-Point word set::  
  434: * The optional Locals word set::  
  435: * The optional Memory-Allocation word set::  
  436: * The optional Programming-Tools word set::  
  437: * The optional Search-Order word set::  
  438: 
  439: The Core Words
  440: 
  441: * core-idef::                   Implementation Defined Options                   
  442: * core-ambcond::                Ambiguous Conditions                
  443: * core-other::                  Other System Documentation                  
  444: 
  445: The optional Block word set
  446: 
  447: * block-idef::                  Implementation Defined Options
  448: * block-ambcond::               Ambiguous Conditions               
  449: * block-other::                 Other System Documentation                 
  450: 
  451: The optional Double Number word set
  452: 
  453: * double-ambcond::              Ambiguous Conditions              
  454: 
  455: The optional Exception word set
  456: 
  457: * exception-idef::              Implementation Defined Options              
  458: 
  459: The optional Facility word set
  460: 
  461: * facility-idef::               Implementation Defined Options               
  462: * facility-ambcond::            Ambiguous Conditions            
  463: 
  464: The optional File-Access word set
  465: 
  466: * file-idef::                   Implementation Defined Options
  467: * file-ambcond::                Ambiguous Conditions                
  468: 
  469: The optional Floating-Point word set
  470: 
  471: * floating-idef::               Implementation Defined Options
  472: * floating-ambcond::            Ambiguous Conditions            
  473: 
  474: The optional Locals word set
  475: 
  476: * locals-idef::                 Implementation Defined Options                 
  477: * locals-ambcond::              Ambiguous Conditions              
  478: 
  479: The optional Memory-Allocation word set
  480: 
  481: * memory-idef::                 Implementation Defined Options                 
  482: 
  483: The optional Programming-Tools word set
  484: 
  485: * programming-idef::            Implementation Defined Options            
  486: * programming-ambcond::         Ambiguous Conditions         
  487: 
  488: The optional Search-Order word set
  489: 
  490: * search-idef::                 Implementation Defined Options                 
  491: * search-ambcond::              Ambiguous Conditions              
  492: 
  493: Emacs and Gforth
  494: 
  495: * Installing gforth.el::        Making Emacs aware of Forth.
  496: * Emacs Tags::                  Viewing the source of a word in Emacs.
  497: * Hilighting::                  Making Forth code look prettier.
  498: * Auto-Indentation::            Customizing auto-indentation.
  499: * Blocks Files::                Reading and writing blocks files.
  500: 
  501: Image Files
  502: 
  503: * Image Licensing Issues::      Distribution terms for images.
  504: * Image File Background::       Why have image files?
  505: * Non-Relocatable Image Files::  don't always work.
  506: * Data-Relocatable Image Files::  are better.
  507: * Fully Relocatable Image Files::  better yet.
  508: * Stack and Dictionary Sizes::  Setting the default sizes for an image.
  509: * Running Image Files::         @code{gforth -i @i{file}} or @i{file}.
  510: * Modifying the Startup Sequence::  and turnkey applications.
  511: 
  512: Fully Relocatable Image Files
  513: 
  514: * gforthmi::                    The normal way
  515: * cross.fs::                    The hard way
  516: 
  517: Engine
  518: 
  519: * Portability::                 
  520: * Threading::                   
  521: * Primitives::                  
  522: * Performance::                 
  523: 
  524: Threading
  525: 
  526: * Scheduling::                  
  527: * Direct or Indirect Threaded?::  
  528: * Dynamic Superinstructions::   
  529: * DOES>::                       
  530: 
  531: Primitives
  532: 
  533: * Automatic Generation::        
  534: * TOS Optimization::            
  535: * Produced code::               
  536: 
  537: Cross Compiler
  538: 
  539: * Using the Cross Compiler::    
  540: * How the Cross Compiler Works::  
  541: 
  542: Licenses
  543: 
  544: * GNU Free Documentation License::  License for copying this manual.
  545: * Copying::                         GPL (for copying this software).
  546: 
  547: @end detailmenu
  548: @end menu
  549: 
  550: @c ----------------------------------------------------------
  551: @iftex
  552: @unnumbered Preface
  553: @cindex Preface
  554: This manual documents Gforth. Some introductory material is provided for
  555: readers who are unfamiliar with Forth or who are migrating to Gforth
  556: from other Forth compilers. However, this manual is primarily a
  557: reference manual.
  558: @end iftex
  559: 
  560: @comment TODO much more blurb here.
  561: 
  562: @c ******************************************************************
  563: @node Goals, Gforth Environment, Top, Top
  564: @comment node-name,     next,           previous, up
  565: @chapter Goals of Gforth
  566: @cindex goals of the Gforth project
  567: The goal of the Gforth Project is to develop a standard model for
  568: ANS Forth. This can be split into several subgoals:
  569: 
  570: @itemize @bullet
  571: @item
  572: Gforth should conform to the ANS Forth Standard.
  573: @item
  574: It should be a model, i.e. it should define all the
  575: implementation-dependent things.
  576: @item
  577: It should become standard, i.e. widely accepted and used. This goal
  578: is the most difficult one.
  579: @end itemize
  580: 
  581: To achieve these goals Gforth should be
  582: @itemize @bullet
  583: @item
  584: Similar to previous models (fig-Forth, F83)
  585: @item
  586: Powerful. It should provide for all the things that are considered
  587: necessary today and even some that are not yet considered necessary.
  588: @item
  589: Efficient. It should not get the reputation of being exceptionally
  590: slow.
  591: @item
  592: Free.
  593: @item
  594: Available on many machines/easy to port.
  595: @end itemize
  596: 
  597: Have we achieved these goals? Gforth conforms to the ANS Forth
  598: standard. It may be considered a model, but we have not yet documented
  599: which parts of the model are stable and which parts we are likely to
  600: change. It certainly has not yet become a de facto standard, but it
  601: appears to be quite popular. It has some similarities to and some
  602: differences from previous models. It has some powerful features, but not
  603: yet everything that we envisioned. We certainly have achieved our
  604: execution speed goals (@pxref{Performance})@footnote{However, in 1998
  605: the bar was raised when the major commercial Forth vendors switched to
  606: native code compilers.}.  It is free and available on many machines.
  607: 
  608: @c ******************************************************************
  609: @node Gforth Environment, Tutorial, Goals, Top
  610: @chapter Gforth Environment
  611: @cindex Gforth environment
  612: 
  613: Note: ultimately, the Gforth man page will be auto-generated from the
  614: material in this chapter.
  615: 
  616: @menu
  617: * Invoking Gforth::             Getting in
  618: * Leaving Gforth::              Getting out
  619: * Command-line editing::        
  620: * Environment variables::       that affect how Gforth starts up
  621: * Gforth Files::                What gets installed and where
  622: * Gforth in pipes::             
  623: * Startup speed::               When 35ms is not fast enough ...
  624: @end menu
  625: 
  626: For related information about the creation of images see @ref{Image Files}.
  627: 
  628: @comment ----------------------------------------------
  629: @node Invoking Gforth, Leaving Gforth, Gforth Environment, Gforth Environment
  630: @section Invoking Gforth
  631: @cindex invoking Gforth
  632: @cindex running Gforth
  633: @cindex command-line options
  634: @cindex options on the command line
  635: @cindex flags on the command line
  636: 
  637: Gforth is made up of two parts; an executable ``engine'' (named
  638: @command{gforth} or @command{gforth-fast}) and an image file. To start it, you
  639: will usually just say @code{gforth} -- this automatically loads the
  640: default image file @file{gforth.fi}. In many other cases the default
  641: Gforth image will be invoked like this:
  642: @example
  643: gforth [file | -e forth-code] ...
  644: @end example
  645: @noindent
  646: This interprets the contents of the files and the Forth code in the order they
  647: are given.
  648: 
  649: In addition to the @command{gforth} engine, there is also an engine
  650: called @command{gforth-fast}, which is faster, but gives less
  651: informative error messages (@pxref{Error messages}) and may catch some
  652: stack underflows later or not at all.  You should use it for debugged,
  653: performance-critical programs.
  654: 
  655: Moreover, there is an engine called @command{gforth-itc}, which is
  656: useful in some backwards-compatibility situations (@pxref{Direct or
  657: Indirect Threaded?}).
  658: 
  659: In general, the command line looks like this:
  660: 
  661: @example
  662: gforth[-fast] [engine options] [image options]
  663: @end example
  664: 
  665: The engine options must come before the rest of the command
  666: line. They are:
  667: 
  668: @table @code
  669: @cindex -i, command-line option
  670: @cindex --image-file, command-line option
  671: @item --image-file @i{file}
  672: @itemx -i @i{file}
  673: Loads the Forth image @i{file} instead of the default
  674: @file{gforth.fi} (@pxref{Image Files}).
  675: 
  676: @cindex --appl-image, command-line option
  677: @item --appl-image @i{file}
  678: Loads the image @i{file} and leaves all further command-line arguments
  679: to the image (instead of processing them as engine options).  This is
  680: useful for building executable application images on Unix, built with
  681: @code{gforthmi --application ...}.
  682: 
  683: @cindex --path, command-line option
  684: @cindex -p, command-line option
  685: @item --path @i{path}
  686: @itemx -p @i{path}
  687: Uses @i{path} for searching the image file and Forth source code files
  688: instead of the default in the environment variable @code{GFORTHPATH} or
  689: the path specified at installation time (e.g.,
  690: @file{/usr/local/share/gforth/0.2.0:.}). A path is given as a list of
  691: directories, separated by @samp{:} (on Unix) or @samp{;} (on other OSs).
  692: 
  693: @cindex --dictionary-size, command-line option
  694: @cindex -m, command-line option
  695: @cindex @i{size} parameters for command-line options
  696: @cindex size of the dictionary and the stacks
  697: @item --dictionary-size @i{size}
  698: @itemx -m @i{size}
  699: Allocate @i{size} space for the Forth dictionary space instead of
  700: using the default specified in the image (typically 256K). The
  701: @i{size} specification for this and subsequent options consists of
  702: an integer and a unit (e.g.,
  703: @code{4M}). The unit can be one of @code{b} (bytes), @code{e} (element
  704: size, in this case Cells), @code{k} (kilobytes), @code{M} (Megabytes),
  705: @code{G} (Gigabytes), and @code{T} (Terabytes). If no unit is specified,
  706: @code{e} is used.
  707: 
  708: @cindex --data-stack-size, command-line option
  709: @cindex -d, command-line option
  710: @item --data-stack-size @i{size}
  711: @itemx -d @i{size}
  712: Allocate @i{size} space for the data stack instead of using the
  713: default specified in the image (typically 16K).
  714: 
  715: @cindex --return-stack-size, command-line option
  716: @cindex -r, command-line option
  717: @item --return-stack-size @i{size}
  718: @itemx -r @i{size}
  719: Allocate @i{size} space for the return stack instead of using the
  720: default specified in the image (typically 15K).
  721: 
  722: @cindex --fp-stack-size, command-line option
  723: @cindex -f, command-line option
  724: @item --fp-stack-size @i{size}
  725: @itemx -f @i{size}
  726: Allocate @i{size} space for the floating point stack instead of
  727: using the default specified in the image (typically 15.5K). In this case
  728: the unit specifier @code{e} refers to floating point numbers.
  729: 
  730: @cindex --locals-stack-size, command-line option
  731: @cindex -l, command-line option
  732: @item --locals-stack-size @i{size}
  733: @itemx -l @i{size}
  734: Allocate @i{size} space for the locals stack instead of using the
  735: default specified in the image (typically 14.5K).
  736: 
  737: @cindex -h, command-line option
  738: @cindex --help, command-line option
  739: @item --help
  740: @itemx -h
  741: Print a message about the command-line options
  742: 
  743: @cindex -v, command-line option
  744: @cindex --version, command-line option
  745: @item --version
  746: @itemx -v
  747: Print version and exit
  748: 
  749: @cindex --debug, command-line option
  750: @item --debug
  751: Print some information useful for debugging on startup.
  752: 
  753: @cindex --offset-image, command-line option
  754: @item --offset-image
  755: Start the dictionary at a slightly different position than would be used
  756: otherwise (useful for creating data-relocatable images,
  757: @pxref{Data-Relocatable Image Files}).
  758: 
  759: @cindex --no-offset-im, command-line option
  760: @item --no-offset-im
  761: Start the dictionary at the normal position.
  762: 
  763: @cindex --clear-dictionary, command-line option
  764: @item --clear-dictionary
  765: Initialize all bytes in the dictionary to 0 before loading the image
  766: (@pxref{Data-Relocatable Image Files}).
  767: 
  768: @cindex --die-on-signal, command-line-option
  769: @item --die-on-signal
  770: Normally Gforth handles most signals (e.g., the user interrupt SIGINT,
  771: or the segmentation violation SIGSEGV) by translating it into a Forth
  772: @code{THROW}. With this option, Gforth exits if it receives such a
  773: signal. This option is useful when the engine and/or the image might be
  774: severely broken (such that it causes another signal before recovering
  775: from the first); this option avoids endless loops in such cases.
  776: 
  777: @cindex --no-dynamic, command-line option
  778: @cindex --dynamic, command-line option
  779: @item --no-dynamic
  780: @item --dynamic
  781: Disable or enable dynamic superinstructions with replication
  782: (@pxref{Dynamic Superinstructions}).
  783: 
  784: @cindex --no-super, command-line option
  785: @item --no-super
  786: Disable dynamic superinstructions, use just dynamic replication; this is
  787: useful if you want to patch threaded code (@pxref{Dynamic
  788: Superinstructions}).
  789: 
  790: @cindex --ss-number, command-line option
  791: @item --ss-number=@var{N}
  792: Use only the first @var{N} static superinstructions compiled into the
  793: engine (default: use them all; note that only @code{gforth-fast} has
  794: any).  This option is useful for measuring the performance impact of
  795: static superinstructions.
  796: 
  797: @cindex --ss-min-..., command-line options
  798: @item --ss-min-codesize
  799: @item --ss-min-ls
  800: @item --ss-min-lsu
  801: @item --ss-min-nexts
  802: Use specified metric for determining the cost of a primitive or static
  803: superinstruction for static superinstruction selection.  @code{Codesize}
  804: is the native code size of the primive or static superinstruction,
  805: @code{ls} is the number of loads and stores, @code{lsu} is the number of
  806: loads, stores, and updates, and @code{nexts} is the number of dispatches
  807: (not taking dynamic superinstructions into account), i.e. every
  808: primitive or static superinstruction has cost 1. Default:
  809: @code{codesize} if you use dynamic code generation, otherwise
  810: @code{nexts}.
  811: 
  812: @cindex --ss-greedy, command-line option
  813: @item --ss-greedy
  814: This option is useful for measuring the performance impact of static
  815: superinstructions.  By default, an optimal shortest-path algorithm is
  816: used for selecting static superinstructions.  With @option{--ss-greedy}
  817: this algorithm is modified to assume that anything after the static
  818: superinstruction currently under consideration is not combined into
  819: static superinstructions.  With @option{--ss-min-nexts} this produces
  820: the same result as a greedy algorithm that always selects the longest
  821: superinstruction available at the moment.  E.g., if there are
  822: superinstructions AB and BCD, then for the sequence A B C D the optimal
  823: algorithm will select A BCD and the greedy algorithm will select AB C D.
  824: 
  825: @cindex --print-metrics, command-line option
  826: @item --print-metrics
  827: Prints some metrics used during static superinstruction selection:
  828: @code{code size} is the actual size of the dynamically generated code.
  829: @code{Metric codesize} is the sum of the codesize metrics as seen by
  830: static superinstruction selection; there is a difference from @code{code
  831: size}, because not all primitives and static superinstructions are
  832: compiled into dynamically generated code, and because of markers.  The
  833: other metrics correspond to the @option{ss-min-...} options.  This
  834: option is useful for evaluating the effects of the @option{--ss-...}
  835: options.
  836: 
  837: @end table
  838: 
  839: @cindex loading files at startup
  840: @cindex executing code on startup
  841: @cindex batch processing with Gforth
  842: As explained above, the image-specific command-line arguments for the
  843: default image @file{gforth.fi} consist of a sequence of filenames and
  844: @code{-e @var{forth-code}} options that are interpreted in the sequence
  845: in which they are given. The @code{-e @var{forth-code}} or
  846: @code{--evaluate @var{forth-code}} option evaluates the Forth code. This
  847: option takes only one argument; if you want to evaluate more Forth
  848: words, you have to quote them or use @code{-e} several times. To exit
  849: after processing the command line (instead of entering interactive mode)
  850: append @code{-e bye} to the command line.  You can also process the
  851: command-line arguments with a Forth program (@pxref{OS command line
  852: arguments}).
  853: 
  854: @cindex versions, invoking other versions of Gforth
  855: If you have several versions of Gforth installed, @code{gforth} will
  856: invoke the version that was installed last. @code{gforth-@i{version}}
  857: invokes a specific version. If your environment contains the variable
  858: @code{GFORTHPATH}, you may want to override it by using the
  859: @code{--path} option.
  860: 
  861: Not yet implemented:
  862: On startup the system first executes the system initialization file
  863: (unless the option @code{--no-init-file} is given; note that the system
  864: resulting from using this option may not be ANS Forth conformant). Then
  865: the user initialization file @file{.gforth.fs} is executed, unless the
  866: option @code{--no-rc} is given; this file is searched for in @file{.},
  867: then in @file{~}, then in the normal path (see above).
  868: 
  869: 
  870: 
  871: @comment ----------------------------------------------
  872: @node Leaving Gforth, Command-line editing, Invoking Gforth, Gforth Environment
  873: @section Leaving Gforth
  874: @cindex Gforth - leaving
  875: @cindex leaving Gforth
  876: 
  877: You can leave Gforth by typing @code{bye} or @kbd{Ctrl-d} (at the start
  878: of a line) or (if you invoked Gforth with the @code{--die-on-signal}
  879: option) @kbd{Ctrl-c}. When you leave Gforth, all of your definitions and
  880: data are discarded.  For ways of saving the state of the system before
  881: leaving Gforth see @ref{Image Files}.
  882: 
  883: doc-bye
  884: 
  885: 
  886: @comment ----------------------------------------------
  887: @node Command-line editing, Environment variables, Leaving Gforth, Gforth Environment
  888: @section Command-line editing
  889: @cindex command-line editing
  890: 
  891: Gforth maintains a history file that records every line that you type to
  892: the text interpreter. This file is preserved between sessions, and is
  893: used to provide a command-line recall facility; if you type @kbd{Ctrl-P}
  894: repeatedly you can recall successively older commands from this (or
  895: previous) session(s). The full list of command-line editing facilities is:
  896: 
  897: @itemize @bullet
  898: @item
  899: @kbd{Ctrl-p} (``previous'') (or up-arrow) to recall successively older
  900: commands from the history buffer.
  901: @item
  902: @kbd{Ctrl-n} (``next'') (or down-arrow) to recall successively newer commands
  903: from the history buffer.
  904: @item
  905: @kbd{Ctrl-f} (or right-arrow) to move the cursor right, non-destructively.
  906: @item
  907: @kbd{Ctrl-b} (or left-arrow) to move the cursor left, non-destructively.
  908: @item
  909: @kbd{Ctrl-h} (backspace) to delete the character to the left of the cursor,
  910: closing up the line.
  911: @item
  912: @kbd{Ctrl-k} to delete (``kill'') from the cursor to the end of the line.
  913: @item
  914: @kbd{Ctrl-a} to move the cursor to the start of the line.
  915: @item
  916: @kbd{Ctrl-e} to move the cursor to the end of the line.
  917: @item
  918: @key{RET} (@kbd{Ctrl-m}) or @key{LFD} (@kbd{Ctrl-j}) to submit the current
  919: line.
  920: @item
  921: @key{TAB} to step through all possible full-word completions of the word
  922: currently being typed.
  923: @item
  924: @kbd{Ctrl-d} on an empty line line to terminate Gforth (gracefully,
  925: using @code{bye}). 
  926: @item
  927: @kbd{Ctrl-x} (or @code{Ctrl-d} on a non-empty line) to delete the
  928: character under the cursor.
  929: @end itemize
  930: 
  931: When editing, displayable characters are inserted to the left of the
  932: cursor position; the line is always in ``insert'' (as opposed to
  933: ``overstrike'') mode.
  934: 
  935: @cindex history file
  936: @cindex @file{.gforth-history}
  937: On Unix systems, the history file is @file{~/.gforth-history} by
  938: default@footnote{i.e. it is stored in the user's home directory.}. You
  939: can find out the name and location of your history file using:
  940: 
  941: @example 
  942: history-file type \ Unix-class systems
  943: 
  944: history-file type \ Other systems
  945: history-dir  type
  946: @end example
  947: 
  948: If you enter long definitions by hand, you can use a text editor to
  949: paste them out of the history file into a Forth source file for reuse at
  950: a later time.
  951: 
  952: Gforth never trims the size of the history file, so you should do this
  953: periodically, if necessary.
  954: 
  955: @comment this is all defined in history.fs
  956: @comment NAC TODO the ctrl-D behaviour can either do a bye or a beep.. how is that option
  957: @comment chosen?
  958: 
  959: 
  960: @comment ----------------------------------------------
  961: @node Environment variables, Gforth Files, Command-line editing, Gforth Environment
  962: @section Environment variables
  963: @cindex environment variables
  964: 
  965: Gforth uses these environment variables:
  966: 
  967: @itemize @bullet
  968: @item
  969: @cindex @code{GFORTHHIST} -- environment variable
  970: @code{GFORTHHIST} -- (Unix systems only) specifies the directory in which to
  971: open/create the history file, @file{.gforth-history}. Default:
  972: @code{$HOME}.
  973: 
  974: @item
  975: @cindex @code{GFORTHPATH} -- environment variable
  976: @code{GFORTHPATH} -- specifies the path used when searching for the gforth image file and
  977: for Forth source-code files.
  978: 
  979: @item
  980: @cindex @code{LANG} -- environment variable
  981: @code{LANG} -- see @code{LC_CTYPE}
  982: 
  983: @item
  984: @cindex @code{LC_ALL} -- environment variable
  985: @code{LC_ALL} -- see @code{LC_CTYPE}
  986: 
  987: @item
  988: @cindex @code{LC_CTYPE} -- environment variable
  989: @code{LC_CTYPE} -- If this variable contains ``UTF-8'' on Gforth
  990: startup, Gforth uses the UTF-8 encoding for strings internally and
  991: expects its input and produces its output in UTF-8 encoding, otherwise
  992: the encoding is 8bit (see @pxref{Xchars and Unicode}).  If this
  993: environment variable is unset, Gforth looks in @code{LC_ALL}, and if
  994: that is unset, in @code{LANG}.
  995: 
  996: @item
  997: @cindex @code{GFORTHSYSTEMPREFIX} -- environment variable
  998: 
  999: @code{GFORTHSYSTEMPREFIX} -- specifies what to prepend to the argument
 1000: of @code{system} before passing it to C's @code{system()}.  Default:
 1001: @code{"./$COMSPEC /c "} on Windows, @code{""} on other OSs.  The prefix
 1002: and the command are directly concatenated, so if a space between them is
 1003: necessary, append it to the prefix.
 1004: 
 1005: @item
 1006: @cindex @code{GFORTH} -- environment variable
 1007: @code{GFORTH} -- used by @file{gforthmi}, @xref{gforthmi}.
 1008: 
 1009: @item
 1010: @cindex @code{GFORTHD} -- environment variable
 1011: @code{GFORTHD} -- used by @file{gforthmi}, @xref{gforthmi}.
 1012: 
 1013: @item
 1014: @cindex @code{TMP}, @code{TEMP} - environment variable
 1015: @code{TMP}, @code{TEMP} - (non-Unix systems only) used as a potential
 1016: location for the history file.
 1017: @end itemize
 1018: 
 1019: @comment also POSIXELY_CORRECT LINES COLUMNS HOME but no interest in
 1020: @comment mentioning these.
 1021: 
 1022: All the Gforth environment variables default to sensible values if they
 1023: are not set.
 1024: 
 1025: 
 1026: @comment ----------------------------------------------
 1027: @node Gforth Files, Gforth in pipes, Environment variables, Gforth Environment
 1028: @section Gforth files
 1029: @cindex Gforth files
 1030: 
 1031: When you install Gforth on a Unix system, it installs files in these
 1032: locations by default:
 1033: 
 1034: @itemize @bullet
 1035: @item
 1036: @file{/usr/local/bin/gforth}
 1037: @item
 1038: @file{/usr/local/bin/gforthmi}
 1039: @item
 1040: @file{/usr/local/man/man1/gforth.1} - man page.
 1041: @item
 1042: @file{/usr/local/info} - the Info version of this manual.
 1043: @item
 1044: @file{/usr/local/lib/gforth/<version>/...} - Gforth @file{.fi} files.
 1045: @item
 1046: @file{/usr/local/share/gforth/<version>/TAGS} - Emacs TAGS file.
 1047: @item
 1048: @file{/usr/local/share/gforth/<version>/...} - Gforth source files.
 1049: @item
 1050: @file{.../emacs/site-lisp/gforth.el} - Emacs gforth mode.
 1051: @end itemize
 1052: 
 1053: You can select different places for installation by using
 1054: @code{configure} options (listed with @code{configure --help}).
 1055: 
 1056: @comment ----------------------------------------------
 1057: @node Gforth in pipes, Startup speed, Gforth Files, Gforth Environment
 1058: @section Gforth in pipes
 1059: @cindex pipes, Gforth as part of
 1060: 
 1061: Gforth can be used in pipes created elsewhere (described here).  It can
 1062: also create pipes on its own (@pxref{Pipes}).
 1063: 
 1064: @cindex input from pipes
 1065: If you pipe into Gforth, your program should read with @code{read-file}
 1066: or @code{read-line} from @code{stdin} (@pxref{General files}).
 1067: @code{Key} does not recognize the end of input.  Words like
 1068: @code{accept} echo the input and are therefore usually not useful for
 1069: reading from a pipe.  You have to invoke the Forth program with an OS
 1070: command-line option, as you have no chance to use the Forth command line
 1071: (the text interpreter would try to interpret the pipe input).
 1072: 
 1073: @cindex output in pipes
 1074: You can output to a pipe with @code{type}, @code{emit}, @code{cr} etc.
 1075: 
 1076: @cindex silent exiting from Gforth
 1077: When you write to a pipe that has been closed at the other end, Gforth
 1078: receives a SIGPIPE signal (``pipe broken'').  Gforth translates this
 1079: into the exception @code{broken-pipe-error}.  If your application does
 1080: not catch that exception, the system catches it and exits, usually
 1081: silently (unless you were working on the Forth command line; then it
 1082: prints an error message and exits).  This is usually the desired
 1083: behaviour.
 1084: 
 1085: If you do not like this behaviour, you have to catch the exception
 1086: yourself, and react to it.
 1087: 
 1088: Here's an example of an invocation of Gforth that is usable in a pipe:
 1089: 
 1090: @example
 1091: gforth -e ": foo begin pad dup 10 stdin read-file throw dup while \
 1092:  type repeat ; foo bye"
 1093: @end example
 1094: 
 1095: This example just copies the input verbatim to the output.  A very
 1096: simple pipe containing this example looks like this:
 1097: 
 1098: @example
 1099: cat startup.fs |
 1100: gforth -e ": foo begin pad dup 80 stdin read-file throw dup while \
 1101:  type repeat ; foo bye"|
 1102: head
 1103: @end example
 1104: 
 1105: @cindex stderr and pipes
 1106: Pipes involving Gforth's @code{stderr} output do not work.
 1107: 
 1108: @comment ----------------------------------------------
 1109: @node Startup speed,  , Gforth in pipes, Gforth Environment
 1110: @section Startup speed
 1111: @cindex Startup speed
 1112: @cindex speed, startup
 1113: 
 1114: If Gforth is used for CGI scripts or in shell scripts, its startup
 1115: speed may become a problem.  On a 300MHz 21064a under Linux-2.2.13 with
 1116: glibc-2.0.7, @code{gforth -e bye} takes about 24.6ms user and 11.3ms
 1117: system time.
 1118: 
 1119: If startup speed is a problem, you may consider the following ways to
 1120: improve it; or you may consider ways to reduce the number of startups
 1121: (for example, by using Fast-CGI).
 1122: 
 1123: An easy step that influences Gforth startup speed is the use of the
 1124: @option{--no-dynamic} option; this decreases image loading speed, but
 1125: increases compile-time and run-time.
 1126: 
 1127: Another step to improve startup speed is to statically link Gforth, by
 1128: building it with @code{XLDFLAGS=-static}.  This requires more memory for
 1129: the code and will therefore slow down the first invocation, but
 1130: subsequent invocations avoid the dynamic linking overhead.  Another
 1131: disadvantage is that Gforth won't profit from library upgrades.  As a
 1132: result, @code{gforth-static -e bye} takes about 17.1ms user and
 1133: 8.2ms system time.
 1134: 
 1135: The next step to improve startup speed is to use a non-relocatable image
 1136: (@pxref{Non-Relocatable Image Files}).  You can create this image with
 1137: @code{gforth -e "savesystem gforthnr.fi bye"} and later use it with
 1138: @code{gforth -i gforthnr.fi ...}.  This avoids the relocation overhead
 1139: and a part of the copy-on-write overhead.  The disadvantage is that the
 1140: non-relocatable image does not work if the OS gives Gforth a different
 1141: address for the dictionary, for whatever reason; so you better provide a
 1142: fallback on a relocatable image.  @code{gforth-static -i gforthnr.fi -e
 1143: bye} takes about 15.3ms user and 7.5ms system time.
 1144: 
 1145: The final step is to disable dictionary hashing in Gforth.  Gforth
 1146: builds the hash table on startup, which takes much of the startup
 1147: overhead. You can do this by commenting out the @code{include hash.fs}
 1148: in @file{startup.fs} and everything that requires @file{hash.fs} (at the
 1149: moment @file{table.fs} and @file{ekey.fs}) and then doing @code{make}.
 1150: The disadvantages are that functionality like @code{table} and
 1151: @code{ekey} is missing and that text interpretation (e.g., compiling)
 1152: now takes much longer. So, you should only use this method if there is
 1153: no significant text interpretation to perform (the script should be
 1154: compiled into the image, amongst other things).  @code{gforth-static -i
 1155: gforthnrnh.fi -e bye} takes about 2.1ms user and 6.1ms system time.
 1156: 
 1157: @c ******************************************************************
 1158: @node Tutorial, Introduction, Gforth Environment, Top
 1159: @chapter Forth Tutorial
 1160: @cindex Tutorial
 1161: @cindex Forth Tutorial
 1162: 
 1163: @c Topics from nac's Introduction that could be mentioned:
 1164: @c press <ret> after each line
 1165: @c Prompt
 1166: @c numbers vs. words in dictionary on text interpretation
 1167: @c what happens on redefinition
 1168: @c parsing words (in particular, defining words)
 1169: 
 1170: The difference of this chapter from the Introduction
 1171: (@pxref{Introduction}) is that this tutorial is more fast-paced, should
 1172: be used while sitting in front of a computer, and covers much more
 1173: material, but does not explain how the Forth system works.
 1174: 
 1175: This tutorial can be used with any ANS-compliant Forth; any
 1176: Gforth-specific features are marked as such and you can skip them if you
 1177: work with another Forth.  This tutorial does not explain all features of
 1178: Forth, just enough to get you started and give you some ideas about the
 1179: facilities available in Forth.  Read the rest of the manual and the
 1180: standard when you are through this.
 1181: 
 1182: The intended way to use this tutorial is that you work through it while
 1183: sitting in front of the console, take a look at the examples and predict
 1184: what they will do, then try them out; if the outcome is not as expected,
 1185: find out why (e.g., by trying out variations of the example), so you
 1186: understand what's going on.  There are also some assignments that you
 1187: should solve.
 1188: 
 1189: This tutorial assumes that you have programmed before and know what,
 1190: e.g., a loop is.
 1191: 
 1192: @c !! explain compat library
 1193: 
 1194: @menu
 1195: * Starting Gforth Tutorial::    
 1196: * Syntax Tutorial::             
 1197: * Crash Course Tutorial::       
 1198: * Stack Tutorial::              
 1199: * Arithmetics Tutorial::        
 1200: * Stack Manipulation Tutorial::  
 1201: * Using files for Forth code Tutorial::  
 1202: * Comments Tutorial::           
 1203: * Colon Definitions Tutorial::  
 1204: * Decompilation Tutorial::      
 1205: * Stack-Effect Comments Tutorial::  
 1206: * Types Tutorial::              
 1207: * Factoring Tutorial::          
 1208: * Designing the stack effect Tutorial::  
 1209: * Local Variables Tutorial::    
 1210: * Conditional execution Tutorial::  
 1211: * Flags and Comparisons Tutorial::  
 1212: * General Loops Tutorial::      
 1213: * Counted loops Tutorial::      
 1214: * Recursion Tutorial::          
 1215: * Leaving definitions or loops Tutorial::  
 1216: * Return Stack Tutorial::       
 1217: * Memory Tutorial::             
 1218: * Characters and Strings Tutorial::  
 1219: * Alignment Tutorial::          
 1220: * Files Tutorial::              
 1221: * Interpretation and Compilation Semantics and Immediacy Tutorial::  
 1222: * Execution Tokens Tutorial::   
 1223: * Exceptions Tutorial::         
 1224: * Defining Words Tutorial::     
 1225: * Arrays and Records Tutorial::  
 1226: * POSTPONE Tutorial::           
 1227: * Literal Tutorial::            
 1228: * Advanced macros Tutorial::    
 1229: * Compilation Tokens Tutorial::  
 1230: * Wordlists and Search Order Tutorial::  
 1231: @end menu
 1232: 
 1233: @node Starting Gforth Tutorial, Syntax Tutorial, Tutorial, Tutorial
 1234: @section Starting Gforth
 1235: @cindex starting Gforth tutorial
 1236: You can start Gforth by typing its name:
 1237: 
 1238: @example
 1239: gforth
 1240: @end example
 1241: 
 1242: That puts you into interactive mode; you can leave Gforth by typing
 1243: @code{bye}.  While in Gforth, you can edit the command line and access
 1244: the command line history with cursor keys, similar to bash.
 1245: 
 1246: 
 1247: @node Syntax Tutorial, Crash Course Tutorial, Starting Gforth Tutorial, Tutorial
 1248: @section Syntax
 1249: @cindex syntax tutorial
 1250: 
 1251: A @dfn{word} is a sequence of arbitrary characters (expcept white
 1252: space).  Words are separated by white space.  E.g., each of the
 1253: following lines contains exactly one word:
 1254: 
 1255: @example
 1256: word
 1257: !@@#$%^&*()
 1258: 1234567890
 1259: 5!a
 1260: @end example
 1261: 
 1262: A frequent beginner's error is to leave away necessary white space,
 1263: resulting in an error like @samp{Undefined word}; so if you see such an
 1264: error, check if you have put spaces wherever necessary.
 1265: 
 1266: @example
 1267: ." hello, world" \ correct
 1268: ."hello, world"  \ gives an "Undefined word" error
 1269: @end example
 1270: 
 1271: Gforth and most other Forth systems ignore differences in case (they are
 1272: case-insensitive), i.e., @samp{word} is the same as @samp{Word}.  If
 1273: your system is case-sensitive, you may have to type all the examples
 1274: given here in upper case.
 1275: 
 1276: 
 1277: @node Crash Course Tutorial, Stack Tutorial, Syntax Tutorial, Tutorial
 1278: @section Crash Course
 1279: 
 1280: Type
 1281: 
 1282: @example
 1283: 0 0 !
 1284: here execute
 1285: ' catch >body 20 erase abort
 1286: ' (quit) >body 20 erase
 1287: @end example
 1288: 
 1289: The last two examples are guaranteed to destroy parts of Gforth (and
 1290: most other systems), so you better leave Gforth afterwards (if it has
 1291: not finished by itself).  On some systems you may have to kill gforth
 1292: from outside (e.g., in Unix with @code{kill}).
 1293: 
 1294: Now that you know how to produce crashes (and that there's not much to
 1295: them), let's learn how to produce meaningful programs.
 1296: 
 1297: 
 1298: @node Stack Tutorial, Arithmetics Tutorial, Crash Course Tutorial, Tutorial
 1299: @section Stack
 1300: @cindex stack tutorial
 1301: 
 1302: The most obvious feature of Forth is the stack.  When you type in a
 1303: number, it is pushed on the stack.  You can display the content of the
 1304: stack with @code{.s}.
 1305: 
 1306: @example
 1307: 1 2 .s
 1308: 3 .s
 1309: @end example
 1310: 
 1311: @code{.s} displays the top-of-stack to the right, i.e., the numbers
 1312: appear in @code{.s} output as they appeared in the input.
 1313: 
 1314: You can print the top of stack element with @code{.}.
 1315: 
 1316: @example
 1317: 1 2 3 . . .
 1318: @end example
 1319: 
 1320: In general, words consume their stack arguments (@code{.s} is an
 1321: exception).
 1322: 
 1323: @quotation Assignment
 1324: What does the stack contain after @code{5 6 7 .}?
 1325: @end quotation
 1326: 
 1327: 
 1328: @node Arithmetics Tutorial, Stack Manipulation Tutorial, Stack Tutorial, Tutorial
 1329: @section Arithmetics
 1330: @cindex arithmetics tutorial
 1331: 
 1332: The words @code{+}, @code{-}, @code{*}, @code{/}, and @code{mod} always
 1333: operate on the top two stack items:
 1334: 
 1335: @example
 1336: 2 2 .s
 1337: + .s
 1338: .
 1339: 2 1 - .
 1340: 7 3 mod .
 1341: @end example
 1342: 
 1343: The operands of @code{-}, @code{/}, and @code{mod} are in the same order
 1344: as in the corresponding infix expression (this is generally the case in
 1345: Forth).
 1346: 
 1347: Parentheses are superfluous (and not available), because the order of
 1348: the words unambiguously determines the order of evaluation and the
 1349: operands:
 1350: 
 1351: @example
 1352: 3 4 + 5 * .
 1353: 3 4 5 * + .
 1354: @end example
 1355: 
 1356: @quotation Assignment
 1357: What are the infix expressions corresponding to the Forth code above?
 1358: Write @code{6-7*8+9} in Forth notation@footnote{This notation is also
 1359: known as Postfix or RPN (Reverse Polish Notation).}.
 1360: @end quotation
 1361: 
 1362: To change the sign, use @code{negate}:
 1363: 
 1364: @example
 1365: 2 negate .
 1366: @end example
 1367: 
 1368: @quotation Assignment
 1369: Convert -(-3)*4-5 to Forth.
 1370: @end quotation
 1371: 
 1372: @code{/mod} performs both @code{/} and @code{mod}.
 1373: 
 1374: @example
 1375: 7 3 /mod . .
 1376: @end example
 1377: 
 1378: Reference: @ref{Arithmetic}.
 1379: 
 1380: 
 1381: @node Stack Manipulation Tutorial, Using files for Forth code Tutorial, Arithmetics Tutorial, Tutorial
 1382: @section Stack Manipulation
 1383: @cindex stack manipulation tutorial
 1384: 
 1385: Stack manipulation words rearrange the data on the stack.
 1386: 
 1387: @example
 1388: 1 .s drop .s
 1389: 1 .s dup .s drop drop .s
 1390: 1 2 .s over .s drop drop drop
 1391: 1 2 .s swap .s drop drop
 1392: 1 2 3 .s rot .s drop drop drop
 1393: @end example
 1394: 
 1395: These are the most important stack manipulation words.  There are also
 1396: variants that manipulate twice as many stack items:
 1397: 
 1398: @example
 1399: 1 2 3 4 .s 2swap .s 2drop 2drop
 1400: @end example
 1401: 
 1402: Two more stack manipulation words are:
 1403: 
 1404: @example
 1405: 1 2 .s nip .s drop
 1406: 1 2 .s tuck .s 2drop drop
 1407: @end example
 1408: 
 1409: @quotation Assignment
 1410: Replace @code{nip} and @code{tuck} with combinations of other stack
 1411: manipulation words.
 1412: 
 1413: @example
 1414: Given:          How do you get:
 1415: 1 2 3           3 2 1           
 1416: 1 2 3           1 2 3 2                 
 1417: 1 2 3           1 2 3 3                 
 1418: 1 2 3           1 3 3           
 1419: 1 2 3           2 1 3           
 1420: 1 2 3 4         4 3 2 1         
 1421: 1 2 3           1 2 3 1 2 3             
 1422: 1 2 3 4         1 2 3 4 1 2             
 1423: 1 2 3
 1424: 1 2 3           1 2 3 4                 
 1425: 1 2 3           1 3             
 1426: @end example
 1427: @end quotation
 1428: 
 1429: @example
 1430: 5 dup * .
 1431: @end example
 1432: 
 1433: @quotation Assignment
 1434: Write 17^3 and 17^4 in Forth, without writing @code{17} more than once.
 1435: Write a piece of Forth code that expects two numbers on the stack
 1436: (@var{a} and @var{b}, with @var{b} on top) and computes
 1437: @code{(a-b)(a+1)}.
 1438: @end quotation
 1439: 
 1440: Reference: @ref{Stack Manipulation}.
 1441: 
 1442: 
 1443: @node Using files for Forth code Tutorial, Comments Tutorial, Stack Manipulation Tutorial, Tutorial
 1444: @section Using files for Forth code
 1445: @cindex loading Forth code, tutorial
 1446: @cindex files containing Forth code, tutorial
 1447: 
 1448: While working at the Forth command line is convenient for one-line
 1449: examples and short one-off code, you probably want to store your source
 1450: code in files for convenient editing and persistence.  You can use your
 1451: favourite editor (Gforth includes Emacs support, @pxref{Emacs and
 1452: Gforth}) to create @var{file.fs} and use
 1453: 
 1454: @example
 1455: s" @var{file.fs}" included
 1456: @end example
 1457: 
 1458: to load it into your Forth system.  The file name extension I use for
 1459: Forth files is @samp{.fs}.
 1460: 
 1461: You can easily start Gforth with some files loaded like this:
 1462: 
 1463: @example
 1464: gforth @var{file1.fs} @var{file2.fs}
 1465: @end example
 1466: 
 1467: If an error occurs during loading these files, Gforth terminates,
 1468: whereas an error during @code{INCLUDED} within Gforth usually gives you
 1469: a Gforth command line.  Starting the Forth system every time gives you a
 1470: clean start every time, without interference from the results of earlier
 1471: tries.
 1472: 
 1473: I often put all the tests in a file, then load the code and run the
 1474: tests with
 1475: 
 1476: @example
 1477: gforth @var{code.fs} @var{tests.fs} -e bye
 1478: @end example
 1479: 
 1480: (often by performing this command with @kbd{C-x C-e} in Emacs).  The
 1481: @code{-e bye} ensures that Gforth terminates afterwards so that I can
 1482: restart this command without ado.
 1483: 
 1484: The advantage of this approach is that the tests can be repeated easily
 1485: every time the program ist changed, making it easy to catch bugs
 1486: introduced by the change.
 1487: 
 1488: Reference: @ref{Forth source files}.
 1489: 
 1490: 
 1491: @node Comments Tutorial, Colon Definitions Tutorial, Using files for Forth code Tutorial, Tutorial
 1492: @section Comments
 1493: @cindex comments tutorial
 1494: 
 1495: @example
 1496: \ That's a comment; it ends at the end of the line
 1497: ( Another comment; it ends here: )  .s
 1498: @end example
 1499: 
 1500: @code{\} and @code{(} are ordinary Forth words and therefore have to be
 1501: separated with white space from the following text.
 1502: 
 1503: @example
 1504: \This gives an "Undefined word" error
 1505: @end example
 1506: 
 1507: The first @code{)} ends a comment started with @code{(}, so you cannot
 1508: nest @code{(}-comments; and you cannot comment out text containing a
 1509: @code{)} with @code{( ... )}@footnote{therefore it's a good idea to
 1510: avoid @code{)} in word names.}.
 1511: 
 1512: I use @code{\}-comments for descriptive text and for commenting out code
 1513: of one or more line; I use @code{(}-comments for describing the stack
 1514: effect, the stack contents, or for commenting out sub-line pieces of
 1515: code.
 1516: 
 1517: The Emacs mode @file{gforth.el} (@pxref{Emacs and Gforth}) supports
 1518: these uses by commenting out a region with @kbd{C-x \}, uncommenting a
 1519: region with @kbd{C-u C-x \}, and filling a @code{\}-commented region
 1520: with @kbd{M-q}.
 1521: 
 1522: Reference: @ref{Comments}.
 1523: 
 1524: 
 1525: @node Colon Definitions Tutorial, Decompilation Tutorial, Comments Tutorial, Tutorial
 1526: @section Colon Definitions
 1527: @cindex colon definitions, tutorial
 1528: @cindex definitions, tutorial
 1529: @cindex procedures, tutorial
 1530: @cindex functions, tutorial
 1531: 
 1532: are similar to procedures and functions in other programming languages.
 1533: 
 1534: @example
 1535: : squared ( n -- n^2 )
 1536:    dup * ;
 1537: 5 squared .
 1538: 7 squared .
 1539: @end example
 1540: 
 1541: @code{:} starts the colon definition; its name is @code{squared}.  The
 1542: following comment describes its stack effect.  The words @code{dup *}
 1543: are not executed, but compiled into the definition.  @code{;} ends the
 1544: colon definition.
 1545: 
 1546: The newly-defined word can be used like any other word, including using
 1547: it in other definitions:
 1548: 
 1549: @example
 1550: : cubed ( n -- n^3 )
 1551:    dup squared * ;
 1552: -5 cubed .
 1553: : fourth-power ( n -- n^4 )
 1554:    squared squared ;
 1555: 3 fourth-power .
 1556: @end example
 1557: 
 1558: @quotation Assignment
 1559: Write colon definitions for @code{nip}, @code{tuck}, @code{negate}, and
 1560: @code{/mod} in terms of other Forth words, and check if they work (hint:
 1561: test your tests on the originals first).  Don't let the
 1562: @samp{redefined}-Messages spook you, they are just warnings.
 1563: @end quotation
 1564: 
 1565: Reference: @ref{Colon Definitions}.
 1566: 
 1567: 
 1568: @node Decompilation Tutorial, Stack-Effect Comments Tutorial, Colon Definitions Tutorial, Tutorial
 1569: @section Decompilation
 1570: @cindex decompilation tutorial
 1571: @cindex see tutorial
 1572: 
 1573: You can decompile colon definitions with @code{see}:
 1574: 
 1575: @example
 1576: see squared
 1577: see cubed
 1578: @end example
 1579: 
 1580: In Gforth @code{see} shows you a reconstruction of the source code from
 1581: the executable code.  Informations that were present in the source, but
 1582: not in the executable code, are lost (e.g., comments).
 1583: 
 1584: You can also decompile the predefined words:
 1585: 
 1586: @example
 1587: see .
 1588: see +
 1589: @end example
 1590: 
 1591: 
 1592: @node Stack-Effect Comments Tutorial, Types Tutorial, Decompilation Tutorial, Tutorial
 1593: @section Stack-Effect Comments
 1594: @cindex stack-effect comments, tutorial
 1595: @cindex --, tutorial
 1596: By convention the comment after the name of a definition describes the
 1597: stack effect: The part in from of the @samp{--} describes the state of
 1598: the stack before the execution of the definition, i.e., the parameters
 1599: that are passed into the colon definition; the part behind the @samp{--}
 1600: is the state of the stack after the execution of the definition, i.e.,
 1601: the results of the definition.  The stack comment only shows the top
 1602: stack items that the definition accesses and/or changes.
 1603: 
 1604: You should put a correct stack effect on every definition, even if it is
 1605: just @code{( -- )}.  You should also add some descriptive comment to
 1606: more complicated words (I usually do this in the lines following
 1607: @code{:}).  If you don't do this, your code becomes unreadable (because
 1608: you have to work through every definition before you can understand
 1609: any).
 1610: 
 1611: @quotation Assignment
 1612: The stack effect of @code{swap} can be written like this: @code{x1 x2 --
 1613: x2 x1}.  Describe the stack effect of @code{-}, @code{drop}, @code{dup},
 1614: @code{over}, @code{rot}, @code{nip}, and @code{tuck}.  Hint: When you
 1615: are done, you can compare your stack effects to those in this manual
 1616: (@pxref{Word Index}).
 1617: @end quotation
 1618: 
 1619: Sometimes programmers put comments at various places in colon
 1620: definitions that describe the contents of the stack at that place (stack
 1621: comments); i.e., they are like the first part of a stack-effect
 1622: comment. E.g.,
 1623: 
 1624: @example
 1625: : cubed ( n -- n^3 )
 1626:    dup squared  ( n n^2 ) * ;
 1627: @end example
 1628: 
 1629: In this case the stack comment is pretty superfluous, because the word
 1630: is simple enough.  If you think it would be a good idea to add such a
 1631: comment to increase readability, you should also consider factoring the
 1632: word into several simpler words (@pxref{Factoring Tutorial,,
 1633: Factoring}), which typically eliminates the need for the stack comment;
 1634: however, if you decide not to refactor it, then having such a comment is
 1635: better than not having it.
 1636: 
 1637: The names of the stack items in stack-effect and stack comments in the
 1638: standard, in this manual, and in many programs specify the type through
 1639: a type prefix, similar to Fortran and Hungarian notation.  The most
 1640: frequent prefixes are:
 1641: 
 1642: @table @code
 1643: @item n
 1644: signed integer
 1645: @item u
 1646: unsigned integer
 1647: @item c
 1648: character
 1649: @item f
 1650: Boolean flags, i.e. @code{false} or @code{true}.
 1651: @item a-addr,a-
 1652: Cell-aligned address
 1653: @item c-addr,c-
 1654: Char-aligned address (note that a Char may have two bytes in Windows NT)
 1655: @item xt
 1656: Execution token, same size as Cell
 1657: @item w,x
 1658: Cell, can contain an integer or an address.  It usually takes 32, 64 or
 1659: 16 bits (depending on your platform and Forth system). A cell is more
 1660: commonly known as machine word, but the term @emph{word} already means
 1661: something different in Forth.
 1662: @item d
 1663: signed double-cell integer
 1664: @item ud
 1665: unsigned double-cell integer
 1666: @item r
 1667: Float (on the FP stack)
 1668: @end table
 1669: 
 1670: You can find a more complete list in @ref{Notation}.
 1671: 
 1672: @quotation Assignment
 1673: Write stack-effect comments for all definitions you have written up to
 1674: now.
 1675: @end quotation
 1676: 
 1677: 
 1678: @node Types Tutorial, Factoring Tutorial, Stack-Effect Comments Tutorial, Tutorial
 1679: @section Types
 1680: @cindex types tutorial
 1681: 
 1682: In Forth the names of the operations are not overloaded; so similar
 1683: operations on different types need different names; e.g., @code{+} adds
 1684: integers, and you have to use @code{f+} to add floating-point numbers.
 1685: The following prefixes are often used for related operations on
 1686: different types:
 1687: 
 1688: @table @code
 1689: @item (none)
 1690: signed integer
 1691: @item u
 1692: unsigned integer
 1693: @item c
 1694: character
 1695: @item d
 1696: signed double-cell integer
 1697: @item ud, du
 1698: unsigned double-cell integer
 1699: @item 2
 1700: two cells (not-necessarily double-cell numbers)
 1701: @item m, um
 1702: mixed single-cell and double-cell operations
 1703: @item f
 1704: floating-point (note that in stack comments @samp{f} represents flags,
 1705: and @samp{r} represents FP numbers).
 1706: @end table
 1707: 
 1708: If there are no differences between the signed and the unsigned variant
 1709: (e.g., for @code{+}), there is only the prefix-less variant.
 1710: 
 1711: Forth does not perform type checking, neither at compile time, nor at
 1712: run time.  If you use the wrong oeration, the data are interpreted
 1713: incorrectly:
 1714: 
 1715: @example
 1716: -1 u.
 1717: @end example
 1718: 
 1719: If you have only experience with type-checked languages until now, and
 1720: have heard how important type-checking is, don't panic!  In my
 1721: experience (and that of other Forthers), type errors in Forth code are
 1722: usually easy to find (once you get used to it), the increased vigilance
 1723: of the programmer tends to catch some harder errors in addition to most
 1724: type errors, and you never have to work around the type system, so in
 1725: most situations the lack of type-checking seems to be a win (projects to
 1726: add type checking to Forth have not caught on).
 1727: 
 1728: 
 1729: @node Factoring Tutorial, Designing the stack effect Tutorial, Types Tutorial, Tutorial
 1730: @section Factoring
 1731: @cindex factoring tutorial
 1732: 
 1733: If you try to write longer definitions, you will soon find it hard to
 1734: keep track of the stack contents.  Therefore, good Forth programmers
 1735: tend to write only short definitions (e.g., three lines).  The art of
 1736: finding meaningful short definitions is known as factoring (as in
 1737: factoring polynomials).
 1738: 
 1739: Well-factored programs offer additional advantages: smaller, more
 1740: general words, are easier to test and debug and can be reused more and
 1741: better than larger, specialized words.
 1742: 
 1743: So, if you run into difficulties with stack management, when writing
 1744: code, try to define meaningful factors for the word, and define the word
 1745: in terms of those.  Even if a factor contains only two words, it is
 1746: often helpful.
 1747: 
 1748: Good factoring is not easy, and it takes some practice to get the knack
 1749: for it; but even experienced Forth programmers often don't find the
 1750: right solution right away, but only when rewriting the program.  So, if
 1751: you don't come up with a good solution immediately, keep trying, don't
 1752: despair.
 1753: 
 1754: @c example !!
 1755: 
 1756: 
 1757: @node Designing the stack effect Tutorial, Local Variables Tutorial, Factoring Tutorial, Tutorial
 1758: @section Designing the stack effect
 1759: @cindex Stack effect design, tutorial
 1760: @cindex design of stack effects, tutorial
 1761: 
 1762: In other languages you can use an arbitrary order of parameters for a
 1763: function; and since there is only one result, you don't have to deal with
 1764: the order of results, either.
 1765: 
 1766: In Forth (and other stack-based languages, e.g., PostScript) the
 1767: parameter and result order of a definition is important and should be
 1768: designed well.  The general guideline is to design the stack effect such
 1769: that the word is simple to use in most cases, even if that complicates
 1770: the implementation of the word.  Some concrete rules are:
 1771: 
 1772: @itemize @bullet
 1773: 
 1774: @item
 1775: Words consume all of their parameters (e.g., @code{.}).
 1776: 
 1777: @item
 1778: If there is a convention on the order of parameters (e.g., from
 1779: mathematics or another programming language), stick with it (e.g.,
 1780: @code{-}).
 1781: 
 1782: @item
 1783: If one parameter usually requires only a short computation (e.g., it is
 1784: a constant), pass it on the top of the stack.  Conversely, parameters
 1785: that usually require a long sequence of code to compute should be passed
 1786: as the bottom (i.e., first) parameter.  This makes the code easier to
 1787: read, because reader does not need to keep track of the bottom item
 1788: through a long sequence of code (or, alternatively, through stack
 1789: manipulations). E.g., @code{!} (store, @pxref{Memory}) expects the
 1790: address on top of the stack because it is usually simpler to compute
 1791: than the stored value (often the address is just a variable).
 1792: 
 1793: @item
 1794: Similarly, results that are usually consumed quickly should be returned
 1795: on the top of stack, whereas a result that is often used in long
 1796: computations should be passed as bottom result.  E.g., the file words
 1797: like @code{open-file} return the error code on the top of stack, because
 1798: it is usually consumed quickly by @code{throw}; moreover, the error code
 1799: has to be checked before doing anything with the other results.
 1800: 
 1801: @end itemize
 1802: 
 1803: These rules are just general guidelines, don't lose sight of the overall
 1804: goal to make the words easy to use.  E.g., if the convention rule
 1805: conflicts with the computation-length rule, you might decide in favour
 1806: of the convention if the word will be used rarely, and in favour of the
 1807: computation-length rule if the word will be used frequently (because
 1808: with frequent use the cost of breaking the computation-length rule would
 1809: be quite high, and frequent use makes it easier to remember an
 1810: unconventional order).
 1811: 
 1812: @c example !! structure package
 1813: 
 1814: 
 1815: @node Local Variables Tutorial, Conditional execution Tutorial, Designing the stack effect Tutorial, Tutorial
 1816: @section Local Variables
 1817: @cindex local variables, tutorial
 1818: 
 1819: You can define local variables (@emph{locals}) in a colon definition:
 1820: 
 1821: @example
 1822: : swap @{ a b -- b a @}
 1823:   b a ;
 1824: 1 2 swap .s 2drop
 1825: @end example
 1826: 
 1827: (If your Forth system does not support this syntax, include
 1828: @file{compat/anslocals.fs} first).
 1829: 
 1830: In this example @code{@{ a b -- b a @}} is the locals definition; it
 1831: takes two cells from the stack, puts the top of stack in @code{b} and
 1832: the next stack element in @code{a}.  @code{--} starts a comment ending
 1833: with @code{@}}.  After the locals definition, using the name of the
 1834: local will push its value on the stack.  You can leave the comment
 1835: part (@code{-- b a}) away:
 1836: 
 1837: @example
 1838: : swap ( x1 x2 -- x2 x1 )
 1839:   @{ a b @} b a ;
 1840: @end example
 1841: 
 1842: In Gforth you can have several locals definitions, anywhere in a colon
 1843: definition; in contrast, in a standard program you can have only one
 1844: locals definition per colon definition, and that locals definition must
 1845: be outside any controll structure.
 1846: 
 1847: With locals you can write slightly longer definitions without running
 1848: into stack trouble.  However, I recommend trying to write colon
 1849: definitions without locals for exercise purposes to help you gain the
 1850: essential factoring skills.
 1851: 
 1852: @quotation Assignment
 1853: Rewrite your definitions until now with locals
 1854: @end quotation
 1855: 
 1856: Reference: @ref{Locals}.
 1857: 
 1858: 
 1859: @node Conditional execution Tutorial, Flags and Comparisons Tutorial, Local Variables Tutorial, Tutorial
 1860: @section Conditional execution
 1861: @cindex conditionals, tutorial
 1862: @cindex if, tutorial
 1863: 
 1864: In Forth you can use control structures only inside colon definitions.
 1865: An @code{if}-structure looks like this:
 1866: 
 1867: @example
 1868: : abs ( n1 -- +n2 )
 1869:     dup 0 < if
 1870:         negate
 1871:     endif ;
 1872: 5 abs .
 1873: -5 abs .
 1874: @end example
 1875: 
 1876: @code{if} takes a flag from the stack.  If the flag is non-zero (true),
 1877: the following code is performed, otherwise execution continues after the
 1878: @code{endif} (or @code{else}).  @code{<} compares the top two stack
 1879: elements and prioduces a flag:
 1880: 
 1881: @example
 1882: 1 2 < .
 1883: 2 1 < .
 1884: 1 1 < .
 1885: @end example
 1886: 
 1887: Actually the standard name for @code{endif} is @code{then}.  This
 1888: tutorial presents the examples using @code{endif}, because this is often
 1889: less confusing for people familiar with other programming languages
 1890: where @code{then} has a different meaning.  If your system does not have
 1891: @code{endif}, define it with
 1892: 
 1893: @example
 1894: : endif postpone then ; immediate
 1895: @end example
 1896: 
 1897: You can optionally use an @code{else}-part:
 1898: 
 1899: @example
 1900: : min ( n1 n2 -- n )
 1901:   2dup < if
 1902:     drop
 1903:   else
 1904:     nip
 1905:   endif ;
 1906: 2 3 min .
 1907: 3 2 min .
 1908: @end example
 1909: 
 1910: @quotation Assignment
 1911: Write @code{min} without @code{else}-part (hint: what's the definition
 1912: of @code{nip}?).
 1913: @end quotation
 1914: 
 1915: Reference: @ref{Selection}.
 1916: 
 1917: 
 1918: @node Flags and Comparisons Tutorial, General Loops Tutorial, Conditional execution Tutorial, Tutorial
 1919: @section Flags and Comparisons
 1920: @cindex flags tutorial
 1921: @cindex comparison tutorial
 1922: 
 1923: In a false-flag all bits are clear (0 when interpreted as integer).  In
 1924: a canonical true-flag all bits are set (-1 as a twos-complement signed
 1925: integer); in many contexts (e.g., @code{if}) any non-zero value is
 1926: treated as true flag.
 1927: 
 1928: @example
 1929: false .
 1930: true .
 1931: true hex u. decimal
 1932: @end example
 1933: 
 1934: Comparison words produce canonical flags:
 1935: 
 1936: @example
 1937: 1 1 = .
 1938: 1 0= .
 1939: 0 1 < .
 1940: 0 0 < .
 1941: -1 1 u< . \ type error, u< interprets -1 as large unsigned number
 1942: -1 1 < .
 1943: @end example
 1944: 
 1945: Gforth supports all combinations of the prefixes @code{0 u d d0 du f f0}
 1946: (or none) and the comparisons @code{= <> < > <= >=}.  Only a part of
 1947: these combinations are standard (for details see the standard,
 1948: @ref{Numeric comparison}, @ref{Floating Point} or @ref{Word Index}).
 1949: 
 1950: You can use @code{and or xor invert} can be used as operations on
 1951: canonical flags.  Actually they are bitwise operations:
 1952: 
 1953: @example
 1954: 1 2 and .
 1955: 1 2 or .
 1956: 1 3 xor .
 1957: 1 invert .
 1958: @end example
 1959: 
 1960: You can convert a zero/non-zero flag into a canonical flag with
 1961: @code{0<>} (and complement it on the way with @code{0=}).
 1962: 
 1963: @example
 1964: 1 0= .
 1965: 1 0<> .
 1966: @end example
 1967: 
 1968: You can use the all-bits-set feature of canonical flags and the bitwise
 1969: operation of the Boolean operations to avoid @code{if}s:
 1970: 
 1971: @example
 1972: : foo ( n1 -- n2 )
 1973:   0= if
 1974:     14
 1975:   else
 1976:     0
 1977:   endif ;
 1978: 0 foo .
 1979: 1 foo .
 1980: 
 1981: : foo ( n1 -- n2 )
 1982:   0= 14 and ;
 1983: 0 foo .
 1984: 1 foo .
 1985: @end example
 1986: 
 1987: @quotation Assignment
 1988: Write @code{min} without @code{if}.
 1989: @end quotation
 1990: 
 1991: For reference, see @ref{Boolean Flags}, @ref{Numeric comparison}, and
 1992: @ref{Bitwise operations}.
 1993: 
 1994: 
 1995: @node General Loops Tutorial, Counted loops Tutorial, Flags and Comparisons Tutorial, Tutorial
 1996: @section General Loops
 1997: @cindex loops, indefinite, tutorial
 1998: 
 1999: The endless loop is the most simple one:
 2000: 
 2001: @example
 2002: : endless ( -- )
 2003:   0 begin
 2004:     dup . 1+
 2005:   again ;
 2006: endless
 2007: @end example
 2008: 
 2009: Terminate this loop by pressing @kbd{Ctrl-C} (in Gforth).  @code{begin}
 2010: does nothing at run-time, @code{again} jumps back to @code{begin}.
 2011: 
 2012: A loop with one exit at any place looks like this:
 2013: 
 2014: @example
 2015: : log2 ( +n1 -- n2 )
 2016: \ logarithmus dualis of n1>0, rounded down to the next integer
 2017:   assert( dup 0> )
 2018:   2/ 0 begin
 2019:     over 0> while
 2020:       1+ swap 2/ swap
 2021:   repeat
 2022:   nip ;
 2023: 7 log2 .
 2024: 8 log2 .
 2025: @end example
 2026: 
 2027: At run-time @code{while} consumes a flag; if it is 0, execution
 2028: continues behind the @code{repeat}; if the flag is non-zero, execution
 2029: continues behind the @code{while}.  @code{Repeat} jumps back to
 2030: @code{begin}, just like @code{again}.
 2031: 
 2032: In Forth there are many combinations/abbreviations, like @code{1+}.
 2033: However, @code{2/} is not one of them; it shifts its argument right by
 2034: one bit (arithmetic shift right):
 2035: 
 2036: @example
 2037: -5 2 / .
 2038: -5 2/ .
 2039: @end example
 2040: 
 2041: @code{assert(} is no standard word, but you can get it on systems other
 2042: then Gforth by including @file{compat/assert.fs}.  You can see what it
 2043: does by trying
 2044: 
 2045: @example
 2046: 0 log2 .
 2047: @end example
 2048: 
 2049: Here's a loop with an exit at the end:
 2050: 
 2051: @example
 2052: : log2 ( +n1 -- n2 )
 2053: \ logarithmus dualis of n1>0, rounded down to the next integer
 2054:   assert( dup 0 > )
 2055:   -1 begin
 2056:     1+ swap 2/ swap
 2057:     over 0 <=
 2058:   until
 2059:   nip ;
 2060: @end example
 2061: 
 2062: @code{Until} consumes a flag; if it is non-zero, execution continues at
 2063: the @code{begin}, otherwise after the @code{until}.
 2064: 
 2065: @quotation Assignment
 2066: Write a definition for computing the greatest common divisor.
 2067: @end quotation
 2068: 
 2069: Reference: @ref{Simple Loops}.
 2070: 
 2071: 
 2072: @node Counted loops Tutorial, Recursion Tutorial, General Loops Tutorial, Tutorial
 2073: @section Counted loops
 2074: @cindex loops, counted, tutorial
 2075: 
 2076: @example
 2077: : ^ ( n1 u -- n )
 2078: \ n = the uth power of u1
 2079:   1 swap 0 u+do
 2080:     over *
 2081:   loop
 2082:   nip ;
 2083: 3 2 ^ .
 2084: 4 3 ^ .
 2085: @end example
 2086: 
 2087: @code{U+do} (from @file{compat/loops.fs}, if your Forth system doesn't
 2088: have it) takes two numbers of the stack @code{( u3 u4 -- )}, and then
 2089: performs the code between @code{u+do} and @code{loop} for @code{u3-u4}
 2090: times (or not at all, if @code{u3-u4<0}).
 2091: 
 2092: You can see the stack effect design rules at work in the stack effect of
 2093: the loop start words: Since the start value of the loop is more
 2094: frequently constant than the end value, the start value is passed on
 2095: the top-of-stack.
 2096: 
 2097: You can access the counter of a counted loop with @code{i}:
 2098: 
 2099: @example
 2100: : fac ( u -- u! )
 2101:   1 swap 1+ 1 u+do
 2102:     i *
 2103:   loop ;
 2104: 5 fac .
 2105: 7 fac .
 2106: @end example
 2107: 
 2108: There is also @code{+do}, which expects signed numbers (important for
 2109: deciding whether to enter the loop).
 2110: 
 2111: @quotation Assignment
 2112: Write a definition for computing the nth Fibonacci number.
 2113: @end quotation
 2114: 
 2115: You can also use increments other than 1:
 2116: 
 2117: @example
 2118: : up2 ( n1 n2 -- )
 2119:   +do
 2120:     i .
 2121:   2 +loop ;
 2122: 10 0 up2
 2123: 
 2124: : down2 ( n1 n2 -- )
 2125:   -do
 2126:     i .
 2127:   2 -loop ;
 2128: 0 10 down2
 2129: @end example
 2130: 
 2131: Reference: @ref{Counted Loops}.
 2132: 
 2133: 
 2134: @node Recursion Tutorial, Leaving definitions or loops Tutorial, Counted loops Tutorial, Tutorial
 2135: @section Recursion
 2136: @cindex recursion tutorial
 2137: 
 2138: Usually the name of a definition is not visible in the definition; but
 2139: earlier definitions are usually visible:
 2140: 
 2141: @example
 2142: 1 0 / . \ "Floating-point unidentified fault" in Gforth on most platforms
 2143: : / ( n1 n2 -- n )
 2144:   dup 0= if
 2145:     -10 throw \ report division by zero
 2146:   endif
 2147:   /           \ old version
 2148: ;
 2149: 1 0 /
 2150: @end example
 2151: 
 2152: For recursive definitions you can use @code{recursive} (non-standard) or
 2153: @code{recurse}:
 2154: 
 2155: @example
 2156: : fac1 ( n -- n! ) recursive
 2157:  dup 0> if
 2158:    dup 1- fac1 *
 2159:  else
 2160:    drop 1
 2161:  endif ;
 2162: 7 fac1 .
 2163: 
 2164: : fac2 ( n -- n! )
 2165:  dup 0> if
 2166:    dup 1- recurse *
 2167:  else
 2168:    drop 1
 2169:  endif ;
 2170: 8 fac2 .
 2171: @end example
 2172: 
 2173: @quotation Assignment
 2174: Write a recursive definition for computing the nth Fibonacci number.
 2175: @end quotation
 2176: 
 2177: Reference (including indirect recursion): @xref{Calls and returns}.
 2178: 
 2179: 
 2180: @node Leaving definitions or loops Tutorial, Return Stack Tutorial, Recursion Tutorial, Tutorial
 2181: @section Leaving definitions or loops
 2182: @cindex leaving definitions, tutorial
 2183: @cindex leaving loops, tutorial
 2184: 
 2185: @code{EXIT} exits the current definition right away.  For every counted
 2186: loop that is left in this way, an @code{UNLOOP} has to be performed
 2187: before the @code{EXIT}:
 2188: 
 2189: @c !! real examples
 2190: @example
 2191: : ...
 2192:  ... u+do
 2193:    ... if
 2194:      ... unloop exit
 2195:    endif
 2196:    ...
 2197:  loop
 2198:  ... ;
 2199: @end example
 2200: 
 2201: @code{LEAVE} leaves the innermost counted loop right away:
 2202: 
 2203: @example
 2204: : ...
 2205:  ... u+do
 2206:    ... if
 2207:      ... leave
 2208:    endif
 2209:    ...
 2210:  loop
 2211:  ... ;
 2212: @end example
 2213: 
 2214: @c !! example
 2215: 
 2216: Reference: @ref{Calls and returns}, @ref{Counted Loops}.
 2217: 
 2218: 
 2219: @node Return Stack Tutorial, Memory Tutorial, Leaving definitions or loops Tutorial, Tutorial
 2220: @section Return Stack
 2221: @cindex return stack tutorial
 2222: 
 2223: In addition to the data stack Forth also has a second stack, the return
 2224: stack; most Forth systems store the return addresses of procedure calls
 2225: there (thus its name).  Programmers can also use this stack:
 2226: 
 2227: @example
 2228: : foo ( n1 n2 -- )
 2229:  .s
 2230:  >r .s
 2231:  r@@ .
 2232:  >r .s
 2233:  r@@ .
 2234:  r> .
 2235:  r@@ .
 2236:  r> . ;
 2237: 1 2 foo
 2238: @end example
 2239: 
 2240: @code{>r} takes an element from the data stack and pushes it onto the
 2241: return stack; conversely, @code{r>} moves an elementm from the return to
 2242: the data stack; @code{r@@} pushes a copy of the top of the return stack
 2243: on the data stack.
 2244: 
 2245: Forth programmers usually use the return stack for storing data
 2246: temporarily, if using the data stack alone would be too complex, and
 2247: factoring and locals are not an option:
 2248: 
 2249: @example
 2250: : 2swap ( x1 x2 x3 x4 -- x3 x4 x1 x2 )
 2251:  rot >r rot r> ;
 2252: @end example
 2253: 
 2254: The return address of the definition and the loop control parameters of
 2255: counted loops usually reside on the return stack, so you have to take
 2256: all items, that you have pushed on the return stack in a colon
 2257: definition or counted loop, from the return stack before the definition
 2258: or loop ends.  You cannot access items that you pushed on the return
 2259: stack outside some definition or loop within the definition of loop.
 2260: 
 2261: If you miscount the return stack items, this usually ends in a crash:
 2262: 
 2263: @example
 2264: : crash ( n -- )
 2265:   >r ;
 2266: 5 crash
 2267: @end example
 2268: 
 2269: You cannot mix using locals and using the return stack (according to the
 2270: standard; Gforth has no problem).  However, they solve the same
 2271: problems, so this shouldn't be an issue.
 2272: 
 2273: @quotation Assignment
 2274: Can you rewrite any of the definitions you wrote until now in a better
 2275: way using the return stack?
 2276: @end quotation
 2277: 
 2278: Reference: @ref{Return stack}.
 2279: 
 2280: 
 2281: @node Memory Tutorial, Characters and Strings Tutorial, Return Stack Tutorial, Tutorial
 2282: @section Memory
 2283: @cindex memory access/allocation tutorial
 2284: 
 2285: You can create a global variable @code{v} with
 2286: 
 2287: @example
 2288: variable v ( -- addr )
 2289: @end example
 2290: 
 2291: @code{v} pushes the address of a cell in memory on the stack.  This cell
 2292: was reserved by @code{variable}.  You can use @code{!} (store) to store
 2293: values into this cell and @code{@@} (fetch) to load the value from the
 2294: stack into memory:
 2295: 
 2296: @example
 2297: v .
 2298: 5 v ! .s
 2299: v @@ .
 2300: @end example
 2301: 
 2302: You can see a raw dump of memory with @code{dump}:
 2303: 
 2304: @example
 2305: v 1 cells .s dump
 2306: @end example
 2307: 
 2308: @code{Cells ( n1 -- n2 )} gives you the number of bytes (or, more
 2309: generally, address units (aus)) that @code{n1 cells} occupy.  You can
 2310: also reserve more memory:
 2311: 
 2312: @example
 2313: create v2 20 cells allot
 2314: v2 20 cells dump
 2315: @end example
 2316: 
 2317: creates a word @code{v2} and reserves 20 uninitialized cells; the
 2318: address pushed by @code{v2} points to the start of these 20 cells.  You
 2319: can use address arithmetic to access these cells:
 2320: 
 2321: @example
 2322: 3 v2 5 cells + !
 2323: v2 20 cells dump
 2324: @end example
 2325: 
 2326: You can reserve and initialize memory with @code{,}:
 2327: 
 2328: @example
 2329: create v3
 2330:   5 , 4 , 3 , 2 , 1 ,
 2331: v3 @@ .
 2332: v3 cell+ @@ .
 2333: v3 2 cells + @@ .
 2334: v3 5 cells dump
 2335: @end example
 2336: 
 2337: @quotation Assignment
 2338: Write a definition @code{vsum ( addr u -- n )} that computes the sum of
 2339: @code{u} cells, with the first of these cells at @code{addr}, the next
 2340: one at @code{addr cell+} etc.
 2341: @end quotation
 2342: 
 2343: You can also reserve memory without creating a new word:
 2344: 
 2345: @example
 2346: here 10 cells allot .
 2347: here .
 2348: @end example
 2349: 
 2350: @code{Here} pushes the start address of the memory area.  You should
 2351: store it somewhere, or you will have a hard time finding the memory area
 2352: again.
 2353: 
 2354: @code{Allot} manages dictionary memory.  The dictionary memory contains
 2355: the system's data structures for words etc. on Gforth and most other
 2356: Forth systems.  It is managed like a stack: You can free the memory that
 2357: you have just @code{allot}ed with
 2358: 
 2359: @example
 2360: -10 cells allot
 2361: here .
 2362: @end example
 2363: 
 2364: Note that you cannot do this if you have created a new word in the
 2365: meantime (because then your @code{allot}ed memory is no longer on the
 2366: top of the dictionary ``stack'').
 2367: 
 2368: Alternatively, you can use @code{allocate} and @code{free} which allow
 2369: freeing memory in any order:
 2370: 
 2371: @example
 2372: 10 cells allocate throw .s
 2373: 20 cells allocate throw .s
 2374: swap
 2375: free throw
 2376: free throw
 2377: @end example
 2378: 
 2379: The @code{throw}s deal with errors (e.g., out of memory).
 2380: 
 2381: And there is also a
 2382: @uref{http://www.complang.tuwien.ac.at/forth/garbage-collection.zip,
 2383: garbage collector}, which eliminates the need to @code{free} memory
 2384: explicitly.
 2385: 
 2386: Reference: @ref{Memory}.
 2387: 
 2388: 
 2389: @node Characters and Strings Tutorial, Alignment Tutorial, Memory Tutorial, Tutorial
 2390: @section Characters and Strings
 2391: @cindex strings tutorial
 2392: @cindex characters tutorial
 2393: 
 2394: On the stack characters take up a cell, like numbers.  In memory they
 2395: have their own size (one 8-bit byte on most systems), and therefore
 2396: require their own words for memory access:
 2397: 
 2398: @example
 2399: create v4 
 2400:   104 c, 97 c, 108 c, 108 c, 111 c,
 2401: v4 4 chars + c@@ .
 2402: v4 5 chars dump
 2403: @end example
 2404: 
 2405: The preferred representation of strings on the stack is @code{addr
 2406: u-count}, where @code{addr} is the address of the first character and
 2407: @code{u-count} is the number of characters in the string.
 2408: 
 2409: @example
 2410: v4 5 type
 2411: @end example
 2412: 
 2413: You get a string constant with
 2414: 
 2415: @example
 2416: s" hello, world" .s
 2417: type
 2418: @end example
 2419: 
 2420: Make sure you have a space between @code{s"} and the string; @code{s"}
 2421: is a normal Forth word and must be delimited with white space (try what
 2422: happens when you remove the space).
 2423: 
 2424: However, this interpretive use of @code{s"} is quite restricted: the
 2425: string exists only until the next call of @code{s"} (some Forth systems
 2426: keep more than one of these strings, but usually they still have a
 2427: limited lifetime).
 2428: 
 2429: @example
 2430: s" hello," s" world" .s
 2431: type
 2432: type
 2433: @end example
 2434: 
 2435: You can also use @code{s"} in a definition, and the resulting
 2436: strings then live forever (well, for as long as the definition):
 2437: 
 2438: @example
 2439: : foo s" hello," s" world" ;
 2440: foo .s
 2441: type
 2442: type
 2443: @end example
 2444: 
 2445: @quotation Assignment
 2446: @code{Emit ( c -- )} types @code{c} as character (not a number).
 2447: Implement @code{type ( addr u -- )}.
 2448: @end quotation
 2449: 
 2450: Reference: @ref{Memory Blocks}.
 2451: 
 2452: 
 2453: @node Alignment Tutorial, Files Tutorial, Characters and Strings Tutorial, Tutorial
 2454: @section Alignment
 2455: @cindex alignment tutorial
 2456: @cindex memory alignment tutorial
 2457: 
 2458: On many processors cells have to be aligned in memory, if you want to
 2459: access them with @code{@@} and @code{!} (and even if the processor does
 2460: not require alignment, access to aligned cells is faster).
 2461: 
 2462: @code{Create} aligns @code{here} (i.e., the place where the next
 2463: allocation will occur, and that the @code{create}d word points to).
 2464: Likewise, the memory produced by @code{allocate} starts at an aligned
 2465: address.  Adding a number of @code{cells} to an aligned address produces
 2466: another aligned address.
 2467: 
 2468: However, address arithmetic involving @code{char+} and @code{chars} can
 2469: create an address that is not cell-aligned.  @code{Aligned ( addr --
 2470: a-addr )} produces the next aligned address:
 2471: 
 2472: @example
 2473: v3 char+ aligned .s @@ .
 2474: v3 char+ .s @@ .
 2475: @end example
 2476: 
 2477: Similarly, @code{align} advances @code{here} to the next aligned
 2478: address:
 2479: 
 2480: @example
 2481: create v5 97 c,
 2482: here .
 2483: align here .
 2484: 1000 ,
 2485: @end example
 2486: 
 2487: Note that you should use aligned addresses even if your processor does
 2488: not require them, if you want your program to be portable.
 2489: 
 2490: Reference: @ref{Address arithmetic}.
 2491: 
 2492: 
 2493: @node Files Tutorial, Interpretation and Compilation Semantics and Immediacy Tutorial, Alignment Tutorial, Tutorial
 2494: @section Files
 2495: @cindex files tutorial
 2496: 
 2497: This section gives a short introduction into how to use files inside
 2498: Forth. It's broken up into five easy steps:
 2499: 
 2500: @enumerate 1
 2501: @item Opened an ASCII text file for input
 2502: @item Opened a file for output
 2503: @item Read input file until string matched (or some other condition matched)
 2504: @item Wrote some lines from input ( modified or not) to output
 2505: @item Closed the files.
 2506: @end enumerate
 2507: 
 2508: Reference: @ref{General files}.
 2509: 
 2510: @subsection Open file for input
 2511: 
 2512: @example
 2513: s" foo.in"  r/o open-file throw Value fd-in
 2514: @end example
 2515: 
 2516: @subsection Create file for output
 2517: 
 2518: @example
 2519: s" foo.out" w/o create-file throw Value fd-out
 2520: @end example
 2521: 
 2522: The available file modes are r/o for read-only access, r/w for
 2523: read-write access, and w/o for write-only access. You could open both
 2524: files with r/w, too, if you like. All file words return error codes; for
 2525: most applications, it's best to pass there error codes with @code{throw}
 2526: to the outer error handler.
 2527: 
 2528: If you want words for opening and assigning, define them as follows:
 2529: 
 2530: @example
 2531: 0 Value fd-in
 2532: 0 Value fd-out
 2533: : open-input ( addr u -- )  r/o open-file throw to fd-in ;
 2534: : open-output ( addr u -- )  w/o create-file throw to fd-out ;
 2535: @end example
 2536: 
 2537: Usage example:
 2538: 
 2539: @example
 2540: s" foo.in" open-input
 2541: s" foo.out" open-output
 2542: @end example
 2543: 
 2544: @subsection Scan file for a particular line
 2545: 
 2546: @example
 2547: 256 Constant max-line
 2548: Create line-buffer  max-line 2 + allot
 2549: 
 2550: : scan-file ( addr u -- )
 2551:   begin
 2552:       line-buffer max-line fd-in read-line throw
 2553:   while
 2554:          >r 2dup line-buffer r> compare 0=
 2555:      until
 2556:   else
 2557:      drop
 2558:   then
 2559:   2drop ;
 2560: @end example
 2561: 
 2562: @code{read-line ( addr u1 fd -- u2 flag ior )} reads up to u1 bytes into
 2563: the buffer at addr, and returns the number of bytes read, a flag that is
 2564: false when the end of file is reached, and an error code.
 2565: 
 2566: @code{compare ( addr1 u1 addr2 u2 -- n )} compares two strings and
 2567: returns zero if both strings are equal. It returns a positive number if
 2568: the first string is lexically greater, a negative if the second string
 2569: is lexically greater.
 2570: 
 2571: We haven't seen this loop here; it has two exits. Since the @code{while}
 2572: exits with the number of bytes read on the stack, we have to clean up
 2573: that separately; that's after the @code{else}.
 2574: 
 2575: Usage example:
 2576: 
 2577: @example
 2578: s" The text I search is here" scan-file
 2579: @end example
 2580: 
 2581: @subsection Copy input to output
 2582: 
 2583: @example
 2584: : copy-file ( -- )
 2585:   begin
 2586:       line-buffer max-line fd-in read-line throw
 2587:   while
 2588:       line-buffer swap fd-out write-file throw
 2589:   repeat ;
 2590: @end example
 2591: 
 2592: @subsection Close files
 2593: 
 2594: @example
 2595: fd-in close-file throw
 2596: fd-out close-file throw
 2597: @end example
 2598: 
 2599: Likewise, you can put that into definitions, too:
 2600: 
 2601: @example
 2602: : close-input ( -- )  fd-in close-file throw ;
 2603: : close-output ( -- )  fd-out close-file throw ;
 2604: @end example
 2605: 
 2606: @quotation Assignment
 2607: How could you modify @code{copy-file} so that it copies until a second line is
 2608: matched? Can you write a program that extracts a section of a text file,
 2609: given the line that starts and the line that terminates that section?
 2610: @end quotation
 2611: 
 2612: @node Interpretation and Compilation Semantics and Immediacy Tutorial, Execution Tokens Tutorial, Files Tutorial, Tutorial
 2613: @section Interpretation and Compilation Semantics and Immediacy
 2614: @cindex semantics tutorial
 2615: @cindex interpretation semantics tutorial
 2616: @cindex compilation semantics tutorial
 2617: @cindex immediate, tutorial
 2618: 
 2619: When a word is compiled, it behaves differently from being interpreted.
 2620: E.g., consider @code{+}:
 2621: 
 2622: @example
 2623: 1 2 + .
 2624: : foo + ;
 2625: @end example
 2626: 
 2627: These two behaviours are known as compilation and interpretation
 2628: semantics.  For normal words (e.g., @code{+}), the compilation semantics
 2629: is to append the interpretation semantics to the currently defined word
 2630: (@code{foo} in the example above).  I.e., when @code{foo} is executed
 2631: later, the interpretation semantics of @code{+} (i.e., adding two
 2632: numbers) will be performed.
 2633: 
 2634: However, there are words with non-default compilation semantics, e.g.,
 2635: the control-flow words like @code{if}.  You can use @code{immediate} to
 2636: change the compilation semantics of the last defined word to be equal to
 2637: the interpretation semantics:
 2638: 
 2639: @example
 2640: : [FOO] ( -- )
 2641:  5 . ; immediate
 2642: 
 2643: [FOO]
 2644: : bar ( -- )
 2645:   [FOO] ;
 2646: bar
 2647: see bar
 2648: @end example
 2649: 
 2650: Two conventions to mark words with non-default compilation semnatics are
 2651: names with brackets (more frequently used) and to write them all in
 2652: upper case (less frequently used).
 2653: 
 2654: In Gforth (and many other systems) you can also remove the
 2655: interpretation semantics with @code{compile-only} (the compilation
 2656: semantics is derived from the original interpretation semantics):
 2657: 
 2658: @example
 2659: : flip ( -- )
 2660:  6 . ; compile-only \ but not immediate
 2661: flip
 2662: 
 2663: : flop ( -- )
 2664:  flip ;
 2665: flop
 2666: @end example
 2667: 
 2668: In this example the interpretation semantics of @code{flop} is equal to
 2669: the original interpretation semantics of @code{flip}.
 2670: 
 2671: The text interpreter has two states: in interpret state, it performs the
 2672: interpretation semantics of words it encounters; in compile state, it
 2673: performs the compilation semantics of these words.
 2674: 
 2675: Among other things, @code{:} switches into compile state, and @code{;}
 2676: switches back to interpret state.  They contain the factors @code{]}
 2677: (switch to compile state) and @code{[} (switch to interpret state), that
 2678: do nothing but switch the state.
 2679: 
 2680: @example
 2681: : xxx ( -- )
 2682:   [ 5 . ]
 2683: ;
 2684: 
 2685: xxx
 2686: see xxx
 2687: @end example
 2688: 
 2689: These brackets are also the source of the naming convention mentioned
 2690: above.
 2691: 
 2692: Reference: @ref{Interpretation and Compilation Semantics}.
 2693: 
 2694: 
 2695: @node Execution Tokens Tutorial, Exceptions Tutorial, Interpretation and Compilation Semantics and Immediacy Tutorial, Tutorial
 2696: @section Execution Tokens
 2697: @cindex execution tokens tutorial
 2698: @cindex XT tutorial
 2699: 
 2700: @code{' word} gives you the execution token (XT) of a word.  The XT is a
 2701: cell representing the interpretation semantics of a word.  You can
 2702: execute this semantics with @code{execute}:
 2703: 
 2704: @example
 2705: ' + .s
 2706: 1 2 rot execute .
 2707: @end example
 2708: 
 2709: The XT is similar to a function pointer in C.  However, parameter
 2710: passing through the stack makes it a little more flexible:
 2711: 
 2712: @example
 2713: : map-array ( ... addr u xt -- ... )
 2714: \ executes xt ( ... x -- ... ) for every element of the array starting
 2715: \ at addr and containing u elements
 2716:   @{ xt @}
 2717:   cells over + swap ?do
 2718:     i @@ xt execute
 2719:   1 cells +loop ;
 2720: 
 2721: create a 3 , 4 , 2 , -1 , 4 ,
 2722: a 5 ' . map-array .s
 2723: 0 a 5 ' + map-array .
 2724: s" max-n" environment? drop .s
 2725: a 5 ' min map-array .
 2726: @end example
 2727: 
 2728: You can use map-array with the XTs of words that consume one element
 2729: more than they produce.  In theory you can also use it with other XTs,
 2730: but the stack effect then depends on the size of the array, which is
 2731: hard to understand.
 2732: 
 2733: Since XTs are cell-sized, you can store them in memory and manipulate
 2734: them on the stack like other cells.  You can also compile the XT into a
 2735: word with @code{compile,}:
 2736: 
 2737: @example
 2738: : foo1 ( n1 n2 -- n )
 2739:    [ ' + compile, ] ;
 2740: see foo
 2741: @end example
 2742: 
 2743: This is non-standard, because @code{compile,} has no compilation
 2744: semantics in the standard, but it works in good Forth systems.  For the
 2745: broken ones, use
 2746: 
 2747: @example
 2748: : [compile,] compile, ; immediate
 2749: 
 2750: : foo1 ( n1 n2 -- n )
 2751:    [ ' + ] [compile,] ;
 2752: see foo
 2753: @end example
 2754: 
 2755: @code{'} is a word with default compilation semantics; it parses the
 2756: next word when its interpretation semantics are executed, not during
 2757: compilation:
 2758: 
 2759: @example
 2760: : foo ( -- xt )
 2761:   ' ;
 2762: see foo
 2763: : bar ( ... "word" -- ... )
 2764:   ' execute ;
 2765: see bar
 2766: 1 2 bar + .
 2767: @end example
 2768: 
 2769: You often want to parse a word during compilation and compile its XT so
 2770: it will be pushed on the stack at run-time.  @code{[']} does this:
 2771: 
 2772: @example
 2773: : xt-+ ( -- xt )
 2774:   ['] + ;
 2775: see xt-+
 2776: 1 2 xt-+ execute .
 2777: @end example
 2778: 
 2779: Many programmers tend to see @code{'} and the word it parses as one
 2780: unit, and expect it to behave like @code{[']} when compiled, and are
 2781: confused by the actual behaviour.  If you are, just remember that the
 2782: Forth system just takes @code{'} as one unit and has no idea that it is
 2783: a parsing word (attempts to convenience programmers in this issue have
 2784: usually resulted in even worse pitfalls, see
 2785: @uref{http://www.complang.tuwien.ac.at/papers/ertl98.ps.gz,
 2786: @code{State}-smartness---Why it is evil and How to Exorcise it}).
 2787: 
 2788: Note that the state of the interpreter does not come into play when
 2789: creating and executing XTs.  I.e., even when you execute @code{'} in
 2790: compile state, it still gives you the interpretation semantics.  And
 2791: whatever that state is, @code{execute} performs the semantics
 2792: represented by the XT (i.e., for XTs produced with @code{'} the
 2793: interpretation semantics).
 2794: 
 2795: Reference: @ref{Tokens for Words}.
 2796: 
 2797: 
 2798: @node Exceptions Tutorial, Defining Words Tutorial, Execution Tokens Tutorial, Tutorial
 2799: @section Exceptions
 2800: @cindex exceptions tutorial
 2801: 
 2802: @code{throw ( n -- )} causes an exception unless n is zero.
 2803: 
 2804: @example
 2805: 100 throw .s
 2806: 0 throw .s
 2807: @end example
 2808: 
 2809: @code{catch ( ... xt -- ... n )} behaves similar to @code{execute}, but
 2810: it catches exceptions and pushes the number of the exception on the
 2811: stack (or 0, if the xt executed without exception).  If there was an
 2812: exception, the stacks have the same depth as when entering @code{catch}:
 2813: 
 2814: @example
 2815: .s
 2816: 3 0 ' / catch .s
 2817: 3 2 ' / catch .s
 2818: @end example
 2819: 
 2820: @quotation Assignment
 2821: Try the same with @code{execute} instead of @code{catch}.
 2822: @end quotation
 2823: 
 2824: @code{Throw} always jumps to the dynamically next enclosing
 2825: @code{catch}, even if it has to leave several call levels to achieve
 2826: this:
 2827: 
 2828: @example
 2829: : foo 100 throw ;
 2830: : foo1 foo ." after foo" ;
 2831: : bar ['] foo1 catch ;
 2832: bar .
 2833: @end example
 2834: 
 2835: It is often important to restore a value upon leaving a definition, even
 2836: if the definition is left through an exception.  You can ensure this
 2837: like this:
 2838: 
 2839: @example
 2840: : ...
 2841:    save-x
 2842:    ['] word-changing-x catch ( ... n )
 2843:    restore-x
 2844:    ( ... n ) throw ;
 2845: @end example
 2846: 
 2847: Gforth provides an alternative syntax in addition to @code{catch}:
 2848: @code{try ... recover ... endtry}.  If the code between @code{try} and
 2849: @code{recover} has an exception, the stack depths are restored, the
 2850: exception number is pushed on the stack, and the code between
 2851: @code{recover} and @code{endtry} is performed.  E.g., the definition for
 2852: @code{catch} is
 2853: 
 2854: @example
 2855: : catch ( x1 .. xn xt -- y1 .. ym 0 / z1 .. zn error ) \ exception
 2856:   try
 2857:     execute 0
 2858:   recover
 2859:     nip
 2860:   endtry ;
 2861: @end example
 2862: 
 2863: The equivalent to the restoration code above is
 2864: 
 2865: @example
 2866: : ...
 2867:   save-x
 2868:   try
 2869:     word-changing-x 0
 2870:   recover endtry
 2871:   restore-x
 2872:   throw ;
 2873: @end example
 2874: 
 2875: This works if @code{word-changing-x} does not change the stack depth,
 2876: otherwise you should add some code between @code{recover} and
 2877: @code{endtry} to balance the stack.
 2878: 
 2879: Reference: @ref{Exception Handling}.
 2880: 
 2881: 
 2882: @node Defining Words Tutorial, Arrays and Records Tutorial, Exceptions Tutorial, Tutorial
 2883: @section Defining Words
 2884: @cindex defining words tutorial
 2885: @cindex does> tutorial
 2886: @cindex create...does> tutorial
 2887: 
 2888: @c before semantics?
 2889: 
 2890: @code{:}, @code{create}, and @code{variable} are definition words: They
 2891: define other words.  @code{Constant} is another definition word:
 2892: 
 2893: @example
 2894: 5 constant foo
 2895: foo .
 2896: @end example
 2897: 
 2898: You can also use the prefixes @code{2} (double-cell) and @code{f}
 2899: (floating point) with @code{variable} and @code{constant}.
 2900: 
 2901: You can also define your own defining words.  E.g.:
 2902: 
 2903: @example
 2904: : variable ( "name" -- )
 2905:   create 0 , ;
 2906: @end example
 2907: 
 2908: You can also define defining words that create words that do something
 2909: other than just producing their address:
 2910: 
 2911: @example
 2912: : constant ( n "name" -- )
 2913:   create ,
 2914: does> ( -- n )
 2915:   ( addr ) @@ ;
 2916: 
 2917: 5 constant foo
 2918: foo .
 2919: @end example
 2920: 
 2921: The definition of @code{constant} above ends at the @code{does>}; i.e.,
 2922: @code{does>} replaces @code{;}, but it also does something else: It
 2923: changes the last defined word such that it pushes the address of the
 2924: body of the word and then performs the code after the @code{does>}
 2925: whenever it is called.
 2926: 
 2927: In the example above, @code{constant} uses @code{,} to store 5 into the
 2928: body of @code{foo}.  When @code{foo} executes, it pushes the address of
 2929: the body onto the stack, then (in the code after the @code{does>})
 2930: fetches the 5 from there.
 2931: 
 2932: The stack comment near the @code{does>} reflects the stack effect of the
 2933: defined word, not the stack effect of the code after the @code{does>}
 2934: (the difference is that the code expects the address of the body that
 2935: the stack comment does not show).
 2936: 
 2937: You can use these definition words to do factoring in cases that involve
 2938: (other) definition words.  E.g., a field offset is always added to an
 2939: address.  Instead of defining
 2940: 
 2941: @example
 2942: 2 cells constant offset-field1
 2943: @end example
 2944: 
 2945: and using this like
 2946: 
 2947: @example
 2948: ( addr ) offset-field1 +
 2949: @end example
 2950: 
 2951: you can define a definition word
 2952: 
 2953: @example
 2954: : simple-field ( n "name" -- )
 2955:   create ,
 2956: does> ( n1 -- n1+n )
 2957:   ( addr ) @@ + ;
 2958: @end example
 2959: 
 2960: Definition and use of field offsets now look like this:
 2961: 
 2962: @example
 2963: 2 cells simple-field field1
 2964: create mystruct 4 cells allot
 2965: mystruct .s field1 .s drop
 2966: @end example
 2967: 
 2968: If you want to do something with the word without performing the code
 2969: after the @code{does>}, you can access the body of a @code{create}d word
 2970: with @code{>body ( xt -- addr )}:
 2971: 
 2972: @example
 2973: : value ( n "name" -- )
 2974:   create ,
 2975: does> ( -- n1 )
 2976:   @@ ;
 2977: : to ( n "name" -- )
 2978:   ' >body ! ;
 2979: 
 2980: 5 value foo
 2981: foo .
 2982: 7 to foo
 2983: foo .
 2984: @end example
 2985: 
 2986: @quotation Assignment
 2987: Define @code{defer ( "name" -- )}, which creates a word that stores an
 2988: XT (at the start the XT of @code{abort}), and upon execution
 2989: @code{execute}s the XT.  Define @code{is ( xt "name" -- )} that stores
 2990: @code{xt} into @code{name}, a word defined with @code{defer}.  Indirect
 2991: recursion is one application of @code{defer}.
 2992: @end quotation
 2993: 
 2994: Reference: @ref{User-defined Defining Words}.
 2995: 
 2996: 
 2997: @node Arrays and Records Tutorial, POSTPONE Tutorial, Defining Words Tutorial, Tutorial
 2998: @section Arrays and Records
 2999: @cindex arrays tutorial
 3000: @cindex records tutorial
 3001: @cindex structs tutorial
 3002: 
 3003: Forth has no standard words for defining data structures such as arrays
 3004: and records (structs in C terminology), but you can build them yourself
 3005: based on address arithmetic.  You can also define words for defining
 3006: arrays and records (@pxref{Defining Words Tutorial,, Defining Words}).
 3007: 
 3008: One of the first projects a Forth newcomer sets out upon when learning
 3009: about defining words is an array defining word (possibly for
 3010: n-dimensional arrays).  Go ahead and do it, I did it, too; you will
 3011: learn something from it.  However, don't be disappointed when you later
 3012: learn that you have little use for these words (inappropriate use would
 3013: be even worse).  I have not yet found a set of useful array words yet;
 3014: the needs are just too diverse, and named, global arrays (the result of
 3015: naive use of defining words) are often not flexible enough (e.g.,
 3016: consider how to pass them as parameters).  Another such project is a set
 3017: of words to help dealing with strings.
 3018: 
 3019: On the other hand, there is a useful set of record words, and it has
 3020: been defined in @file{compat/struct.fs}; these words are predefined in
 3021: Gforth.  They are explained in depth elsewhere in this manual (see
 3022: @pxref{Structures}).  The @code{simple-field} example above is
 3023: simplified variant of fields in this package.
 3024: 
 3025: 
 3026: @node POSTPONE Tutorial, Literal Tutorial, Arrays and Records Tutorial, Tutorial
 3027: @section @code{POSTPONE}
 3028: @cindex postpone tutorial
 3029: 
 3030: You can compile the compilation semantics (instead of compiling the
 3031: interpretation semantics) of a word with @code{POSTPONE}:
 3032: 
 3033: @example
 3034: : MY-+ ( Compilation: -- ; Run-time of compiled code: n1 n2 -- n )
 3035:  POSTPONE + ; immediate
 3036: : foo ( n1 n2 -- n )
 3037:  MY-+ ;
 3038: 1 2 foo .
 3039: see foo
 3040: @end example
 3041: 
 3042: During the definition of @code{foo} the text interpreter performs the
 3043: compilation semantics of @code{MY-+}, which performs the compilation
 3044: semantics of @code{+}, i.e., it compiles @code{+} into @code{foo}.
 3045: 
 3046: This example also displays separate stack comments for the compilation
 3047: semantics and for the stack effect of the compiled code.  For words with
 3048: default compilation semantics these stack effects are usually not
 3049: displayed; the stack effect of the compilation semantics is always
 3050: @code{( -- )} for these words, the stack effect for the compiled code is
 3051: the stack effect of the interpretation semantics.
 3052: 
 3053: Note that the state of the interpreter does not come into play when
 3054: performing the compilation semantics in this way.  You can also perform
 3055: it interpretively, e.g.:
 3056: 
 3057: @example
 3058: : foo2 ( n1 n2 -- n )
 3059:  [ MY-+ ] ;
 3060: 1 2 foo .
 3061: see foo
 3062: @end example
 3063: 
 3064: However, there are some broken Forth systems where this does not always
 3065: work, and therefore this practice was been declared non-standard in
 3066: 1999.
 3067: @c !! repair.fs
 3068: 
 3069: Here is another example for using @code{POSTPONE}:
 3070: 
 3071: @example
 3072: : MY-- ( Compilation: -- ; Run-time of compiled code: n1 n2 -- n )
 3073:  POSTPONE negate POSTPONE + ; immediate compile-only
 3074: : bar ( n1 n2 -- n )
 3075:   MY-- ;
 3076: 2 1 bar .
 3077: see bar
 3078: @end example
 3079: 
 3080: You can define @code{ENDIF} in this way:
 3081: 
 3082: @example
 3083: : ENDIF ( Compilation: orig -- )
 3084:   POSTPONE then ; immediate
 3085: @end example
 3086: 
 3087: @quotation Assignment
 3088: Write @code{MY-2DUP} that has compilation semantics equivalent to
 3089: @code{2dup}, but compiles @code{over over}.
 3090: @end quotation
 3091: 
 3092: @c !! @xref{Macros} for reference
 3093: 
 3094: 
 3095: @node Literal Tutorial, Advanced macros Tutorial, POSTPONE Tutorial, Tutorial
 3096: @section @code{Literal}
 3097: @cindex literal tutorial
 3098: 
 3099: You cannot @code{POSTPONE} numbers:
 3100: 
 3101: @example
 3102: : [FOO] POSTPONE 500 ; immediate
 3103: @end example
 3104: 
 3105: Instead, you can use @code{LITERAL (compilation: n --; run-time: -- n )}:
 3106: 
 3107: @example
 3108: : [FOO] ( compilation: --; run-time: -- n )
 3109:   500 POSTPONE literal ; immediate
 3110: 
 3111: : flip [FOO] ;
 3112: flip .
 3113: see flip
 3114: @end example
 3115: 
 3116: @code{LITERAL} consumes a number at compile-time (when it's compilation
 3117: semantics are executed) and pushes it at run-time (when the code it
 3118: compiled is executed).  A frequent use of @code{LITERAL} is to compile a
 3119: number computed at compile time into the current word:
 3120: 
 3121: @example
 3122: : bar ( -- n )
 3123:   [ 2 2 + ] literal ;
 3124: see bar
 3125: @end example
 3126: 
 3127: @quotation Assignment
 3128: Write @code{]L} which allows writing the example above as @code{: bar (
 3129: -- n ) [ 2 2 + ]L ;}
 3130: @end quotation
 3131: 
 3132: @c !! @xref{Macros} for reference
 3133: 
 3134: 
 3135: @node Advanced macros Tutorial, Compilation Tokens Tutorial, Literal Tutorial, Tutorial
 3136: @section Advanced macros
 3137: @cindex macros, advanced tutorial
 3138: @cindex run-time code generation, tutorial
 3139: 
 3140: Reconsider @code{map-array} from @ref{Execution Tokens Tutorial,,
 3141: Execution Tokens}.  It frequently performs @code{execute}, a relatively
 3142: expensive operation in some Forth implementations.  You can use
 3143: @code{compile,} and @code{POSTPONE} to eliminate these @code{execute}s
 3144: and produce a word that contains the word to be performed directly:
 3145: 
 3146: @c use ]] ... [[
 3147: @example
 3148: : compile-map-array ( compilation: xt -- ; run-time: ... addr u -- ... )
 3149: \ at run-time, execute xt ( ... x -- ... ) for each element of the
 3150: \ array beginning at addr and containing u elements
 3151:   @{ xt @}
 3152:   POSTPONE cells POSTPONE over POSTPONE + POSTPONE swap POSTPONE ?do
 3153:     POSTPONE i POSTPONE @@ xt compile,
 3154:   1 cells POSTPONE literal POSTPONE +loop ;
 3155: 
 3156: : sum-array ( addr u -- n )
 3157:  0 rot rot [ ' + compile-map-array ] ;
 3158: see sum-array
 3159: a 5 sum-array .
 3160: @end example
 3161: 
 3162: You can use the full power of Forth for generating the code; here's an
 3163: example where the code is generated in a loop:
 3164: 
 3165: @example
 3166: : compile-vmul-step ( compilation: n --; run-time: n1 addr1 -- n2 addr2 )
 3167: \ n2=n1+(addr1)*n, addr2=addr1+cell
 3168:   POSTPONE tuck POSTPONE @@
 3169:   POSTPONE literal POSTPONE * POSTPONE +
 3170:   POSTPONE swap POSTPONE cell+ ;
 3171: 
 3172: : compile-vmul ( compilation: addr1 u -- ; run-time: addr2 -- n )
 3173: \ n=v1*v2 (inner product), where the v_i are represented as addr_i u
 3174:   0 postpone literal postpone swap
 3175:   [ ' compile-vmul-step compile-map-array ]
 3176:   postpone drop ;
 3177: see compile-vmul
 3178: 
 3179: : a-vmul ( addr -- n )
 3180: \ n=a*v, where v is a vector that's as long as a and starts at addr
 3181:  [ a 5 compile-vmul ] ;
 3182: see a-vmul
 3183: a a-vmul .
 3184: @end example
 3185: 
 3186: This example uses @code{compile-map-array} to show off, but you could
 3187: also use @code{map-array} instead (try it now!).
 3188: 
 3189: You can use this technique for efficient multiplication of large
 3190: matrices.  In matrix multiplication, you multiply every line of one
 3191: matrix with every column of the other matrix.  You can generate the code
 3192: for one line once, and use it for every column.  The only downside of
 3193: this technique is that it is cumbersome to recover the memory consumed
 3194: by the generated code when you are done (and in more complicated cases
 3195: it is not possible portably).
 3196: 
 3197: @c !! @xref{Macros} for reference
 3198: 
 3199: 
 3200: @node Compilation Tokens Tutorial, Wordlists and Search Order Tutorial, Advanced macros Tutorial, Tutorial
 3201: @section Compilation Tokens
 3202: @cindex compilation tokens, tutorial
 3203: @cindex CT, tutorial
 3204: 
 3205: This section is Gforth-specific.  You can skip it.
 3206: 
 3207: @code{' word compile,} compiles the interpretation semantics.  For words
 3208: with default compilation semantics this is the same as performing the
 3209: compilation semantics.  To represent the compilation semantics of other
 3210: words (e.g., words like @code{if} that have no interpretation
 3211: semantics), Gforth has the concept of a compilation token (CT,
 3212: consisting of two cells), and words @code{comp'} and @code{[comp']}.
 3213: You can perform the compilation semantics represented by a CT with
 3214: @code{execute}:
 3215: 
 3216: @example
 3217: : foo2 ( n1 n2 -- n )
 3218:    [ comp' + execute ] ;
 3219: see foo
 3220: @end example
 3221: 
 3222: You can compile the compilation semantics represented by a CT with
 3223: @code{postpone,}:
 3224: 
 3225: @example
 3226: : foo3 ( -- )
 3227:   [ comp' + postpone, ] ;
 3228: see foo3
 3229: @end example
 3230: 
 3231: @code{[ comp' word postpone, ]} is equivalent to @code{POSTPONE word}.
 3232: @code{comp'} is particularly useful for words that have no
 3233: interpretation semantics:
 3234: 
 3235: @example
 3236: ' if
 3237: comp' if .s 2drop
 3238: @end example
 3239: 
 3240: Reference: @ref{Tokens for Words}.
 3241: 
 3242: 
 3243: @node Wordlists and Search Order Tutorial,  , Compilation Tokens Tutorial, Tutorial
 3244: @section Wordlists and Search Order
 3245: @cindex wordlists tutorial
 3246: @cindex search order, tutorial
 3247: 
 3248: The dictionary is not just a memory area that allows you to allocate
 3249: memory with @code{allot}, it also contains the Forth words, arranged in
 3250: several wordlists.  When searching for a word in a wordlist,
 3251: conceptually you start searching at the youngest and proceed towards
 3252: older words (in reality most systems nowadays use hash-tables); i.e., if
 3253: you define a word with the same name as an older word, the new word
 3254: shadows the older word.
 3255: 
 3256: Which wordlists are searched in which order is determined by the search
 3257: order.  You can display the search order with @code{order}.  It displays
 3258: first the search order, starting with the wordlist searched first, then
 3259: it displays the wordlist that will contain newly defined words.
 3260: 
 3261: You can create a new, empty wordlist with @code{wordlist ( -- wid )}:
 3262: 
 3263: @example
 3264: wordlist constant mywords
 3265: @end example
 3266: 
 3267: @code{Set-current ( wid -- )} sets the wordlist that will contain newly
 3268: defined words (the @emph{current} wordlist):
 3269: 
 3270: @example
 3271: mywords set-current
 3272: order
 3273: @end example
 3274: 
 3275: Gforth does not display a name for the wordlist in @code{mywords}
 3276: because this wordlist was created anonymously with @code{wordlist}.
 3277: 
 3278: You can get the current wordlist with @code{get-current ( -- wid)}.  If
 3279: you want to put something into a specific wordlist without overall
 3280: effect on the current wordlist, this typically looks like this:
 3281: 
 3282: @example
 3283: get-current mywords set-current ( wid )
 3284: create someword
 3285: ( wid ) set-current
 3286: @end example
 3287: 
 3288: You can write the search order with @code{set-order ( wid1 .. widn n --
 3289: )} and read it with @code{get-order ( -- wid1 .. widn n )}.  The first
 3290: searched wordlist is topmost.
 3291: 
 3292: @example
 3293: get-order mywords swap 1+ set-order
 3294: order
 3295: @end example
 3296: 
 3297: Yes, the order of wordlists in the output of @code{order} is reversed
 3298: from stack comments and the output of @code{.s} and thus unintuitive.
 3299: 
 3300: @quotation Assignment
 3301: Define @code{>order ( wid -- )} with adds @code{wid} as first searched
 3302: wordlist to the search order.  Define @code{previous ( -- )}, which
 3303: removes the first searched wordlist from the search order.  Experiment
 3304: with boundary conditions (you will see some crashes or situations that
 3305: are hard or impossible to leave).
 3306: @end quotation
 3307: 
 3308: The search order is a powerful foundation for providing features similar
 3309: to Modula-2 modules and C++ namespaces.  However, trying to modularize
 3310: programs in this way has disadvantages for debugging and reuse/factoring
 3311: that overcome the advantages in my experience (I don't do huge projects,
 3312: though).  These disadvantages are not so clear in other
 3313: languages/programming environments, because these languages are not so
 3314: strong in debugging and reuse.
 3315: 
 3316: @c !! example
 3317: 
 3318: Reference: @ref{Word Lists}.
 3319: 
 3320: @c ******************************************************************
 3321: @node Introduction, Words, Tutorial, Top
 3322: @comment node-name,     next,           previous, up
 3323: @chapter An Introduction to ANS Forth
 3324: @cindex Forth - an introduction
 3325: 
 3326: The difference of this chapter from the Tutorial (@pxref{Tutorial}) is
 3327: that it is slower-paced in its examples, but uses them to dive deep into
 3328: explaining Forth internals (not covered by the Tutorial).  Apart from
 3329: that, this chapter covers far less material.  It is suitable for reading
 3330: without using a computer.
 3331: 
 3332: The primary purpose of this manual is to document Gforth. However, since
 3333: Forth is not a widely-known language and there is a lack of up-to-date
 3334: teaching material, it seems worthwhile to provide some introductory
 3335: material.  For other sources of Forth-related
 3336: information, see @ref{Forth-related information}.
 3337: 
 3338: The examples in this section should work on any ANS Forth; the
 3339: output shown was produced using Gforth. Each example attempts to
 3340: reproduce the exact output that Gforth produces. If you try out the
 3341: examples (and you should), what you should type is shown @kbd{like this}
 3342: and Gforth's response is shown @code{like this}. The single exception is
 3343: that, where the example shows @key{RET} it means that you should
 3344: press the ``carriage return'' key. Unfortunately, some output formats for
 3345: this manual cannot show the difference between @kbd{this} and
 3346: @code{this} which will make trying out the examples harder (but not
 3347: impossible).
 3348: 
 3349: Forth is an unusual language. It provides an interactive development
 3350: environment which includes both an interpreter and compiler. Forth
 3351: programming style encourages you to break a problem down into many
 3352: @cindex factoring
 3353: small fragments (@dfn{factoring}), and then to develop and test each
 3354: fragment interactively. Forth advocates assert that breaking the
 3355: edit-compile-test cycle used by conventional programming languages can
 3356: lead to great productivity improvements.
 3357: 
 3358: @menu
 3359: * Introducing the Text Interpreter::  
 3360: * Stacks and Postfix notation::  
 3361: * Your first definition::       
 3362: * How does that work?::         
 3363: * Forth is written in Forth::   
 3364: * Review - elements of a Forth system::  
 3365: * Where to go next::            
 3366: * Exercises::                   
 3367: @end menu
 3368: 
 3369: @comment ----------------------------------------------
 3370: @node Introducing the Text Interpreter, Stacks and Postfix notation, Introduction, Introduction
 3371: @section Introducing the Text Interpreter
 3372: @cindex text interpreter
 3373: @cindex outer interpreter
 3374: 
 3375: @c IMO this is too detailed and the pace is too slow for
 3376: @c an introduction.  If you know German, take a look at
 3377: @c http://www.complang.tuwien.ac.at/anton/lvas/skriptum-stack.html 
 3378: @c to see how I do it - anton 
 3379: 
 3380: @c nac-> Where I have accepted your comments 100% and modified the text
 3381: @c accordingly, I have deleted your comments. Elsewhere I have added a
 3382: @c response like this to attempt to rationalise what I have done. Of
 3383: @c course, this is a very clumsy mechanism for something that would be
 3384: @c done far more efficiently over a beer. Please delete any dialogue
 3385: @c you consider closed.
 3386: 
 3387: When you invoke the Forth image, you will see a startup banner printed
 3388: and nothing else (if you have Gforth installed on your system, try
 3389: invoking it now, by typing @kbd{gforth@key{RET}}). Forth is now running
 3390: its command line interpreter, which is called the @dfn{Text Interpreter}
 3391: (also known as the @dfn{Outer Interpreter}).  (You will learn a lot
 3392: about the text interpreter as you read through this chapter, for more
 3393: detail @pxref{The Text Interpreter}).
 3394: 
 3395: Although it's not obvious, Forth is actually waiting for your
 3396: input. Type a number and press the @key{RET} key:
 3397: 
 3398: @example
 3399: @kbd{45@key{RET}}  ok
 3400: @end example
 3401: 
 3402: Rather than give you a prompt to invite you to input something, the text
 3403: interpreter prints a status message @i{after} it has processed a line
 3404: of input. The status message in this case (``@code{ ok}'' followed by
 3405: carriage-return) indicates that the text interpreter was able to process
 3406: all of your input successfully. Now type something illegal:
 3407: 
 3408: @example
 3409: @kbd{qwer341@key{RET}}
 3410: *the terminal*:2: Undefined word
 3411: >>>qwer341<<<
 3412: Backtrace:
 3413: $2A95B42A20 throw 
 3414: $2A95B57FB8 no.extensions 
 3415: @end example
 3416: 
 3417: The exact text, other than the ``Undefined word'' may differ slightly
 3418: on your system, but the effect is the same; when the text interpreter
 3419: detects an error, it discards any remaining text on a line, resets
 3420: certain internal state and prints an error message. For a detailed
 3421: description of error messages see @ref{Error messages}.
 3422: 
 3423: The text interpreter waits for you to press carriage-return, and then
 3424: processes your input line. Starting at the beginning of the line, it
 3425: breaks the line into groups of characters separated by spaces. For each
 3426: group of characters in turn, it makes two attempts to do something:
 3427: 
 3428: @itemize @bullet
 3429: @item
 3430: @cindex name dictionary
 3431: It tries to treat it as a command. It does this by searching a @dfn{name
 3432: dictionary}. If the group of characters matches an entry in the name
 3433: dictionary, the name dictionary provides the text interpreter with
 3434: information that allows the text interpreter perform some actions. In
 3435: Forth jargon, we say that the group
 3436: @cindex word
 3437: @cindex definition
 3438: @cindex execution token
 3439: @cindex xt
 3440: of characters names a @dfn{word}, that the dictionary search returns an
 3441: @dfn{execution token (xt)} corresponding to the @dfn{definition} of the
 3442: word, and that the text interpreter executes the xt. Often, the terms
 3443: @dfn{word} and @dfn{definition} are used interchangeably.
 3444: @item
 3445: If the text interpreter fails to find a match in the name dictionary, it
 3446: tries to treat the group of characters as a number in the current number
 3447: base (when you start up Forth, the current number base is base 10). If
 3448: the group of characters legitimately represents a number, the text
 3449: interpreter pushes the number onto a stack (we'll learn more about that
 3450: in the next section).
 3451: @end itemize
 3452: 
 3453: If the text interpreter is unable to do either of these things with any
 3454: group of characters, it discards the group of characters and the rest of
 3455: the line, then prints an error message. If the text interpreter reaches
 3456: the end of the line without error, it prints the status message ``@code{ ok}''
 3457: followed by carriage-return.
 3458: 
 3459: This is the simplest command we can give to the text interpreter:
 3460: 
 3461: @example
 3462: @key{RET}  ok
 3463: @end example
 3464: 
 3465: The text interpreter did everything we asked it to do (nothing) without
 3466: an error, so it said that everything is ``@code{ ok}''. Try a slightly longer
 3467: command:
 3468: 
 3469: @example
 3470: @kbd{12 dup fred dup@key{RET}}
 3471: *the terminal*:3: Undefined word
 3472: 12 dup >>>fred<<< dup
 3473: Backtrace:
 3474: $2A95B42A20 throw 
 3475: $2A95B57FB8 no.extensions 
 3476: @end example
 3477: 
 3478: When you press the carriage-return key, the text interpreter starts to
 3479: work its way along the line:
 3480: 
 3481: @itemize @bullet
 3482: @item
 3483: When it gets to the space after the @code{2}, it takes the group of
 3484: characters @code{12} and looks them up in the name
 3485: dictionary@footnote{We can't tell if it found them or not, but assume
 3486: for now that it did not}. There is no match for this group of characters
 3487: in the name dictionary, so it tries to treat them as a number. It is
 3488: able to do this successfully, so it puts the number, 12, ``on the stack''
 3489: (whatever that means).
 3490: @item
 3491: The text interpreter resumes scanning the line and gets the next group
 3492: of characters, @code{dup}. It looks it up in the name dictionary and
 3493: (you'll have to take my word for this) finds it, and executes the word
 3494: @code{dup} (whatever that means).
 3495: @item
 3496: Once again, the text interpreter resumes scanning the line and gets the
 3497: group of characters @code{fred}. It looks them up in the name
 3498: dictionary, but can't find them. It tries to treat them as a number, but
 3499: they don't represent any legal number.
 3500: @end itemize
 3501: 
 3502: At this point, the text interpreter gives up and prints an error
 3503: message. The error message shows exactly how far the text interpreter
 3504: got in processing the line. In particular, it shows that the text
 3505: interpreter made no attempt to do anything with the final character
 3506: group, @code{dup}, even though we have good reason to believe that the
 3507: text interpreter would have no problem looking that word up and
 3508: executing it a second time.
 3509: 
 3510: 
 3511: @comment ----------------------------------------------
 3512: @node Stacks and Postfix notation, Your first definition, Introducing the Text Interpreter, Introduction
 3513: @section Stacks, postfix notation and parameter passing
 3514: @cindex text interpreter
 3515: @cindex outer interpreter
 3516: 
 3517: In procedural programming languages (like C and Pascal), the
 3518: building-block of programs is the @dfn{function} or @dfn{procedure}. These
 3519: functions or procedures are called with @dfn{explicit parameters}. For
 3520: example, in C we might write:
 3521: 
 3522: @example
 3523: total = total + new_volume(length,height,depth);
 3524: @end example
 3525: 
 3526: @noindent
 3527: where new_volume is a function-call to another piece of code, and total,
 3528: length, height and depth are all variables. length, height and depth are
 3529: parameters to the function-call.
 3530: 
 3531: In Forth, the equivalent of the function or procedure is the
 3532: @dfn{definition} and parameters are implicitly passed between
 3533: definitions using a shared stack that is visible to the
 3534: programmer. Although Forth does support variables, the existence of the
 3535: stack means that they are used far less often than in most other
 3536: programming languages. When the text interpreter encounters a number, it
 3537: will place (@dfn{push}) it on the stack. There are several stacks (the
 3538: actual number is implementation-dependent ...) and the particular stack
 3539: used for any operation is implied unambiguously by the operation being
 3540: performed. The stack used for all integer operations is called the @dfn{data
 3541: stack} and, since this is the stack used most commonly, references to
 3542: ``the data stack'' are often abbreviated to ``the stack''.
 3543: 
 3544: The stacks have a last-in, first-out (LIFO) organisation. If you type:
 3545: 
 3546: @example
 3547: @kbd{1 2 3@key{RET}}  ok
 3548: @end example
 3549: 
 3550: Then this instructs the text interpreter to placed three numbers on the
 3551: (data) stack. An analogy for the behaviour of the stack is to take a
 3552: pack of playing cards and deal out the ace (1), 2 and 3 into a pile on
 3553: the table. The 3 was the last card onto the pile (``last-in'') and if
 3554: you take a card off the pile then, unless you're prepared to fiddle a
 3555: bit, the card that you take off will be the 3 (``first-out''). The
 3556: number that will be first-out of the stack is called the @dfn{top of
 3557: stack}, which
 3558: @cindex TOS definition
 3559: is often abbreviated to @dfn{TOS}.
 3560: 
 3561: To understand how parameters are passed in Forth, consider the
 3562: behaviour of the definition @code{+} (pronounced ``plus''). You will not
 3563: be surprised to learn that this definition performs addition. More
 3564: precisely, it adds two number together and produces a result. Where does
 3565: it get the two numbers from? It takes the top two numbers off the
 3566: stack. Where does it place the result? On the stack. You can act-out the
 3567: behaviour of @code{+} with your playing cards like this:
 3568: 
 3569: @itemize @bullet
 3570: @item
 3571: Pick up two cards from the stack on the table
 3572: @item
 3573: Stare at them intently and ask yourself ``what @i{is} the sum of these two
 3574: numbers''
 3575: @item
 3576: Decide that the answer is 5
 3577: @item
 3578: Shuffle the two cards back into the pack and find a 5
 3579: @item
 3580: Put a 5 on the remaining ace that's on the table.
 3581: @end itemize
 3582: 
 3583: If you don't have a pack of cards handy but you do have Forth running,
 3584: you can use the definition @code{.s} to show the current state of the stack,
 3585: without affecting the stack. Type:
 3586: 
 3587: @example
 3588: @kbd{clearstacks 1 2 3@key{RET}} ok
 3589: @kbd{.s@key{RET}} <3> 1 2 3  ok
 3590: @end example
 3591: 
 3592: The text interpreter looks up the word @code{clearstacks} and executes
 3593: it; it tidies up the stacks and removes any entries that may have been
 3594: left on it by earlier examples. The text interpreter pushes each of the
 3595: three numbers in turn onto the stack. Finally, the text interpreter
 3596: looks up the word @code{.s} and executes it. The effect of executing
 3597: @code{.s} is to print the ``<3>'' (the total number of items on the stack)
 3598: followed by a list of all the items on the stack; the item on the far
 3599: right-hand side is the TOS.
 3600: 
 3601: You can now type:
 3602: 
 3603: @example
 3604: @kbd{+ .s@key{RET}} <2> 1 5  ok
 3605: @end example
 3606: 
 3607: @noindent
 3608: which is correct; there are now 2 items on the stack and the result of
 3609: the addition is 5.
 3610: 
 3611: If you're playing with cards, try doing a second addition: pick up the
 3612: two cards, work out that their sum is 6, shuffle them into the pack,
 3613: look for a 6 and place that on the table. You now have just one item on
 3614: the stack. What happens if you try to do a third addition? Pick up the
 3615: first card, pick up the second card -- ah! There is no second card. This
 3616: is called a @dfn{stack underflow} and consitutes an error. If you try to
 3617: do the same thing with Forth it often reports an error (probably a Stack
 3618: Underflow or an Invalid Memory Address error).
 3619: 
 3620: The opposite situation to a stack underflow is a @dfn{stack overflow},
 3621: which simply accepts that there is a finite amount of storage space
 3622: reserved for the stack. To stretch the playing card analogy, if you had
 3623: enough packs of cards and you piled the cards up on the table, you would
 3624: eventually be unable to add another card; you'd hit the ceiling. Gforth
 3625: allows you to set the maximum size of the stacks. In general, the only
 3626: time that you will get a stack overflow is because a definition has a
 3627: bug in it and is generating data on the stack uncontrollably.
 3628: 
 3629: There's one final use for the playing card analogy. If you model your
 3630: stack using a pack of playing cards, the maximum number of items on
 3631: your stack will be 52 (I assume you didn't use the Joker). The maximum
 3632: @i{value} of any item on the stack is 13 (the King). In fact, the only
 3633: possible numbers are positive integer numbers 1 through 13; you can't
 3634: have (for example) 0 or 27 or 3.52 or -2. If you change the way you
 3635: think about some of the cards, you can accommodate different
 3636: numbers. For example, you could think of the Jack as representing 0,
 3637: the Queen as representing -1 and the King as representing -2. Your
 3638: @i{range} remains unchanged (you can still only represent a total of 13
 3639: numbers) but the numbers that you can represent are -2 through 10.
 3640: 
 3641: In that analogy, the limit was the amount of information that a single
 3642: stack entry could hold, and Forth has a similar limit. In Forth, the
 3643: size of a stack entry is called a @dfn{cell}. The actual size of a cell is
 3644: implementation dependent and affects the maximum value that a stack
 3645: entry can hold. A Standard Forth provides a cell size of at least
 3646: 16-bits, and most desktop systems use a cell size of 32-bits.
 3647: 
 3648: Forth does not do any type checking for you, so you are free to
 3649: manipulate and combine stack items in any way you wish. A convenient way
 3650: of treating stack items is as 2's complement signed integers, and that
 3651: is what Standard words like @code{+} do. Therefore you can type:
 3652: 
 3653: @example
 3654: @kbd{-5 12 + .s@key{RET}} <1> 7  ok
 3655: @end example
 3656: 
 3657: If you use numbers and definitions like @code{+} in order to turn Forth
 3658: into a great big pocket calculator, you will realise that it's rather
 3659: different from a normal calculator. Rather than typing 2 + 3 = you had
 3660: to type 2 3 + (ignore the fact that you had to use @code{.s} to see the
 3661: result). The terminology used to describe this difference is to say that
 3662: your calculator uses @dfn{Infix Notation} (parameters and operators are
 3663: mixed) whilst Forth uses @dfn{Postfix Notation} (parameters and
 3664: operators are separate), also called @dfn{Reverse Polish Notation}.
 3665: 
 3666: Whilst postfix notation might look confusing to begin with, it has
 3667: several important advantages:
 3668: 
 3669: @itemize @bullet
 3670: @item
 3671: it is unambiguous
 3672: @item
 3673: it is more concise
 3674: @item
 3675: it fits naturally with a stack-based system
 3676: @end itemize
 3677: 
 3678: To examine these claims in more detail, consider these sums:
 3679: 
 3680: @example
 3681: 6 + 5 * 4 =
 3682: 4 * 5 + 6 =
 3683: @end example
 3684: 
 3685: If you're just learning maths or your maths is very rusty, you will
 3686: probably come up with the answer 44 for the first and 26 for the
 3687: second. If you are a bit of a whizz at maths you will remember the
 3688: @i{convention} that multiplication takes precendence over addition, and
 3689: you'd come up with the answer 26 both times. To explain the answer 26
 3690: to someone who got the answer 44, you'd probably rewrite the first sum
 3691: like this:
 3692: 
 3693: @example
 3694: 6 + (5 * 4) =
 3695: @end example
 3696: 
 3697: If what you really wanted was to perform the addition before the
 3698: multiplication, you would have to use parentheses to force it.
 3699: 
 3700: If you did the first two sums on a pocket calculator you would probably
 3701: get the right answers, unless you were very cautious and entered them using
 3702: these keystroke sequences:
 3703: 
 3704: 6 + 5 = * 4 =
 3705: 4 * 5 = + 6 =
 3706: 
 3707: Postfix notation is unambiguous because the order that the operators
 3708: are applied is always explicit; that also means that parentheses are
 3709: never required. The operators are @i{active} (the act of quoting the
 3710: operator makes the operation occur) which removes the need for ``=''.
 3711: 
 3712: The sum 6 + 5 * 4 can be written (in postfix notation) in two
 3713: equivalent ways:
 3714: 
 3715: @example
 3716: 6 5 4 * +      or:
 3717: 5 4 * 6 +
 3718: @end example
 3719: 
 3720: An important thing that you should notice about this notation is that
 3721: the @i{order} of the numbers does not change; if you want to subtract
 3722: 2 from 10 you type @code{10 2 -}.
 3723: 
 3724: The reason that Forth uses postfix notation is very simple to explain: it
 3725: makes the implementation extremely simple, and it follows naturally from
 3726: using the stack as a mechanism for passing parameters. Another way of
 3727: thinking about this is to realise that all Forth definitions are
 3728: @i{active}; they execute as they are encountered by the text
 3729: interpreter. The result of this is that the syntax of Forth is trivially
 3730: simple.
 3731: 
 3732: 
 3733: 
 3734: @comment ----------------------------------------------
 3735: @node Your first definition, How does that work?, Stacks and Postfix notation, Introduction
 3736: @section Your first Forth definition
 3737: @cindex first definition
 3738: 
 3739: Until now, the examples we've seen have been trivial; we've just been
 3740: using Forth as a bigger-than-pocket calculator. Also, each calculation
 3741: we've shown has been a ``one-off'' -- to repeat it we'd need to type it in
 3742: again@footnote{That's not quite true. If you press the up-arrow key on
 3743: your keyboard you should be able to scroll back to any earlier command,
 3744: edit it and re-enter it.} In this section we'll see how to add new
 3745: words to Forth's vocabulary.
 3746: 
 3747: The easiest way to create a new word is to use a @dfn{colon
 3748: definition}. We'll define a few and try them out before worrying too
 3749: much about how they work. Try typing in these examples; be careful to
 3750: copy the spaces accurately:
 3751: 
 3752: @example
 3753: : add-two 2 + . ;
 3754: : greet ." Hello and welcome" ;
 3755: : demo 5 add-two ;
 3756: @end example
 3757: 
 3758: @noindent
 3759: Now try them out:
 3760: 
 3761: @example
 3762: @kbd{greet@key{RET}} Hello and welcome  ok
 3763: @kbd{greet greet@key{RET}} Hello and welcomeHello and welcome  ok
 3764: @kbd{4 add-two@key{RET}} 6  ok
 3765: @kbd{demo@key{RET}} 7  ok
 3766: @kbd{9 greet demo add-two@key{RET}} Hello and welcome7 11  ok
 3767: @end example
 3768: 
 3769: The first new thing that we've introduced here is the pair of words
 3770: @code{:} and @code{;}. These are used to start and terminate a new
 3771: definition, respectively. The first word after the @code{:} is the name
 3772: for the new definition.
 3773: 
 3774: As you can see from the examples, a definition is built up of words that
 3775: have already been defined; Forth makes no distinction between
 3776: definitions that existed when you started the system up, and those that
 3777: you define yourself.
 3778: 
 3779: The examples also introduce the words @code{.} (dot), @code{."}
 3780: (dot-quote) and @code{dup} (dewp). Dot takes the value from the top of
 3781: the stack and displays it. It's like @code{.s} except that it only
 3782: displays the top item of the stack and it is destructive; after it has
 3783: executed, the number is no longer on the stack. There is always one
 3784: space printed after the number, and no spaces before it. Dot-quote
 3785: defines a string (a sequence of characters) that will be printed when
 3786: the word is executed. The string can contain any printable characters
 3787: except @code{"}. A @code{"} has a special function; it is not a Forth
 3788: word but it acts as a delimiter (the way that delimiters work is
 3789: described in the next section). Finally, @code{dup} duplicates the value
 3790: at the top of the stack. Try typing @code{5 dup .s} to see what it does.
 3791: 
 3792: We already know that the text interpreter searches through the
 3793: dictionary to locate names. If you've followed the examples earlier, you
 3794: will already have a definition called @code{add-two}. Lets try modifying
 3795: it by typing in a new definition:
 3796: 
 3797: @example
 3798: @kbd{: add-two dup . ." + 2 =" 2 + . ;@key{RET}} redefined add-two  ok
 3799: @end example
 3800: 
 3801: Forth recognised that we were defining a word that already exists, and
 3802: printed a message to warn us of that fact. Let's try out the new
 3803: definition:
 3804: 
 3805: @example
 3806: @kbd{9 add-two@key{RET}} 9 + 2 =11  ok
 3807: @end example
 3808: 
 3809: @noindent
 3810: All that we've actually done here, though, is to create a new
 3811: definition, with a particular name. The fact that there was already a
 3812: definition with the same name did not make any difference to the way
 3813: that the new definition was created (except that Forth printed a warning
 3814: message). The old definition of add-two still exists (try @code{demo}
 3815: again to see that this is true). Any new definition will use the new
 3816: definition of @code{add-two}, but old definitions continue to use the
 3817: version that already existed at the time that they were @code{compiled}.
 3818: 
 3819: Before you go on to the next section, try defining and redefining some
 3820: words of your own.
 3821: 
 3822: @comment ----------------------------------------------
 3823: @node How does that work?, Forth is written in Forth, Your first definition, Introduction
 3824: @section How does that work?
 3825: @cindex parsing words
 3826: 
 3827: @c That's pretty deep (IMO way too deep) for an introduction. - anton
 3828: 
 3829: @c Is it a good idea to talk about the interpretation semantics of a
 3830: @c number? We don't have an xt to go along with it. - anton
 3831: 
 3832: @c Now that I have eliminated execution semantics, I wonder if it would not
 3833: @c be better to keep them (or add run-time semantics), to make it easier to
 3834: @c explain what compilation semantics usually does. - anton
 3835: 
 3836: @c nac-> I removed the term ``default compilation sematics'' from the
 3837: @c introductory chapter. Removing ``execution semantics'' was making
 3838: @c everything simpler to explain, then I think the use of this term made
 3839: @c everything more complex again. I replaced it with ``default
 3840: @c semantics'' (which is used elsewhere in the manual) by which I mean
 3841: @c ``a definition that has neither the immediate nor the compile-only
 3842: @c flag set''.
 3843: 
 3844: @c anton: I have eliminated default semantics (except in one place where it
 3845: @c means "default interpretation and compilation semantics"), because it
 3846: @c makes no sense in the presence of combined words.  I reverted to
 3847: @c "execution semantics" where necessary.
 3848: 
 3849: @c nac-> I reworded big chunks of the ``how does that work''
 3850: @c section (and, unusually for me, I think I even made it shorter!).  See
 3851: @c what you think -- I know I have not addressed your primary concern
 3852: @c that it is too heavy-going for an introduction. From what I understood
 3853: @c of your course notes it looks as though they might be a good framework. 
 3854: @c Things that I've tried to capture here are some things that came as a
 3855: @c great revelation here when I first understood them. Also, I like the
 3856: @c fact that a very simple code example shows up almost all of the issues
 3857: @c that you need to understand to see how Forth works. That's unique and
 3858: @c worthwhile to emphasise.
 3859: 
 3860: @c anton: I think it's a good idea to present the details, especially those
 3861: @c that you found to be a revelation, and probably the tutorial tries to be
 3862: @c too superficial and does not get some of the things across that make
 3863: @c Forth special.  I do believe that most of the time these things should
 3864: @c be discussed at the end of a section or in separate sections instead of
 3865: @c in the middle of a section (e.g., the stuff you added in "User-defined
 3866: @c defining words" leads in a completely different direction from the rest
 3867: @c of the section).
 3868: 
 3869: Now we're going to take another look at the definition of @code{add-two}
 3870: from the previous section. From our knowledge of the way that the text
 3871: interpreter works, we would have expected this result when we tried to
 3872: define @code{add-two}:
 3873: 
 3874: @example
 3875: @kbd{: add-two 2 + . ;@key{RET}}
 3876: *the terminal*:4: Undefined word
 3877: : >>>add-two<<< 2 + . ;
 3878: @end example
 3879: 
 3880: The reason that this didn't happen is bound up in the way that @code{:}
 3881: works. The word @code{:} does two special things. The first special
 3882: thing that it does prevents the text interpreter from ever seeing the
 3883: characters @code{add-two}. The text interpreter uses a variable called
 3884: @cindex modifying >IN
 3885: @code{>IN} (pronounced ``to-in'') to keep track of where it is in the
 3886: input line. When it encounters the word @code{:} it behaves in exactly
 3887: the same way as it does for any other word; it looks it up in the name
 3888: dictionary, finds its xt and executes it. When @code{:} executes, it
 3889: looks at the input buffer, finds the word @code{add-two} and advances the
 3890: value of @code{>IN} to point past it. It then does some other stuff
 3891: associated with creating the new definition (including creating an entry
 3892: for @code{add-two} in the name dictionary). When the execution of @code{:}
 3893: completes, control returns to the text interpreter, which is oblivious
 3894: to the fact that it has been tricked into ignoring part of the input
 3895: line.
 3896: 
 3897: @cindex parsing words
 3898: Words like @code{:} -- words that advance the value of @code{>IN} and so
 3899: prevent the text interpreter from acting on the whole of the input line
 3900: -- are called @dfn{parsing words}.
 3901: 
 3902: @cindex @code{state} - effect on the text interpreter
 3903: @cindex text interpreter - effect of state
 3904: The second special thing that @code{:} does is change the value of a
 3905: variable called @code{state}, which affects the way that the text
 3906: interpreter behaves. When Gforth starts up, @code{state} has the value
 3907: 0, and the text interpreter is said to be @dfn{interpreting}. During a
 3908: colon definition (started with @code{:}), @code{state} is set to -1 and
 3909: the text interpreter is said to be @dfn{compiling}.
 3910: 
 3911: In this example, the text interpreter is compiling when it processes the
 3912: string ``@code{2 + . ;}''. It still breaks the string down into
 3913: character sequences in the same way. However, instead of pushing the
 3914: number @code{2} onto the stack, it lays down (@dfn{compiles}) some magic
 3915: into the definition of @code{add-two} that will make the number @code{2} get
 3916: pushed onto the stack when @code{add-two} is @dfn{executed}. Similarly,
 3917: the behaviours of @code{+} and @code{.} are also compiled into the
 3918: definition.
 3919: 
 3920: One category of words don't get compiled. These so-called @dfn{immediate
 3921: words} get executed (performed @i{now}) regardless of whether the text
 3922: interpreter is interpreting or compiling. The word @code{;} is an
 3923: immediate word. Rather than being compiled into the definition, it
 3924: executes. Its effect is to terminate the current definition, which
 3925: includes changing the value of @code{state} back to 0.
 3926: 
 3927: When you execute @code{add-two}, it has a @dfn{run-time effect} that is
 3928: exactly the same as if you had typed @code{2 + . @key{RET}} outside of a
 3929: definition.
 3930: 
 3931: In Forth, every word or number can be described in terms of two
 3932: properties:
 3933: 
 3934: @itemize @bullet
 3935: @item
 3936: @cindex interpretation semantics
 3937: Its @dfn{interpretation semantics} describe how it will behave when the
 3938: text interpreter encounters it in @dfn{interpret} state. The
 3939: interpretation semantics of a word are represented by an @dfn{execution
 3940: token}.
 3941: @item
 3942: @cindex compilation semantics
 3943: Its @dfn{compilation semantics} describe how it will behave when the
 3944: text interpreter encounters it in @dfn{compile} state. The compilation
 3945: semantics of a word are represented in an implementation-dependent way;
 3946: Gforth uses a @dfn{compilation token}.
 3947: @end itemize
 3948: 
 3949: @noindent
 3950: Numbers are always treated in a fixed way:
 3951: 
 3952: @itemize @bullet
 3953: @item
 3954: When the number is @dfn{interpreted}, its behaviour is to push the
 3955: number onto the stack.
 3956: @item
 3957: When the number is @dfn{compiled}, a piece of code is appended to the
 3958: current definition that pushes the number when it runs. (In other words,
 3959: the compilation semantics of a number are to postpone its interpretation
 3960: semantics until the run-time of the definition that it is being compiled
 3961: into.)
 3962: @end itemize
 3963: 
 3964: Words don't behave in such a regular way, but most have @i{default
 3965: semantics} which means that they behave like this:
 3966: 
 3967: @itemize @bullet
 3968: @item
 3969: The @dfn{interpretation semantics} of the word are to do something useful.
 3970: @item
 3971: The @dfn{compilation semantics} of the word are to append its
 3972: @dfn{interpretation semantics} to the current definition (so that its
 3973: run-time behaviour is to do something useful).
 3974: @end itemize
 3975: 
 3976: @cindex immediate words
 3977: The actual behaviour of any particular word can be controlled by using
 3978: the words @code{immediate} and @code{compile-only} when the word is
 3979: defined. These words set flags in the name dictionary entry of the most
 3980: recently defined word, and these flags are retrieved by the text
 3981: interpreter when it finds the word in the name dictionary.
 3982: 
 3983: A word that is marked as @dfn{immediate} has compilation semantics that
 3984: are identical to its interpretation semantics. In other words, it
 3985: behaves like this:
 3986: 
 3987: @itemize @bullet
 3988: @item
 3989: The @dfn{interpretation semantics} of the word are to do something useful.
 3990: @item
 3991: The @dfn{compilation semantics} of the word are to do something useful
 3992: (and actually the same thing); i.e., it is executed during compilation.
 3993: @end itemize
 3994: 
 3995: Marking a word as @dfn{compile-only} prohibits the text interpreter from
 3996: performing the interpretation semantics of the word directly; an attempt
 3997: to do so will generate an error. It is never necessary to use
 3998: @code{compile-only} (and it is not even part of ANS Forth, though it is
 3999: provided by many implementations) but it is good etiquette to apply it
 4000: to a word that will not behave correctly (and might have unexpected
 4001: side-effects) in interpret state. For example, it is only legal to use
 4002: the conditional word @code{IF} within a definition. If you forget this
 4003: and try to use it elsewhere, the fact that (in Gforth) it is marked as
 4004: @code{compile-only} allows the text interpreter to generate a helpful
 4005: error message rather than subjecting you to the consequences of your
 4006: folly.
 4007: 
 4008: This example shows the difference between an immediate and a
 4009: non-immediate word:
 4010: 
 4011: @example
 4012: : show-state state @@ . ;
 4013: : show-state-now show-state ; immediate
 4014: : word1 show-state ;
 4015: : word2 show-state-now ;
 4016: @end example
 4017: 
 4018: The word @code{immediate} after the definition of @code{show-state-now}
 4019: makes that word an immediate word. These definitions introduce a new
 4020: word: @code{@@} (pronounced ``fetch''). This word fetches the value of a
 4021: variable, and leaves it on the stack. Therefore, the behaviour of
 4022: @code{show-state} is to print a number that represents the current value
 4023: of @code{state}.
 4024: 
 4025: When you execute @code{word1}, it prints the number 0, indicating that
 4026: the system is interpreting. When the text interpreter compiled the
 4027: definition of @code{word1}, it encountered @code{show-state} whose
 4028: compilation semantics are to append its interpretation semantics to the
 4029: current definition. When you execute @code{word1}, it performs the
 4030: interpretation semantics of @code{show-state}.  At the time that @code{word1}
 4031: (and therefore @code{show-state}) are executed, the system is
 4032: interpreting.
 4033: 
 4034: When you pressed @key{RET} after entering the definition of @code{word2},
 4035: you should have seen the number -1 printed, followed by ``@code{
 4036: ok}''. When the text interpreter compiled the definition of
 4037: @code{word2}, it encountered @code{show-state-now}, an immediate word,
 4038: whose compilation semantics are therefore to perform its interpretation
 4039: semantics. It is executed straight away (even before the text
 4040: interpreter has moved on to process another group of characters; the
 4041: @code{;} in this example). The effect of executing it are to display the
 4042: value of @code{state} @i{at the time that the definition of}
 4043: @code{word2} @i{is being defined}. Printing -1 demonstrates that the
 4044: system is compiling at this time. If you execute @code{word2} it does
 4045: nothing at all.
 4046: 
 4047: @cindex @code{."}, how it works
 4048: Before leaving the subject of immediate words, consider the behaviour of
 4049: @code{."} in the definition of @code{greet}, in the previous
 4050: section. This word is both a parsing word and an immediate word. Notice
 4051: that there is a space between @code{."} and the start of the text
 4052: @code{Hello and welcome}, but that there is no space between the last
 4053: letter of @code{welcome} and the @code{"} character. The reason for this
 4054: is that @code{."} is a Forth word; it must have a space after it so that
 4055: the text interpreter can identify it. The @code{"} is not a Forth word;
 4056: it is a @dfn{delimiter}. The examples earlier show that, when the string
 4057: is displayed, there is neither a space before the @code{H} nor after the
 4058: @code{e}. Since @code{."} is an immediate word, it executes at the time
 4059: that @code{greet} is defined. When it executes, its behaviour is to
 4060: search forward in the input line looking for the delimiter. When it
 4061: finds the delimiter, it updates @code{>IN} to point past the
 4062: delimiter. It also compiles some magic code into the definition of
 4063: @code{greet}; the xt of a run-time routine that prints a text string. It
 4064: compiles the string @code{Hello and welcome} into memory so that it is
 4065: available to be printed later. When the text interpreter gains control,
 4066: the next word it finds in the input stream is @code{;} and so it
 4067: terminates the definition of @code{greet}.
 4068: 
 4069: 
 4070: @comment ----------------------------------------------
 4071: @node Forth is written in Forth, Review - elements of a Forth system, How does that work?, Introduction
 4072: @section Forth is written in Forth
 4073: @cindex structure of Forth programs
 4074: 
 4075: When you start up a Forth compiler, a large number of definitions
 4076: already exist. In Forth, you develop a new application using bottom-up
 4077: programming techniques to create new definitions that are defined in
 4078: terms of existing definitions. As you create each definition you can
 4079: test and debug it interactively.
 4080: 
 4081: If you have tried out the examples in this section, you will probably
 4082: have typed them in by hand; when you leave Gforth, your definitions will
 4083: be lost. You can avoid this by using a text editor to enter Forth source
 4084: code into a file, and then loading code from the file using
 4085: @code{include} (@pxref{Forth source files}). A Forth source file is
 4086: processed by the text interpreter, just as though you had typed it in by
 4087: hand@footnote{Actually, there are some subtle differences -- see
 4088: @ref{The Text Interpreter}.}.
 4089: 
 4090: Gforth also supports the traditional Forth alternative to using text
 4091: files for program entry (@pxref{Blocks}).
 4092: 
 4093: In common with many, if not most, Forth compilers, most of Gforth is
 4094: actually written in Forth. All of the @file{.fs} files in the
 4095: installation directory@footnote{For example,
 4096: @file{/usr/local/share/gforth...}} are Forth source files, which you can
 4097: study to see examples of Forth programming.
 4098: 
 4099: Gforth maintains a history file that records every line that you type to
 4100: the text interpreter. This file is preserved between sessions, and is
 4101: used to provide a command-line recall facility. If you enter long
 4102: definitions by hand, you can use a text editor to paste them out of the
 4103: history file into a Forth source file for reuse at a later time
 4104: (for more information @pxref{Command-line editing}).
 4105: 
 4106: 
 4107: @comment ----------------------------------------------
 4108: @node Review - elements of a Forth system, Where to go next, Forth is written in Forth, Introduction
 4109: @section Review - elements of a Forth system
 4110: @cindex elements of a Forth system
 4111: 
 4112: To summarise this chapter:
 4113: 
 4114: @itemize @bullet
 4115: @item
 4116: Forth programs use @dfn{factoring} to break a problem down into small
 4117: fragments called @dfn{words} or @dfn{definitions}.
 4118: @item
 4119: Forth program development is an interactive process.
 4120: @item
 4121: The main command loop that accepts input, and controls both
 4122: interpretation and compilation, is called the @dfn{text interpreter}
 4123: (also known as the @dfn{outer interpreter}).
 4124: @item
 4125: Forth has a very simple syntax, consisting of words and numbers
 4126: separated by spaces or carriage-return characters. Any additional syntax
 4127: is imposed by @dfn{parsing words}.
 4128: @item
 4129: Forth uses a stack to pass parameters between words. As a result, it
 4130: uses postfix notation.
 4131: @item
 4132: To use a word that has previously been defined, the text interpreter
 4133: searches for the word in the @dfn{name dictionary}.
 4134: @item
 4135: Words have @dfn{interpretation semantics} and @dfn{compilation semantics}.
 4136: @item
 4137: The text interpreter uses the value of @code{state} to select between
 4138: the use of the @dfn{interpretation semantics} and the  @dfn{compilation
 4139: semantics} of a word that it encounters.
 4140: @item
 4141: The relationship between the @dfn{interpretation semantics} and
 4142: @dfn{compilation semantics} for a word
 4143: depend upon the way in which the word was defined (for example, whether
 4144: it is an @dfn{immediate} word).
 4145: @item
 4146: Forth definitions can be implemented in Forth (called @dfn{high-level
 4147: definitions}) or in some other way (usually a lower-level language and
 4148: as a result often called @dfn{low-level definitions}, @dfn{code
 4149: definitions} or @dfn{primitives}).
 4150: @item
 4151: Many Forth systems are implemented mainly in Forth.
 4152: @end itemize
 4153: 
 4154: 
 4155: @comment ----------------------------------------------
 4156: @node Where to go next, Exercises, Review - elements of a Forth system, Introduction
 4157: @section Where To Go Next
 4158: @cindex where to go next
 4159: 
 4160: Amazing as it may seem, if you have read (and understood) this far, you
 4161: know almost all the fundamentals about the inner workings of a Forth
 4162: system. You certainly know enough to be able to read and understand the
 4163: rest of this manual and the ANS Forth document, to learn more about the
 4164: facilities that Forth in general and Gforth in particular provide. Even
 4165: scarier, you know almost enough to implement your own Forth system.
 4166: However, that's not a good idea just yet... better to try writing some
 4167: programs in Gforth.
 4168: 
 4169: Forth has such a rich vocabulary that it can be hard to know where to
 4170: start in learning it. This section suggests a few sets of words that are
 4171: enough to write small but useful programs. Use the word index in this
 4172: document to learn more about each word, then try it out and try to write
 4173: small definitions using it. Start by experimenting with these words:
 4174: 
 4175: @itemize @bullet
 4176: @item
 4177: Arithmetic: @code{+ - * / /MOD */ ABS INVERT}
 4178: @item
 4179: Comparison: @code{MIN MAX =}
 4180: @item
 4181: Logic: @code{AND OR XOR NOT}
 4182: @item
 4183: Stack manipulation: @code{DUP DROP SWAP OVER}
 4184: @item
 4185: Loops and decisions: @code{IF ELSE ENDIF ?DO I LOOP}
 4186: @item
 4187: Input/Output: @code{. ." EMIT CR KEY}
 4188: @item
 4189: Defining words: @code{: ; CREATE}
 4190: @item
 4191: Memory allocation words: @code{ALLOT ,}
 4192: @item
 4193: Tools: @code{SEE WORDS .S MARKER}
 4194: @end itemize
 4195: 
 4196: When you have mastered those, go on to:
 4197: 
 4198: @itemize @bullet
 4199: @item
 4200: More defining words: @code{VARIABLE CONSTANT VALUE TO CREATE DOES>}
 4201: @item
 4202: Memory access: @code{@@ !}
 4203: @end itemize
 4204: 
 4205: When you have mastered these, there's nothing for it but to read through
 4206: the whole of this manual and find out what you've missed.
 4207: 
 4208: @comment ----------------------------------------------
 4209: @node Exercises,  , Where to go next, Introduction
 4210: @section Exercises
 4211: @cindex exercises
 4212: 
 4213: TODO: provide a set of programming excercises linked into the stuff done
 4214: already and into other sections of the manual. Provide solutions to all
 4215: the exercises in a .fs file in the distribution.
 4216: 
 4217: @c Get some inspiration from Starting Forth and Kelly&Spies.
 4218: 
 4219: @c excercises:
 4220: @c 1. take inches and convert to feet and inches.
 4221: @c 2. take temperature and convert from fahrenheight to celcius;
 4222: @c    may need to care about symmetric vs floored??
 4223: @c 3. take input line and do character substitution
 4224: @c    to encipher or decipher
 4225: @c 4. as above but work on a file for in and out
 4226: @c 5. take input line and convert to pig-latin 
 4227: @c
 4228: @c thing of sets of things to exercise then come up with
 4229: @c problems that need those things.
 4230: 
 4231: 
 4232: @c ******************************************************************
 4233: @node Words, Error messages, Introduction, Top
 4234: @chapter Forth Words
 4235: @cindex words
 4236: 
 4237: @menu
 4238: * Notation::                    
 4239: * Case insensitivity::          
 4240: * Comments::                    
 4241: * Boolean Flags::               
 4242: * Arithmetic::                  
 4243: * Stack Manipulation::          
 4244: * Memory::                      
 4245: * Control Structures::          
 4246: * Defining Words::              
 4247: * Interpretation and Compilation Semantics::  
 4248: * Tokens for Words::            
 4249: * Compiling words::             
 4250: * The Text Interpreter::        
 4251: * The Input Stream::            
 4252: * Word Lists::                  
 4253: * Environmental Queries::       
 4254: * Files::                       
 4255: * Blocks::                      
 4256: * Other I/O::                   
 4257: * OS command line arguments::   
 4258: * Locals::                      
 4259: * Structures::                  
 4260: * Object-oriented Forth::       
 4261: * Programming Tools::           
 4262: * C Interface::                 
 4263: * Assembler and Code Words::    
 4264: * Threading Words::             
 4265: * Passing Commands to the OS::  
 4266: * Keeping track of Time::       
 4267: * Miscellaneous Words::         
 4268: @end menu
 4269: 
 4270: @node Notation, Case insensitivity, Words, Words
 4271: @section Notation
 4272: @cindex notation of glossary entries
 4273: @cindex format of glossary entries
 4274: @cindex glossary notation format
 4275: @cindex word glossary entry format
 4276: 
 4277: The Forth words are described in this section in the glossary notation
 4278: that has become a de-facto standard for Forth texts:
 4279: 
 4280: @format
 4281: @i{word}     @i{Stack effect}   @i{wordset}   @i{pronunciation}
 4282: @end format
 4283: @i{Description}
 4284: 
 4285: @table @var
 4286: @item word
 4287: The name of the word.
 4288: 
 4289: @item Stack effect
 4290: @cindex stack effect
 4291: The stack effect is written in the notation @code{@i{before} --
 4292: @i{after}}, where @i{before} and @i{after} describe the top of
 4293: stack entries before and after the execution of the word. The rest of
 4294: the stack is not touched by the word. The top of stack is rightmost,
 4295: i.e., a stack sequence is written as it is typed in. Note that Gforth
 4296: uses a separate floating point stack, but a unified stack
 4297: notation. Also, return stack effects are not shown in @i{stack
 4298: effect}, but in @i{Description}. The name of a stack item describes
 4299: the type and/or the function of the item. See below for a discussion of
 4300: the types.
 4301: 
 4302: All words have two stack effects: A compile-time stack effect and a
 4303: run-time stack effect. The compile-time stack-effect of most words is
 4304: @i{ -- }. If the compile-time stack-effect of a word deviates from
 4305: this standard behaviour, or the word does other unusual things at
 4306: compile time, both stack effects are shown; otherwise only the run-time
 4307: stack effect is shown.
 4308: 
 4309: @cindex pronounciation of words
 4310: @item pronunciation
 4311: How the word is pronounced.
 4312: 
 4313: @cindex wordset
 4314: @cindex environment wordset
 4315: @item wordset
 4316: The ANS Forth standard is divided into several word sets. A standard
 4317: system need not support all of them. Therefore, in theory, the fewer
 4318: word sets your program uses the more portable it will be. However, we
 4319: suspect that most ANS Forth systems on personal machines will feature
 4320: all word sets. Words that are not defined in ANS Forth have
 4321: @code{gforth} or @code{gforth-internal} as word set. @code{gforth}
 4322: describes words that will work in future releases of Gforth;
 4323: @code{gforth-internal} words are more volatile. Environmental query
 4324: strings are also displayed like words; you can recognize them by the
 4325: @code{environment} in the word set field.
 4326: 
 4327: @item Description
 4328: A description of the behaviour of the word.
 4329: @end table
 4330: 
 4331: @cindex types of stack items
 4332: @cindex stack item types
 4333: The type of a stack item is specified by the character(s) the name
 4334: starts with:
 4335: 
 4336: @table @code
 4337: @item f
 4338: @cindex @code{f}, stack item type
 4339: Boolean flags, i.e. @code{false} or @code{true}.
 4340: @item c
 4341: @cindex @code{c}, stack item type
 4342: Char
 4343: @item w
 4344: @cindex @code{w}, stack item type
 4345: Cell, can contain an integer or an address
 4346: @item n
 4347: @cindex @code{n}, stack item type
 4348: signed integer
 4349: @item u
 4350: @cindex @code{u}, stack item type
 4351: unsigned integer
 4352: @item d
 4353: @cindex @code{d}, stack item type
 4354: double sized signed integer
 4355: @item ud
 4356: @cindex @code{ud}, stack item type
 4357: double sized unsigned integer
 4358: @item r
 4359: @cindex @code{r}, stack item type
 4360: Float (on the FP stack)
 4361: @item a-
 4362: @cindex @code{a_}, stack item type
 4363: Cell-aligned address
 4364: @item c-
 4365: @cindex @code{c_}, stack item type
 4366: Char-aligned address (note that a Char may have two bytes in Windows NT)
 4367: @item f-
 4368: @cindex @code{f_}, stack item type
 4369: Float-aligned address
 4370: @item df-
 4371: @cindex @code{df_}, stack item type
 4372: Address aligned for IEEE double precision float
 4373: @item sf-
 4374: @cindex @code{sf_}, stack item type
 4375: Address aligned for IEEE single precision float
 4376: @item xt
 4377: @cindex @code{xt}, stack item type
 4378: Execution token, same size as Cell
 4379: @item wid
 4380: @cindex @code{wid}, stack item type
 4381: Word list ID, same size as Cell
 4382: @item ior, wior
 4383: @cindex ior type description
 4384: @cindex wior type description
 4385: I/O result code, cell-sized.  In Gforth, you can @code{throw} iors.
 4386: @item f83name
 4387: @cindex @code{f83name}, stack item type
 4388: Pointer to a name structure
 4389: @item "
 4390: @cindex @code{"}, stack item type
 4391: string in the input stream (not on the stack). The terminating character
 4392: is a blank by default. If it is not a blank, it is shown in @code{<>}
 4393: quotes.
 4394: @end table
 4395: 
 4396: @comment ----------------------------------------------
 4397: @node Case insensitivity, Comments, Notation, Words
 4398: @section Case insensitivity
 4399: @cindex case sensitivity
 4400: @cindex upper and lower case
 4401: 
 4402: Gforth is case-insensitive; you can enter definitions and invoke
 4403: Standard words using upper, lower or mixed case (however,
 4404: @pxref{core-idef, Implementation-defined options, Implementation-defined
 4405: options}).
 4406: 
 4407: ANS Forth only @i{requires} implementations to recognise Standard words
 4408: when they are typed entirely in upper case. Therefore, a Standard
 4409: program must use upper case for all Standard words. You can use whatever
 4410: case you like for words that you define, but in a Standard program you
 4411: have to use the words in the same case that you defined them.
 4412: 
 4413: Gforth supports case sensitivity through @code{table}s (case-sensitive
 4414: wordlists, @pxref{Word Lists}).
 4415: 
 4416: Two people have asked how to convert Gforth to be case-sensitive; while
 4417: we think this is a bad idea, you can change all wordlists into tables
 4418: like this:
 4419: 
 4420: @example
 4421: ' table-find forth-wordlist wordlist-map @ !
 4422: @end example
 4423: 
 4424: Note that you now have to type the predefined words in the same case
 4425: that we defined them, which are varying.  You may want to convert them
 4426: to your favourite case before doing this operation (I won't explain how,
 4427: because if you are even contemplating doing this, you'd better have
 4428: enough knowledge of Forth systems to know this already).
 4429: 
 4430: @node Comments, Boolean Flags, Case insensitivity, Words
 4431: @section Comments
 4432: @cindex comments
 4433: 
 4434: Forth supports two styles of comment; the traditional @i{in-line} comment,
 4435: @code{(} and its modern cousin, the @i{comment to end of line}; @code{\}.
 4436: 
 4437: 
 4438: doc-(
 4439: doc-\
 4440: doc-\G
 4441: 
 4442: 
 4443: @node Boolean Flags, Arithmetic, Comments, Words
 4444: @section Boolean Flags
 4445: @cindex Boolean flags
 4446: 
 4447: A Boolean flag is cell-sized. A cell with all bits clear represents the
 4448: flag @code{false} and a flag with all bits set represents the flag
 4449: @code{true}. Words that check a flag (for example, @code{IF}) will treat
 4450: a cell that has @i{any} bit set as @code{true}.
 4451: @c on and off to Memory? 
 4452: @c true and false to "Bitwise operations" or "Numeric comparison"?
 4453: 
 4454: doc-true
 4455: doc-false
 4456: doc-on
 4457: doc-off
 4458: 
 4459: 
 4460: @node Arithmetic, Stack Manipulation, Boolean Flags, Words
 4461: @section Arithmetic
 4462: @cindex arithmetic words
 4463: 
 4464: @cindex division with potentially negative operands
 4465: Forth arithmetic is not checked, i.e., you will not hear about integer
 4466: overflow on addition or multiplication, you may hear about division by
 4467: zero if you are lucky. The operator is written after the operands, but
 4468: the operands are still in the original order. I.e., the infix @code{2-1}
 4469: corresponds to @code{2 1 -}. Forth offers a variety of division
 4470: operators. If you perform division with potentially negative operands,
 4471: you do not want to use @code{/} or @code{/mod} with its undefined
 4472: behaviour, but rather @code{fm/mod} or @code{sm/mod} (probably the
 4473: former, @pxref{Mixed precision}).
 4474: @comment TODO discuss the different division forms and the std approach
 4475: 
 4476: @menu
 4477: * Single precision::            
 4478: * Double precision::            Double-cell integer arithmetic
 4479: * Bitwise operations::          
 4480: * Numeric comparison::          
 4481: * Mixed precision::             Operations with single and double-cell integers
 4482: * Floating Point::              
 4483: @end menu
 4484: 
 4485: @node Single precision, Double precision, Arithmetic, Arithmetic
 4486: @subsection Single precision
 4487: @cindex single precision arithmetic words
 4488: 
 4489: @c !! cell undefined
 4490: 
 4491: By default, numbers in Forth are single-precision integers that are one
 4492: cell in size. They can be signed or unsigned, depending upon how you
 4493: treat them. For the rules used by the text interpreter for recognising
 4494: single-precision integers see @ref{Number Conversion}.
 4495: 
 4496: These words are all defined for signed operands, but some of them also
 4497: work for unsigned numbers: @code{+}, @code{1+}, @code{-}, @code{1-},
 4498: @code{*}.
 4499: 
 4500: doc-+
 4501: doc-1+
 4502: doc-under+
 4503: doc--
 4504: doc-1-
 4505: doc-*
 4506: doc-/
 4507: doc-mod
 4508: doc-/mod
 4509: doc-negate
 4510: doc-abs
 4511: doc-min
 4512: doc-max
 4513: doc-floored
 4514: 
 4515: 
 4516: @node Double precision, Bitwise operations, Single precision, Arithmetic
 4517: @subsection Double precision
 4518: @cindex double precision arithmetic words
 4519: 
 4520: For the rules used by the text interpreter for
 4521: recognising double-precision integers, see @ref{Number Conversion}.
 4522: 
 4523: A double precision number is represented by a cell pair, with the most
 4524: significant cell at the TOS. It is trivial to convert an unsigned single
 4525: to a double: simply push a @code{0} onto the TOS. Since numbers are
 4526: represented by Gforth using 2's complement arithmetic, converting a
 4527: signed single to a (signed) double requires sign-extension across the
 4528: most significant cell. This can be achieved using @code{s>d}. The moral
 4529: of the story is that you cannot convert a number without knowing whether
 4530: it represents an unsigned or a signed number.
 4531: 
 4532: These words are all defined for signed operands, but some of them also
 4533: work for unsigned numbers: @code{d+}, @code{d-}.
 4534: 
 4535: doc-s>d
 4536: doc-d>s
 4537: doc-d+
 4538: doc-d-
 4539: doc-dnegate
 4540: doc-dabs
 4541: doc-dmin
 4542: doc-dmax
 4543: 
 4544: 
 4545: @node Bitwise operations, Numeric comparison, Double precision, Arithmetic
 4546: @subsection Bitwise operations
 4547: @cindex bitwise operation words
 4548: 
 4549: 
 4550: doc-and
 4551: doc-or
 4552: doc-xor
 4553: doc-invert
 4554: doc-lshift
 4555: doc-rshift
 4556: doc-2*
 4557: doc-d2*
 4558: doc-2/
 4559: doc-d2/
 4560: 
 4561: 
 4562: @node Numeric comparison, Mixed precision, Bitwise operations, Arithmetic
 4563: @subsection Numeric comparison
 4564: @cindex numeric comparison words
 4565: 
 4566: Note that the words that compare for equality (@code{= <> 0= 0<> d= d<>
 4567: d0= d0<>}) work for for both signed and unsigned numbers.
 4568: 
 4569: doc-<
 4570: doc-<=
 4571: doc-<>
 4572: doc-=
 4573: doc->
 4574: doc->=
 4575: 
 4576: doc-0<
 4577: doc-0<=
 4578: doc-0<>
 4579: doc-0=
 4580: doc-0>
 4581: doc-0>=
 4582: 
 4583: doc-u<
 4584: doc-u<=
 4585: @c u<> and u= exist but are the same as <> and =
 4586: @c doc-u<>
 4587: @c doc-u=
 4588: doc-u>
 4589: doc-u>=
 4590: 
 4591: doc-within
 4592: 
 4593: doc-d<
 4594: doc-d<=
 4595: doc-d<>
 4596: doc-d=
 4597: doc-d>
 4598: doc-d>=
 4599: 
 4600: doc-d0<
 4601: doc-d0<=
 4602: doc-d0<>
 4603: doc-d0=
 4604: doc-d0>
 4605: doc-d0>=
 4606: 
 4607: doc-du<
 4608: doc-du<=
 4609: @c du<> and du= exist but are the same as d<> and d=
 4610: @c doc-du<>
 4611: @c doc-du=
 4612: doc-du>
 4613: doc-du>=
 4614: 
 4615: 
 4616: @node Mixed precision, Floating Point, Numeric comparison, Arithmetic
 4617: @subsection Mixed precision
 4618: @cindex mixed precision arithmetic words
 4619: 
 4620: 
 4621: doc-m+
 4622: doc-*/
 4623: doc-*/mod
 4624: doc-m*
 4625: doc-um*
 4626: doc-m*/
 4627: doc-um/mod
 4628: doc-fm/mod
 4629: doc-sm/rem
 4630: 
 4631: 
 4632: @node Floating Point,  , Mixed precision, Arithmetic
 4633: @subsection Floating Point
 4634: @cindex floating point arithmetic words
 4635: 
 4636: For the rules used by the text interpreter for
 4637: recognising floating-point numbers see @ref{Number Conversion}.
 4638: 
 4639: Gforth has a separate floating point stack, but the documentation uses
 4640: the unified notation.@footnote{It's easy to generate the separate
 4641: notation from that by just separating the floating-point numbers out:
 4642: e.g. @code{( n r1 u r2 -- r3 )} becomes @code{( n u -- ) ( F: r1 r2 --
 4643: r3 )}.}
 4644: 
 4645: @cindex floating-point arithmetic, pitfalls
 4646: Floating point numbers have a number of unpleasant surprises for the
 4647: unwary (e.g., floating point addition is not associative) and even a few
 4648: for the wary. You should not use them unless you know what you are doing
 4649: or you don't care that the results you get are totally bogus. If you
 4650: want to learn about the problems of floating point numbers (and how to
 4651: avoid them), you might start with @cite{David Goldberg,
 4652: @uref{http://www.validgh.com/goldberg/paper.ps,What Every Computer
 4653: Scientist Should Know About Floating-Point Arithmetic}, ACM Computing
 4654: Surveys 23(1):5@minus{}48, March 1991}.
 4655: 
 4656: 
 4657: doc-d>f
 4658: doc-f>d
 4659: doc-f+
 4660: doc-f-
 4661: doc-f*
 4662: doc-f/
 4663: doc-fnegate
 4664: doc-fabs
 4665: doc-fmax
 4666: doc-fmin
 4667: doc-floor
 4668: doc-fround
 4669: doc-f**
 4670: doc-fsqrt
 4671: doc-fexp
 4672: doc-fexpm1
 4673: doc-fln
 4674: doc-flnp1
 4675: doc-flog
 4676: doc-falog
 4677: doc-f2*
 4678: doc-f2/
 4679: doc-1/f
 4680: doc-precision
 4681: doc-set-precision
 4682: 
 4683: @cindex angles in trigonometric operations
 4684: @cindex trigonometric operations
 4685: Angles in floating point operations are given in radians (a full circle
 4686: has 2 pi radians).
 4687: 
 4688: doc-fsin
 4689: doc-fcos
 4690: doc-fsincos
 4691: doc-ftan
 4692: doc-fasin
 4693: doc-facos
 4694: doc-fatan
 4695: doc-fatan2
 4696: doc-fsinh
 4697: doc-fcosh
 4698: doc-ftanh
 4699: doc-fasinh
 4700: doc-facosh
 4701: doc-fatanh
 4702: doc-pi
 4703: 
 4704: @cindex equality of floats
 4705: @cindex floating-point comparisons
 4706: One particular problem with floating-point arithmetic is that comparison
 4707: for equality often fails when you would expect it to succeed.  For this
 4708: reason approximate equality is often preferred (but you still have to
 4709: know what you are doing).  Also note that IEEE NaNs may compare
 4710: differently from what you might expect.  The comparison words are:
 4711: 
 4712: doc-f~rel
 4713: doc-f~abs
 4714: doc-f~
 4715: doc-f=
 4716: doc-f<>
 4717: 
 4718: doc-f<
 4719: doc-f<=
 4720: doc-f>
 4721: doc-f>=
 4722: 
 4723: doc-f0<
 4724: doc-f0<=
 4725: doc-f0<>
 4726: doc-f0=
 4727: doc-f0>
 4728: doc-f0>=
 4729: 
 4730: 
 4731: @node Stack Manipulation, Memory, Arithmetic, Words
 4732: @section Stack Manipulation
 4733: @cindex stack manipulation words
 4734: 
 4735: @cindex floating-point stack in the standard
 4736: Gforth maintains a number of separate stacks:
 4737: 
 4738: @cindex data stack
 4739: @cindex parameter stack
 4740: @itemize @bullet
 4741: @item
 4742: A data stack (also known as the @dfn{parameter stack}) -- for
 4743: characters, cells, addresses, and double cells.
 4744: 
 4745: @cindex floating-point stack
 4746: @item
 4747: A floating point stack -- for holding floating point (FP) numbers.
 4748: 
 4749: @cindex return stack
 4750: @item
 4751: A return stack -- for holding the return addresses of colon
 4752: definitions and other (non-FP) data.
 4753: 
 4754: @cindex locals stack
 4755: @item
 4756: A locals stack -- for holding local variables.
 4757: @end itemize
 4758: 
 4759: @menu
 4760: * Data stack::                  
 4761: * Floating point stack::        
 4762: * Return stack::                
 4763: * Locals stack::                
 4764: * Stack pointer manipulation::  
 4765: @end menu
 4766: 
 4767: @node Data stack, Floating point stack, Stack Manipulation, Stack Manipulation
 4768: @subsection Data stack
 4769: @cindex data stack manipulation words
 4770: @cindex stack manipulations words, data stack
 4771: 
 4772: 
 4773: doc-drop
 4774: doc-nip
 4775: doc-dup
 4776: doc-over
 4777: doc-tuck
 4778: doc-swap
 4779: doc-pick
 4780: doc-rot
 4781: doc--rot
 4782: doc-?dup
 4783: doc-roll
 4784: doc-2drop
 4785: doc-2nip
 4786: doc-2dup
 4787: doc-2over
 4788: doc-2tuck
 4789: doc-2swap
 4790: doc-2rot
 4791: 
 4792: 
 4793: @node Floating point stack, Return stack, Data stack, Stack Manipulation
 4794: @subsection Floating point stack
 4795: @cindex floating-point stack manipulation words
 4796: @cindex stack manipulation words, floating-point stack
 4797: 
 4798: Whilst every sane Forth has a separate floating-point stack, it is not
 4799: strictly required; an ANS Forth system could theoretically keep
 4800: floating-point numbers on the data stack. As an additional difficulty,
 4801: you don't know how many cells a floating-point number takes. It is
 4802: reportedly possible to write words in a way that they work also for a
 4803: unified stack model, but we do not recommend trying it. Instead, just
 4804: say that your program has an environmental dependency on a separate
 4805: floating-point stack.
 4806: 
 4807: doc-floating-stack
 4808: 
 4809: doc-fdrop
 4810: doc-fnip
 4811: doc-fdup
 4812: doc-fover
 4813: doc-ftuck
 4814: doc-fswap
 4815: doc-fpick
 4816: doc-frot
 4817: 
 4818: 
 4819: @node Return stack, Locals stack, Floating point stack, Stack Manipulation
 4820: @subsection Return stack
 4821: @cindex return stack manipulation words
 4822: @cindex stack manipulation words, return stack
 4823: 
 4824: @cindex return stack and locals
 4825: @cindex locals and return stack
 4826: A Forth system is allowed to keep local variables on the
 4827: return stack. This is reasonable, as local variables usually eliminate
 4828: the need to use the return stack explicitly. So, if you want to produce
 4829: a standard compliant program and you are using local variables in a
 4830: word, forget about return stack manipulations in that word (refer to the
 4831: standard document for the exact rules).
 4832: 
 4833: doc->r
 4834: doc-r>
 4835: doc-r@
 4836: doc-rdrop
 4837: doc-2>r
 4838: doc-2r>
 4839: doc-2r@
 4840: doc-2rdrop
 4841: 
 4842: 
 4843: @node Locals stack, Stack pointer manipulation, Return stack, Stack Manipulation
 4844: @subsection Locals stack
 4845: 
 4846: Gforth uses an extra locals stack.  It is described, along with the
 4847: reasons for its existence, in @ref{Locals implementation}.
 4848: 
 4849: @node Stack pointer manipulation,  , Locals stack, Stack Manipulation
 4850: @subsection Stack pointer manipulation
 4851: @cindex stack pointer manipulation words
 4852: 
 4853: @c removed s0 r0 l0 -- they are obsolete aliases for sp0 rp0 lp0
 4854: doc-sp0
 4855: doc-sp@
 4856: doc-sp!
 4857: doc-fp0
 4858: doc-fp@
 4859: doc-fp!
 4860: doc-rp0
 4861: doc-rp@
 4862: doc-rp!
 4863: doc-lp0
 4864: doc-lp@
 4865: doc-lp!
 4866: 
 4867: 
 4868: @node Memory, Control Structures, Stack Manipulation, Words
 4869: @section Memory
 4870: @cindex memory words
 4871: 
 4872: @menu
 4873: * Memory model::                
 4874: * Dictionary allocation::       
 4875: * Heap Allocation::             
 4876: * Memory Access::               
 4877: * Address arithmetic::          
 4878: * Memory Blocks::               
 4879: @end menu
 4880: 
 4881: In addition to the standard Forth memory allocation words, there is also
 4882: a @uref{http://www.complang.tuwien.ac.at/forth/garbage-collection.zip,
 4883: garbage collector}.
 4884: 
 4885: @node Memory model, Dictionary allocation, Memory, Memory
 4886: @subsection ANS Forth and Gforth memory models
 4887: 
 4888: @c The ANS Forth description is a mess (e.g., is the heap part of
 4889: @c the dictionary?), so let's not stick to closely with it.
 4890: 
 4891: ANS Forth considers a Forth system as consisting of several address
 4892: spaces, of which only @dfn{data space} is managed and accessible with
 4893: the memory words.  Memory not necessarily in data space includes the
 4894: stacks, the code (called code space) and the headers (called name
 4895: space). In Gforth everything is in data space, but the code for the
 4896: primitives is usually read-only.
 4897: 
 4898: Data space is divided into a number of areas: The (data space portion of
 4899: the) dictionary@footnote{Sometimes, the term @dfn{dictionary} is used to
 4900: refer to the search data structure embodied in word lists and headers,
 4901: because it is used for looking up names, just as you would in a
 4902: conventional dictionary.}, the heap, and a number of system-allocated
 4903: buffers.
 4904: 
 4905: @cindex address arithmetic restrictions, ANS vs. Gforth
 4906: @cindex contiguous regions, ANS vs. Gforth
 4907: In ANS Forth data space is also divided into contiguous regions.  You
 4908: can only use address arithmetic within a contiguous region, not between
 4909: them.  Usually each allocation gives you one contiguous region, but the
 4910: dictionary allocation words have additional rules (@pxref{Dictionary
 4911: allocation}).
 4912: 
 4913: Gforth provides one big address space, and address arithmetic can be
 4914: performed between any addresses. However, in the dictionary headers or
 4915: code are interleaved with data, so almost the only contiguous data space
 4916: regions there are those described by ANS Forth as contiguous; but you
 4917: can be sure that the dictionary is allocated towards increasing
 4918: addresses even between contiguous regions.  The memory order of
 4919: allocations in the heap is platform-dependent (and possibly different
 4920: from one run to the next).
 4921: 
 4922: 
 4923: @node Dictionary allocation, Heap Allocation, Memory model, Memory
 4924: @subsection Dictionary allocation
 4925: @cindex reserving data space
 4926: @cindex data space - reserving some
 4927: 
 4928: Dictionary allocation is a stack-oriented allocation scheme, i.e., if
 4929: you want to deallocate X, you also deallocate everything
 4930: allocated after X.
 4931: 
 4932: @cindex contiguous regions in dictionary allocation
 4933: The allocations using the words below are contiguous and grow the region
 4934: towards increasing addresses.  Other words that allocate dictionary
 4935: memory of any kind (i.e., defining words including @code{:noname}) end
 4936: the contiguous region and start a new one.
 4937: 
 4938: In ANS Forth only @code{create}d words are guaranteed to produce an
 4939: address that is the start of the following contiguous region.  In
 4940: particular, the cell allocated by @code{variable} is not guaranteed to
 4941: be contiguous with following @code{allot}ed memory.
 4942: 
 4943: You can deallocate memory by using @code{allot} with a negative argument
 4944: (with some restrictions, see @code{allot}). For larger deallocations use
 4945: @code{marker}.
 4946: 
 4947: 
 4948: doc-here
 4949: doc-unused
 4950: doc-allot
 4951: doc-c,
 4952: doc-f,
 4953: doc-,
 4954: doc-2,
 4955: 
 4956: Memory accesses have to be aligned (@pxref{Address arithmetic}). So of
 4957: course you should allocate memory in an aligned way, too. I.e., before
 4958: allocating allocating a cell, @code{here} must be cell-aligned, etc.
 4959: The words below align @code{here} if it is not already.  Basically it is
 4960: only already aligned for a type, if the last allocation was a multiple
 4961: of the size of this type and if @code{here} was aligned for this type
 4962: before.
 4963: 
 4964: After freshly @code{create}ing a word, @code{here} is @code{align}ed in
 4965: ANS Forth (@code{maxalign}ed in Gforth).
 4966: 
 4967: doc-align
 4968: doc-falign
 4969: doc-sfalign
 4970: doc-dfalign
 4971: doc-maxalign
 4972: doc-cfalign
 4973: 
 4974: 
 4975: @node Heap Allocation, Memory Access, Dictionary allocation, Memory
 4976: @subsection Heap allocation
 4977: @cindex heap allocation
 4978: @cindex dynamic allocation of memory
 4979: @cindex memory-allocation word set
 4980: 
 4981: @cindex contiguous regions and heap allocation
 4982: Heap allocation supports deallocation of allocated memory in any
 4983: order. Dictionary allocation is not affected by it (i.e., it does not
 4984: end a contiguous region). In Gforth, these words are implemented using
 4985: the standard C library calls malloc(), free() and resize().
 4986: 
 4987: The memory region produced by one invocation of @code{allocate} or
 4988: @code{resize} is internally contiguous.  There is no contiguity between
 4989: such a region and any other region (including others allocated from the
 4990: heap).
 4991: 
 4992: doc-allocate
 4993: doc-free
 4994: doc-resize
 4995: 
 4996: 
 4997: @node Memory Access, Address arithmetic, Heap Allocation, Memory
 4998: @subsection Memory Access
 4999: @cindex memory access words
 5000: 
 5001: doc-@
 5002: doc-!
 5003: doc-+!
 5004: doc-c@
 5005: doc-c!
 5006: doc-2@
 5007: doc-2!
 5008: doc-f@
 5009: doc-f!
 5010: doc-sf@
 5011: doc-sf!
 5012: doc-df@
 5013: doc-df!
 5014: doc-sw@
 5015: doc-uw@
 5016: doc-w!
 5017: doc-sl@
 5018: doc-ul@
 5019: doc-l!
 5020: 
 5021: @node Address arithmetic, Memory Blocks, Memory Access, Memory
 5022: @subsection Address arithmetic
 5023: @cindex address arithmetic words
 5024: 
 5025: Address arithmetic is the foundation on which you can build data
 5026: structures like arrays, records (@pxref{Structures}) and objects
 5027: (@pxref{Object-oriented Forth}).
 5028: 
 5029: @cindex address unit
 5030: @cindex au (address unit)
 5031: ANS Forth does not specify the sizes of the data types. Instead, it
 5032: offers a number of words for computing sizes and doing address
 5033: arithmetic. Address arithmetic is performed in terms of address units
 5034: (aus); on most systems the address unit is one byte. Note that a
 5035: character may have more than one au, so @code{chars} is no noop (on
 5036: platforms where it is a noop, it compiles to nothing).
 5037: 
 5038: The basic address arithmetic words are @code{+} and @code{-}.  E.g., if
 5039: you have the address of a cell, perform @code{1 cells +}, and you will
 5040: have the address of the next cell.
 5041: 
 5042: @cindex contiguous regions and address arithmetic
 5043: In ANS Forth you can perform address arithmetic only within a contiguous
 5044: region, i.e., if you have an address into one region, you can only add
 5045: and subtract such that the result is still within the region; you can
 5046: only subtract or compare addresses from within the same contiguous
 5047: region.  Reasons: several contiguous regions can be arranged in memory
 5048: in any way; on segmented systems addresses may have unusual
 5049: representations, such that address arithmetic only works within a
 5050: region.  Gforth provides a few more guarantees (linear address space,
 5051: dictionary grows upwards), but in general I have found it easy to stay
 5052: within contiguous regions (exception: computing and comparing to the
 5053: address just beyond the end of an array).
 5054: 
 5055: @cindex alignment of addresses for types
 5056: ANS Forth also defines words for aligning addresses for specific
 5057: types. Many computers require that accesses to specific data types
 5058: must only occur at specific addresses; e.g., that cells may only be
 5059: accessed at addresses divisible by 4. Even if a machine allows unaligned
 5060: accesses, it can usually perform aligned accesses faster. 
 5061: 
 5062: For the performance-conscious: alignment operations are usually only
 5063: necessary during the definition of a data structure, not during the
 5064: (more frequent) accesses to it.
 5065: 
 5066: ANS Forth defines no words for character-aligning addresses. This is not
 5067: an oversight, but reflects the fact that addresses that are not
 5068: char-aligned have no use in the standard and therefore will not be
 5069: created.
 5070: 
 5071: @cindex @code{CREATE} and alignment
 5072: ANS Forth guarantees that addresses returned by @code{CREATE}d words
 5073: are cell-aligned; in addition, Gforth guarantees that these addresses
 5074: are aligned for all purposes.
 5075: 
 5076: Note that the ANS Forth word @code{char} has nothing to do with address
 5077: arithmetic.
 5078: 
 5079: 
 5080: doc-chars
 5081: doc-char+
 5082: doc-cells
 5083: doc-cell+
 5084: doc-cell
 5085: doc-aligned
 5086: doc-floats
 5087: doc-float+
 5088: doc-float
 5089: doc-faligned
 5090: doc-sfloats
 5091: doc-sfloat+
 5092: doc-sfaligned
 5093: doc-dfloats
 5094: doc-dfloat+
 5095: doc-dfaligned
 5096: doc-maxaligned
 5097: doc-cfaligned
 5098: doc-address-unit-bits
 5099: doc-/w
 5100: doc-/l
 5101: 
 5102: @node Memory Blocks,  , Address arithmetic, Memory
 5103: @subsection Memory Blocks
 5104: @cindex memory block words
 5105: @cindex character strings - moving and copying
 5106: 
 5107: Memory blocks often represent character strings; For ways of storing
 5108: character strings in memory see @ref{String Formats}.  For other
 5109: string-processing words see @ref{Displaying characters and strings}.
 5110: 
 5111: A few of these words work on address unit blocks.  In that case, you
 5112: usually have to insert @code{CHARS} before the word when working on
 5113: character strings.  Most words work on character blocks, and expect a
 5114: char-aligned address.
 5115: 
 5116: When copying characters between overlapping memory regions, use
 5117: @code{chars move} or choose carefully between @code{cmove} and
 5118: @code{cmove>}.
 5119: 
 5120: doc-move
 5121: doc-erase
 5122: doc-cmove
 5123: doc-cmove>
 5124: doc-fill
 5125: doc-blank
 5126: doc-compare
 5127: doc-str=
 5128: doc-str<
 5129: doc-string-prefix?
 5130: doc-search
 5131: doc--trailing
 5132: doc-/string
 5133: doc-bounds
 5134: doc-pad
 5135: 
 5136: @comment TODO examples
 5137: 
 5138: 
 5139: @node Control Structures, Defining Words, Memory, Words
 5140: @section Control Structures
 5141: @cindex control structures
 5142: 
 5143: Control structures in Forth cannot be used interpretively, only in a
 5144: colon definition@footnote{To be precise, they have no interpretation
 5145: semantics (@pxref{Interpretation and Compilation Semantics}).}. We do
 5146: not like this limitation, but have not seen a satisfying way around it
 5147: yet, although many schemes have been proposed.
 5148: 
 5149: @menu
 5150: * Selection::                   IF ... ELSE ... ENDIF
 5151: * Simple Loops::                BEGIN ...
 5152: * Counted Loops::               DO
 5153: * Arbitrary control structures::  
 5154: * Calls and returns::           
 5155: * Exception Handling::          
 5156: @end menu
 5157: 
 5158: @node Selection, Simple Loops, Control Structures, Control Structures
 5159: @subsection Selection
 5160: @cindex selection control structures
 5161: @cindex control structures for selection
 5162: 
 5163: @cindex @code{IF} control structure
 5164: @example
 5165: @i{flag}
 5166: IF
 5167:   @i{code}
 5168: ENDIF
 5169: @end example
 5170: @noindent
 5171: 
 5172: If @i{flag} is non-zero (as far as @code{IF} etc. are concerned, a cell
 5173: with any bit set represents truth) @i{code} is executed.
 5174: 
 5175: @example
 5176: @i{flag}
 5177: IF
 5178:   @i{code1}
 5179: ELSE
 5180:   @i{code2}
 5181: ENDIF
 5182: @end example
 5183: 
 5184: If @var{flag} is true, @i{code1} is executed, otherwise @i{code2} is
 5185: executed.
 5186: 
 5187: You can use @code{THEN} instead of @code{ENDIF}. Indeed, @code{THEN} is
 5188: standard, and @code{ENDIF} is not, although it is quite popular. We
 5189: recommend using @code{ENDIF}, because it is less confusing for people
 5190: who also know other languages (and is not prone to reinforcing negative
 5191: prejudices against Forth in these people). Adding @code{ENDIF} to a
 5192: system that only supplies @code{THEN} is simple:
 5193: @example
 5194: : ENDIF   POSTPONE then ; immediate
 5195: @end example
 5196: 
 5197: [According to @cite{Webster's New Encyclopedic Dictionary}, @dfn{then
 5198: (adv.)}  has the following meanings:
 5199: @quotation
 5200: ... 2b: following next after in order ... 3d: as a necessary consequence
 5201: (if you were there, then you saw them).
 5202: @end quotation
 5203: Forth's @code{THEN} has the meaning 2b, whereas @code{THEN} in Pascal
 5204: and many other programming languages has the meaning 3d.]
 5205: 
 5206: Gforth also provides the words @code{?DUP-IF} and @code{?DUP-0=-IF}, so
 5207: you can avoid using @code{?dup}. Using these alternatives is also more
 5208: efficient than using @code{?dup}. Definitions in ANS Forth
 5209: for @code{ENDIF}, @code{?DUP-IF} and @code{?DUP-0=-IF} are provided in
 5210: @file{compat/control.fs}.
 5211: 
 5212: @cindex @code{CASE} control structure
 5213: @example
 5214: @i{n}
 5215: CASE
 5216:   @i{n1} OF @i{code1} ENDOF
 5217:   @i{n2} OF @i{code2} ENDOF
 5218:   @dots{}
 5219:   ( n ) @i{default-code} ( n )
 5220: ENDCASE ( )
 5221: @end example
 5222: 
 5223: Executes the first @i{codei}, where the @i{ni} is equal to @i{n}.  If
 5224: no @i{ni} matches, the optional @i{default-code} is executed. The
 5225: optional default case can be added by simply writing the code after
 5226: the last @code{ENDOF}. It may use @i{n}, which is on top of the stack,
 5227: but must not consume it.  The value @i{n} is consumed by this
 5228: construction (either by a OF that matches, or by the ENDCASE, if no OF
 5229: matches).
 5230: 
 5231: @progstyle
 5232: To keep the code understandable, you should ensure that you change the
 5233: stack in the same way (wrt. number and types of stack items consumed
 5234: and pushed) on all paths through a selection construct.
 5235: 
 5236: @node Simple Loops, Counted Loops, Selection, Control Structures
 5237: @subsection Simple Loops
 5238: @cindex simple loops
 5239: @cindex loops without count 
 5240: 
 5241: @cindex @code{WHILE} loop
 5242: @example
 5243: BEGIN
 5244:   @i{code1}
 5245:   @i{flag}
 5246: WHILE
 5247:   @i{code2}
 5248: REPEAT
 5249: @end example
 5250: 
 5251: @i{code1} is executed and @i{flag} is computed. If it is true,
 5252: @i{code2} is executed and the loop is restarted; If @i{flag} is
 5253: false, execution continues after the @code{REPEAT}.
 5254: 
 5255: @cindex @code{UNTIL} loop
 5256: @example
 5257: BEGIN
 5258:   @i{code}
 5259:   @i{flag}
 5260: UNTIL
 5261: @end example
 5262: 
 5263: @i{code} is executed. The loop is restarted if @code{flag} is false.
 5264: 
 5265: @progstyle
 5266: To keep the code understandable, a complete iteration of the loop should
 5267: not change the number and types of the items on the stacks.
 5268: 
 5269: @cindex endless loop
 5270: @cindex loops, endless
 5271: @example
 5272: BEGIN
 5273:   @i{code}
 5274: AGAIN
 5275: @end example
 5276: 
 5277: This is an endless loop.
 5278: 
 5279: @node Counted Loops, Arbitrary control structures, Simple Loops, Control Structures
 5280: @subsection Counted Loops
 5281: @cindex counted loops
 5282: @cindex loops, counted
 5283: @cindex @code{DO} loops
 5284: 
 5285: The basic counted loop is:
 5286: @example
 5287: @i{limit} @i{start}
 5288: ?DO
 5289:   @i{body}
 5290: LOOP
 5291: @end example
 5292: 
 5293: This performs one iteration for every integer, starting from @i{start}
 5294: and up to, but excluding @i{limit}. The counter, or @i{index}, can be
 5295: accessed with @code{i}. For example, the loop:
 5296: @example
 5297: 10 0 ?DO
 5298:   i .
 5299: LOOP
 5300: @end example
 5301: @noindent
 5302: prints @code{0 1 2 3 4 5 6 7 8 9}
 5303: 
 5304: The index of the innermost loop can be accessed with @code{i}, the index
 5305: of the next loop with @code{j}, and the index of the third loop with
 5306: @code{k}.
 5307: 
 5308: 
 5309: doc-i
 5310: doc-j
 5311: doc-k
 5312: 
 5313: 
 5314: The loop control data are kept on the return stack, so there are some
 5315: restrictions on mixing return stack accesses and counted loop words. In
 5316: particuler, if you put values on the return stack outside the loop, you
 5317: cannot read them inside the loop@footnote{well, not in a way that is
 5318: portable.}. If you put values on the return stack within a loop, you
 5319: have to remove them before the end of the loop and before accessing the
 5320: index of the loop.
 5321: 
 5322: There are several variations on the counted loop:
 5323: 
 5324: @itemize @bullet
 5325: @item
 5326: @code{LEAVE} leaves the innermost counted loop immediately; execution
 5327: continues after the associated @code{LOOP} or @code{NEXT}. For example:
 5328: 
 5329: @example
 5330: 10 0 ?DO  i DUP . 3 = IF LEAVE THEN LOOP
 5331: @end example
 5332: prints @code{0 1 2 3}
 5333: 
 5334: 
 5335: @item
 5336: @code{UNLOOP} prepares for an abnormal loop exit, e.g., via
 5337: @code{EXIT}. @code{UNLOOP} removes the loop control parameters from the
 5338: return stack so @code{EXIT} can get to its return address. For example:
 5339: 
 5340: @example
 5341: : demo 10 0 ?DO i DUP . 3 = IF UNLOOP EXIT THEN LOOP ." Done" ;
 5342: @end example
 5343: prints @code{0 1 2 3}
 5344: 
 5345: 
 5346: @item
 5347: If @i{start} is greater than @i{limit}, a @code{?DO} loop is entered
 5348: (and @code{LOOP} iterates until they become equal by wrap-around
 5349: arithmetic). This behaviour is usually not what you want. Therefore,
 5350: Gforth offers @code{+DO} and @code{U+DO} (as replacements for
 5351: @code{?DO}), which do not enter the loop if @i{start} is greater than
 5352: @i{limit}; @code{+DO} is for signed loop parameters, @code{U+DO} for
 5353: unsigned loop parameters.
 5354: 
 5355: @item
 5356: @code{?DO} can be replaced by @code{DO}. @code{DO} always enters
 5357: the loop, independent of the loop parameters. Do not use @code{DO}, even
 5358: if you know that the loop is entered in any case. Such knowledge tends
 5359: to become invalid during maintenance of a program, and then the
 5360: @code{DO} will make trouble.
 5361: 
 5362: @item
 5363: @code{LOOP} can be replaced with @code{@i{n} +LOOP}; this updates the
 5364: index by @i{n} instead of by 1. The loop is terminated when the border
 5365: between @i{limit-1} and @i{limit} is crossed. E.g.:
 5366: 
 5367: @example
 5368: 4 0 +DO  i .  2 +LOOP
 5369: @end example
 5370: @noindent
 5371: prints @code{0 2}
 5372: 
 5373: @example
 5374: 4 1 +DO  i .  2 +LOOP
 5375: @end example
 5376: @noindent
 5377: prints @code{1 3}
 5378: 
 5379: @item
 5380: @cindex negative increment for counted loops
 5381: @cindex counted loops with negative increment
 5382: The behaviour of @code{@i{n} +LOOP} is peculiar when @i{n} is negative:
 5383: 
 5384: @example
 5385: -1 0 ?DO  i .  -1 +LOOP
 5386: @end example
 5387: @noindent
 5388: prints @code{0 -1}
 5389: 
 5390: @example
 5391: 0 0 ?DO  i .  -1 +LOOP
 5392: @end example
 5393: prints nothing.
 5394: 
 5395: Therefore we recommend avoiding @code{@i{n} +LOOP} with negative
 5396: @i{n}. One alternative is @code{@i{u} -LOOP}, which reduces the
 5397: index by @i{u} each iteration. The loop is terminated when the border
 5398: between @i{limit+1} and @i{limit} is crossed. Gforth also provides
 5399: @code{-DO} and @code{U-DO} for down-counting loops. E.g.:
 5400: 
 5401: @example
 5402: -2 0 -DO  i .  1 -LOOP
 5403: @end example
 5404: @noindent
 5405: prints @code{0 -1}
 5406: 
 5407: @example
 5408: -1 0 -DO  i .  1 -LOOP
 5409: @end example
 5410: @noindent
 5411: prints @code{0}
 5412: 
 5413: @example
 5414: 0 0 -DO  i .  1 -LOOP
 5415: @end example
 5416: @noindent
 5417: prints nothing.
 5418: 
 5419: @end itemize
 5420: 
 5421: Unfortunately, @code{+DO}, @code{U+DO}, @code{-DO}, @code{U-DO} and
 5422: @code{-LOOP} are not defined in ANS Forth. However, an implementation
 5423: for these words that uses only standard words is provided in
 5424: @file{compat/loops.fs}.
 5425: 
 5426: 
 5427: @cindex @code{FOR} loops
 5428: Another counted loop is:
 5429: @example
 5430: @i{n}
 5431: FOR
 5432:   @i{body}
 5433: NEXT
 5434: @end example
 5435: This is the preferred loop of native code compiler writers who are too
 5436: lazy to optimize @code{?DO} loops properly. This loop structure is not
 5437: defined in ANS Forth. In Gforth, this loop iterates @i{n+1} times;
 5438: @code{i} produces values starting with @i{n} and ending with 0. Other
 5439: Forth systems may behave differently, even if they support @code{FOR}
 5440: loops. To avoid problems, don't use @code{FOR} loops.
 5441: 
 5442: @node Arbitrary control structures, Calls and returns, Counted Loops, Control Structures
 5443: @subsection Arbitrary control structures
 5444: @cindex control structures, user-defined
 5445: 
 5446: @cindex control-flow stack
 5447: ANS Forth permits and supports using control structures in a non-nested
 5448: way. Information about incomplete control structures is stored on the
 5449: control-flow stack. This stack may be implemented on the Forth data
 5450: stack, and this is what we have done in Gforth.
 5451: 
 5452: @cindex @code{orig}, control-flow stack item
 5453: @cindex @code{dest}, control-flow stack item
 5454: An @i{orig} entry represents an unresolved forward branch, a @i{dest}
 5455: entry represents a backward branch target. A few words are the basis for
 5456: building any control structure possible (except control structures that
 5457: need storage, like calls, coroutines, and backtracking).
 5458: 
 5459: 
 5460: doc-if
 5461: doc-ahead
 5462: doc-then
 5463: doc-begin
 5464: doc-until
 5465: doc-again
 5466: doc-cs-pick
 5467: doc-cs-roll
 5468: 
 5469: 
 5470: The Standard words @code{CS-PICK} and @code{CS-ROLL} allow you to
 5471: manipulate the control-flow stack in a portable way. Without them, you
 5472: would need to know how many stack items are occupied by a control-flow
 5473: entry (many systems use one cell. In Gforth they currently take three,
 5474: but this may change in the future).
 5475: 
 5476: Some standard control structure words are built from these words:
 5477: 
 5478: 
 5479: doc-else
 5480: doc-while
 5481: doc-repeat
 5482: 
 5483: 
 5484: @noindent
 5485: Gforth adds some more control-structure words:
 5486: 
 5487: 
 5488: doc-endif
 5489: doc-?dup-if
 5490: doc-?dup-0=-if
 5491: 
 5492: 
 5493: @noindent
 5494: Counted loop words constitute a separate group of words:
 5495: 
 5496: 
 5497: doc-?do
 5498: doc-+do
 5499: doc-u+do
 5500: doc--do
 5501: doc-u-do
 5502: doc-do
 5503: doc-for
 5504: doc-loop
 5505: doc-+loop
 5506: doc--loop
 5507: doc-next
 5508: doc-leave
 5509: doc-?leave
 5510: doc-unloop
 5511: doc-done
 5512: 
 5513: 
 5514: The standard does not allow using @code{CS-PICK} and @code{CS-ROLL} on
 5515: @i{do-sys}. Gforth allows it, but it's your job to ensure that for
 5516: every @code{?DO} etc. there is exactly one @code{UNLOOP} on any path
 5517: through the definition (@code{LOOP} etc. compile an @code{UNLOOP} on the
 5518: fall-through path). Also, you have to ensure that all @code{LEAVE}s are
 5519: resolved (by using one of the loop-ending words or @code{DONE}).
 5520: 
 5521: @noindent
 5522: Another group of control structure words are:
 5523: 
 5524: 
 5525: doc-case
 5526: doc-endcase
 5527: doc-of
 5528: doc-endof
 5529: 
 5530: 
 5531: @i{case-sys} and @i{of-sys} cannot be processed using @code{CS-PICK} and
 5532: @code{CS-ROLL}.
 5533: 
 5534: @subsubsection Programming Style
 5535: @cindex control structures programming style
 5536: @cindex programming style, arbitrary control structures
 5537: 
 5538: In order to ensure readability we recommend that you do not create
 5539: arbitrary control structures directly, but define new control structure
 5540: words for the control structure you want and use these words in your
 5541: program. For example, instead of writing:
 5542: 
 5543: @example
 5544: BEGIN
 5545:   ...
 5546: IF [ 1 CS-ROLL ]
 5547:   ...
 5548: AGAIN THEN
 5549: @end example
 5550: 
 5551: @noindent
 5552: we recommend defining control structure words, e.g.,
 5553: 
 5554: @example
 5555: : WHILE ( DEST -- ORIG DEST )
 5556:  POSTPONE IF
 5557:  1 CS-ROLL ; immediate
 5558: 
 5559: : REPEAT ( orig dest -- )
 5560:  POSTPONE AGAIN
 5561:  POSTPONE THEN ; immediate
 5562: @end example
 5563: 
 5564: @noindent
 5565: and then using these to create the control structure:
 5566: 
 5567: @example
 5568: BEGIN
 5569:   ...
 5570: WHILE
 5571:   ...
 5572: REPEAT
 5573: @end example
 5574: 
 5575: That's much easier to read, isn't it? Of course, @code{REPEAT} and
 5576: @code{WHILE} are predefined, so in this example it would not be
 5577: necessary to define them.
 5578: 
 5579: @node Calls and returns, Exception Handling, Arbitrary control structures, Control Structures
 5580: @subsection Calls and returns
 5581: @cindex calling a definition
 5582: @cindex returning from a definition
 5583: 
 5584: @cindex recursive definitions
 5585: A definition can be called simply be writing the name of the definition
 5586: to be called. Normally a definition is invisible during its own
 5587: definition. If you want to write a directly recursive definition, you
 5588: can use @code{recursive} to make the current definition visible, or
 5589: @code{recurse} to call the current definition directly.
 5590: 
 5591: 
 5592: doc-recursive
 5593: doc-recurse
 5594: 
 5595: 
 5596: @comment TODO add example of the two recursion methods
 5597: @quotation
 5598: @progstyle
 5599: I prefer using @code{recursive} to @code{recurse}, because calling the
 5600: definition by name is more descriptive (if the name is well-chosen) than
 5601: the somewhat cryptic @code{recurse}.  E.g., in a quicksort
 5602: implementation, it is much better to read (and think) ``now sort the
 5603: partitions'' than to read ``now do a recursive call''.
 5604: @end quotation
 5605: 
 5606: For mutual recursion, use @code{Defer}red words, like this:
 5607: 
 5608: @example
 5609: Defer foo
 5610: 
 5611: : bar ( ... -- ... )
 5612:  ... foo ... ;
 5613: 
 5614: :noname ( ... -- ... )
 5615:  ... bar ... ;
 5616: IS foo
 5617: @end example
 5618: 
 5619: Deferred words are discussed in more detail in @ref{Deferred words}.
 5620: 
 5621: The current definition returns control to the calling definition when
 5622: the end of the definition is reached or @code{EXIT} is encountered.
 5623: 
 5624: doc-exit
 5625: doc-;s
 5626: 
 5627: 
 5628: @node Exception Handling,  , Calls and returns, Control Structures
 5629: @subsection Exception Handling
 5630: @cindex exceptions
 5631: 
 5632: @c quit is a very bad idea for error handling, 
 5633: @c because it does not translate into a THROW
 5634: @c it also does not belong into this chapter
 5635: 
 5636: If a word detects an error condition that it cannot handle, it can
 5637: @code{throw} an exception.  In the simplest case, this will terminate
 5638: your program, and report an appropriate error.
 5639: 
 5640: doc-throw
 5641: 
 5642: @code{Throw} consumes a cell-sized error number on the stack. There are
 5643: some predefined error numbers in ANS Forth (see @file{errors.fs}).  In
 5644: Gforth (and most other systems) you can use the iors produced by various
 5645: words as error numbers (e.g., a typical use of @code{allocate} is
 5646: @code{allocate throw}).  Gforth also provides the word @code{exception}
 5647: to define your own error numbers (with decent error reporting); an ANS
 5648: Forth version of this word (but without the error messages) is available
 5649: in @code{compat/except.fs}.  And finally, you can use your own error
 5650: numbers (anything outside the range -4095..0), but won't get nice error
 5651: messages, only numbers.  For example, try:
 5652: 
 5653: @example
 5654: -10 throw                    \ ANS defined
 5655: -267 throw                   \ system defined
 5656: s" my error" exception throw \ user defined
 5657: 7 throw                      \ arbitrary number
 5658: @end example
 5659: 
 5660: doc---exception-exception
 5661: 
 5662: A common idiom to @code{THROW} a specific error if a flag is true is
 5663: this:
 5664: 
 5665: @example
 5666: @code{( flag ) 0<> @i{errno} and throw}
 5667: @end example
 5668: 
 5669: Your program can provide exception handlers to catch exceptions.  An
 5670: exception handler can be used to correct the problem, or to clean up
 5671: some data structures and just throw the exception to the next exception
 5672: handler.  Note that @code{throw} jumps to the dynamically innermost
 5673: exception handler.  The system's exception handler is outermost, and just
 5674: prints an error and restarts command-line interpretation (or, in batch
 5675: mode (i.e., while processing the shell command line), leaves Gforth).
 5676: 
 5677: The ANS Forth way to catch exceptions is @code{catch}:
 5678: 
 5679: doc-catch
 5680: 
 5681: The most common use of exception handlers is to clean up the state when
 5682: an error happens.  E.g.,
 5683: 
 5684: @example
 5685: base @ >r hex \ actually the hex should be inside foo, or we h
 5686: ['] foo catch ( nerror|0 )
 5687: r> base !
 5688: ( nerror|0 ) throw \ pass it on
 5689: @end example
 5690: 
 5691: A use of @code{catch} for handling the error @code{myerror} might look
 5692: like this:
 5693: 
 5694: @example
 5695: ['] foo catch
 5696: CASE
 5697:   myerror OF ... ( do something about it ) ENDOF
 5698:   dup throw \ default: pass other errors on, do nothing on non-errors
 5699: ENDCASE
 5700: @end example
 5701: 
 5702: Having to wrap the code into a separate word is often cumbersome,
 5703: therefore Gforth provides an alternative syntax:
 5704: 
 5705: @example
 5706: TRY
 5707:   @i{code1}
 5708: RECOVER     \ optional
 5709:   @i{code2} \ optional
 5710: ENDTRY
 5711: @end example
 5712: 
 5713: This performs @i{Code1}.  If @i{code1} completes normally, execution
 5714: continues after the @code{endtry}.  If @i{Code1} throws, the stacks are
 5715: reset to the state during @code{try}, the throw value is pushed on the
 5716: data stack, and execution constinues at @i{code2}, and finally falls
 5717: through the @code{endtry} into the following code.
 5718: 
 5719: doc-try
 5720: doc-recover
 5721: doc-endtry
 5722: 
 5723: The cleanup example from above in this syntax:
 5724: 
 5725: @example
 5726: base @ >r TRY
 5727:   hex foo \ now the hex is placed correctly
 5728:   0       \ value for throw
 5729: RECOVER ENDTRY
 5730: r> base ! throw
 5731: @end example
 5732: 
 5733: And here's the error handling example:
 5734: 
 5735: @example
 5736: TRY
 5737:   foo
 5738: RECOVER
 5739:   CASE
 5740:     myerror OF ... ( do something about it ) ENDOF
 5741:     throw \ pass other errors on
 5742:   ENDCASE
 5743: ENDTRY
 5744: @end example
 5745: 
 5746: @progstyle
 5747: As usual, you should ensure that the stack depth is statically known at
 5748: the end: either after the @code{throw} for passing on errors, or after
 5749: the @code{ENDTRY} (or, if you use @code{catch}, after the end of the
 5750: selection construct for handling the error).
 5751: 
 5752: There are two alternatives to @code{throw}: @code{Abort"} is conditional
 5753: and you can provide an error message.  @code{Abort} just produces an
 5754: ``Aborted'' error.
 5755: 
 5756: The problem with these words is that exception handlers cannot
 5757: differentiate between different @code{abort"}s; they just look like
 5758: @code{-2 throw} to them (the error message cannot be accessed by
 5759: standard programs).  Similar @code{abort} looks like @code{-1 throw} to
 5760: exception handlers.
 5761: 
 5762: doc-abort"
 5763: doc-abort
 5764: 
 5765: 
 5766: 
 5767: @c -------------------------------------------------------------
 5768: @node Defining Words, Interpretation and Compilation Semantics, Control Structures, Words
 5769: @section Defining Words
 5770: @cindex defining words
 5771: 
 5772: Defining words are used to extend Forth by creating new entries in the dictionary.
 5773: 
 5774: @menu
 5775: * CREATE::                      
 5776: * Variables::                   Variables and user variables
 5777: * Constants::                   
 5778: * Values::                      Initialised variables
 5779: * Colon Definitions::           
 5780: * Anonymous Definitions::       Definitions without names
 5781: * Supplying names::             Passing definition names as strings
 5782: * User-defined Defining Words::  
 5783: * Deferred words::              Allow forward references
 5784: * Aliases::                     
 5785: @end menu
 5786: 
 5787: @node CREATE, Variables, Defining Words, Defining Words
 5788: @subsection @code{CREATE}
 5789: @cindex simple defining words
 5790: @cindex defining words, simple
 5791: 
 5792: Defining words are used to create new entries in the dictionary. The
 5793: simplest defining word is @code{CREATE}. @code{CREATE} is used like
 5794: this:
 5795: 
 5796: @example
 5797: CREATE new-word1
 5798: @end example
 5799: 
 5800: @code{CREATE} is a parsing word, i.e., it takes an argument from the
 5801: input stream (@code{new-word1} in our example).  It generates a
 5802: dictionary entry for @code{new-word1}. When @code{new-word1} is
 5803: executed, all that it does is leave an address on the stack. The address
 5804: represents the value of the data space pointer (@code{HERE}) at the time
 5805: that @code{new-word1} was defined. Therefore, @code{CREATE} is a way of
 5806: associating a name with the address of a region of memory.
 5807: 
 5808: doc-create
 5809: 
 5810: Note that in ANS Forth guarantees only for @code{create} that its body
 5811: is in dictionary data space (i.e., where @code{here}, @code{allot}
 5812: etc. work, @pxref{Dictionary allocation}).  Also, in ANS Forth only
 5813: @code{create}d words can be modified with @code{does>}
 5814: (@pxref{User-defined Defining Words}).  And in ANS Forth @code{>body}
 5815: can only be applied to @code{create}d words.
 5816: 
 5817: By extending this example to reserve some memory in data space, we end
 5818: up with something like a @i{variable}. Here are two different ways to do
 5819: it:
 5820: 
 5821: @example
 5822: CREATE new-word2 1 cells allot  \ reserve 1 cell - initial value undefined
 5823: CREATE new-word3 4 ,            \ reserve 1 cell and initialise it (to 4)
 5824: @end example
 5825: 
 5826: The variable can be examined and modified using @code{@@} (``fetch'') and
 5827: @code{!} (``store'') like this:
 5828: 
 5829: @example
 5830: new-word2 @@ .      \ get address, fetch from it and display
 5831: 1234 new-word2 !   \ new value, get address, store to it
 5832: @end example
 5833: 
 5834: @cindex arrays
 5835: A similar mechanism can be used to create arrays. For example, an
 5836: 80-character text input buffer:
 5837: 
 5838: @example
 5839: CREATE text-buf 80 chars allot
 5840: 
 5841: text-buf 0 chars c@@ \ the 1st character (offset 0)
 5842: text-buf 3 chars c@@ \ the 4th character (offset 3)
 5843: @end example
 5844: 
 5845: You can build arbitrarily complex data structures by allocating
 5846: appropriate areas of memory. For further discussions of this, and to
 5847: learn about some Gforth tools that make it easier,
 5848: @xref{Structures}.
 5849: 
 5850: 
 5851: @node Variables, Constants, CREATE, Defining Words
 5852: @subsection Variables
 5853: @cindex variables
 5854: 
 5855: The previous section showed how a sequence of commands could be used to
 5856: generate a variable.  As a final refinement, the whole code sequence can
 5857: be wrapped up in a defining word (pre-empting the subject of the next
 5858: section), making it easier to create new variables:
 5859: 
 5860: @example
 5861: : myvariableX ( "name" -- a-addr ) CREATE 1 cells allot ;
 5862: : myvariable0 ( "name" -- a-addr ) CREATE 0 , ;
 5863: 
 5864: myvariableX foo \ variable foo starts off with an unknown value
 5865: myvariable0 joe \ whilst joe is initialised to 0
 5866: 
 5867: 45 3 * foo !   \ set foo to 135
 5868: 1234 joe !     \ set joe to 1234
 5869: 3 joe +!       \ increment joe by 3.. to 1237
 5870: @end example
 5871: 
 5872: Not surprisingly, there is no need to define @code{myvariable}, since
 5873: Forth already has a definition @code{Variable}. ANS Forth does not
 5874: guarantee that a @code{Variable} is initialised when it is created
 5875: (i.e., it may behave like @code{myvariableX}). In contrast, Gforth's
 5876: @code{Variable} initialises the variable to 0 (i.e., it behaves exactly
 5877: like @code{myvariable0}). Forth also provides @code{2Variable} and
 5878: @code{fvariable} for double and floating-point variables, respectively
 5879: -- they are initialised to 0. and 0e in Gforth. If you use a @code{Variable} to
 5880: store a boolean, you can use @code{on} and @code{off} to toggle its
 5881: state.
 5882: 
 5883: doc-variable
 5884: doc-2variable
 5885: doc-fvariable
 5886: 
 5887: @cindex user variables
 5888: @cindex user space
 5889: The defining word @code{User} behaves in the same way as @code{Variable}.
 5890: The difference is that it reserves space in @i{user (data) space} rather
 5891: than normal data space. In a Forth system that has a multi-tasker, each
 5892: task has its own set of user variables.
 5893: 
 5894: doc-user
 5895: @c doc-udp
 5896: @c doc-uallot
 5897: 
 5898: @comment TODO is that stuff about user variables strictly correct? Is it
 5899: @comment just terminal tasks that have user variables?
 5900: @comment should document tasker.fs (with some examples) elsewhere
 5901: @comment in this manual, then expand on user space and user variables.
 5902: 
 5903: @node Constants, Values, Variables, Defining Words
 5904: @subsection Constants
 5905: @cindex constants
 5906: 
 5907: @code{Constant} allows you to declare a fixed value and refer to it by
 5908: name. For example:
 5909: 
 5910: @example
 5911: 12 Constant INCHES-PER-FOOT
 5912: 3E+08 fconstant SPEED-O-LIGHT
 5913: @end example
 5914: 
 5915: A @code{Variable} can be both read and written, so its run-time
 5916: behaviour is to supply an address through which its current value can be
 5917: manipulated. In contrast, the value of a @code{Constant} cannot be
 5918: changed once it has been declared@footnote{Well, often it can be -- but
 5919: not in a Standard, portable way. It's safer to use a @code{Value} (read
 5920: on).} so it's not necessary to supply the address -- it is more
 5921: efficient to return the value of the constant directly. That's exactly
 5922: what happens; the run-time effect of a constant is to put its value on
 5923: the top of the stack (You can find one
 5924: way of implementing @code{Constant} in @ref{User-defined Defining Words}).
 5925: 
 5926: Forth also provides @code{2Constant} and @code{fconstant} for defining
 5927: double and floating-point constants, respectively.
 5928: 
 5929: doc-constant
 5930: doc-2constant
 5931: doc-fconstant
 5932: 
 5933: @c that's too deep, and it's not necessarily true for all ANS Forths. - anton
 5934: @c nac-> How could that not be true in an ANS Forth? You can't define a
 5935: @c constant, use it and then delete the definition of the constant..
 5936: 
 5937: @c anton->An ANS Forth system can compile a constant to a literal; On
 5938: @c decompilation you would see only the number, just as if it had been used
 5939: @c in the first place.  The word will stay, of course, but it will only be
 5940: @c used by the text interpreter (no run-time duties, except when it is 
 5941: @c POSTPONEd or somesuch).
 5942: 
 5943: @c nac:
 5944: @c I agree that it's rather deep, but IMO it is an important difference
 5945: @c relative to other programming languages.. often it's annoying: it
 5946: @c certainly changes my programming style relative to C.
 5947: 
 5948: @c anton: In what way?
 5949: 
 5950: Constants in Forth behave differently from their equivalents in other
 5951: programming languages. In other languages, a constant (such as an EQU in
 5952: assembler or a #define in C) only exists at compile-time; in the
 5953: executable program the constant has been translated into an absolute
 5954: number and, unless you are using a symbolic debugger, it's impossible to
 5955: know what abstract thing that number represents. In Forth a constant has
 5956: an entry in the header space and remains there after the code that uses
 5957: it has been defined. In fact, it must remain in the dictionary since it
 5958: has run-time duties to perform. For example:
 5959: 
 5960: @example
 5961: 12 Constant INCHES-PER-FOOT
 5962: : FEET-TO-INCHES ( n1 -- n2 ) INCHES-PER-FOOT * ;
 5963: @end example
 5964: 
 5965: @cindex in-lining of constants
 5966: When @code{FEET-TO-INCHES} is executed, it will in turn execute the xt
 5967: associated with the constant @code{INCHES-PER-FOOT}. If you use
 5968: @code{see} to decompile the definition of @code{FEET-TO-INCHES}, you can
 5969: see that it makes a call to @code{INCHES-PER-FOOT}. Some Forth compilers
 5970: attempt to optimise constants by in-lining them where they are used. You
 5971: can force Gforth to in-line a constant like this:
 5972: 
 5973: @example
 5974: : FEET-TO-INCHES ( n1 -- n2 ) [ INCHES-PER-FOOT ] LITERAL * ;
 5975: @end example
 5976: 
 5977: If you use @code{see} to decompile @i{this} version of
 5978: @code{FEET-TO-INCHES}, you can see that @code{INCHES-PER-FOOT} is no
 5979: longer present. To understand how this works, read
 5980: @ref{Interpret/Compile states}, and @ref{Literals}.
 5981: 
 5982: In-lining constants in this way might improve execution time
 5983: fractionally, and can ensure that a constant is now only referenced at
 5984: compile-time. However, the definition of the constant still remains in
 5985: the dictionary. Some Forth compilers provide a mechanism for controlling
 5986: a second dictionary for holding transient words such that this second
 5987: dictionary can be deleted later in order to recover memory
 5988: space. However, there is no standard way of doing this.
 5989: 
 5990: 
 5991: @node Values, Colon Definitions, Constants, Defining Words
 5992: @subsection Values
 5993: @cindex values
 5994: 
 5995: A @code{Value} behaves like a @code{Constant}, but it can be changed.
 5996: @code{TO} is a parsing word that changes a @code{Values}.  In Gforth
 5997: (not in ANS Forth) you can access (and change) a @code{value} also with
 5998: @code{>body}.
 5999: 
 6000: Here are some
 6001: examples:
 6002: 
 6003: @example
 6004: 12 Value APPLES     \ Define APPLES with an initial value of 12
 6005: 34 TO APPLES        \ Change the value of APPLES. TO is a parsing word
 6006: 1 ' APPLES >body +! \ Increment APPLES.  Non-standard usage.
 6007: APPLES              \ puts 35 on the top of the stack.
 6008: @end example
 6009: 
 6010: doc-value
 6011: doc-to
 6012: 
 6013: 
 6014: 
 6015: @node Colon Definitions, Anonymous Definitions, Values, Defining Words
 6016: @subsection Colon Definitions
 6017: @cindex colon definitions
 6018: 
 6019: @example
 6020: : name ( ... -- ... )
 6021:     word1 word2 word3 ;
 6022: @end example
 6023: 
 6024: @noindent
 6025: Creates a word called @code{name} that, upon execution, executes
 6026: @code{word1 word2 word3}. @code{name} is a @dfn{(colon) definition}.
 6027: 
 6028: The explanation above is somewhat superficial. For simple examples of
 6029: colon definitions see @ref{Your first definition}.  For an in-depth
 6030: discussion of some of the issues involved, @xref{Interpretation and
 6031: Compilation Semantics}.
 6032: 
 6033: doc-:
 6034: doc-;
 6035: 
 6036: 
 6037: @node Anonymous Definitions, Supplying names, Colon Definitions, Defining Words
 6038: @subsection Anonymous Definitions
 6039: @cindex colon definitions
 6040: @cindex defining words without name
 6041: 
 6042: Sometimes you want to define an @dfn{anonymous word}; a word without a
 6043: name. You can do this with:
 6044: 
 6045: doc-:noname
 6046: 
 6047: This leaves the execution token for the word on the stack after the
 6048: closing @code{;}. Here's an example in which a deferred word is
 6049: initialised with an @code{xt} from an anonymous colon definition:
 6050: 
 6051: @example
 6052: Defer deferred
 6053: :noname ( ... -- ... )
 6054:   ... ;
 6055: IS deferred
 6056: @end example
 6057: 
 6058: @noindent
 6059: Gforth provides an alternative way of doing this, using two separate
 6060: words:
 6061: 
 6062: doc-noname
 6063: @cindex execution token of last defined word
 6064: doc-latestxt
 6065: 
 6066: @noindent
 6067: The previous example can be rewritten using @code{noname} and
 6068: @code{latestxt}:
 6069: 
 6070: @example
 6071: Defer deferred
 6072: noname : ( ... -- ... )
 6073:   ... ;
 6074: latestxt IS deferred
 6075: @end example
 6076: 
 6077: @noindent
 6078: @code{noname} works with any defining word, not just @code{:}.
 6079: 
 6080: @code{latestxt} also works when the last word was not defined as
 6081: @code{noname}.  It does not work for combined words, though.  It also has
 6082: the useful property that is is valid as soon as the header for a
 6083: definition has been built. Thus:
 6084: 
 6085: @example
 6086: latestxt . : foo [ latestxt . ] ; ' foo .
 6087: @end example
 6088: 
 6089: @noindent
 6090: prints 3 numbers; the last two are the same.
 6091: 
 6092: @node Supplying names, User-defined Defining Words, Anonymous Definitions, Defining Words
 6093: @subsection Supplying the name of a defined word
 6094: @cindex names for defined words
 6095: @cindex defining words, name given in a string
 6096: 
 6097: By default, a defining word takes the name for the defined word from the
 6098: input stream. Sometimes you want to supply the name from a string. You
 6099: can do this with:
 6100: 
 6101: doc-nextname
 6102: 
 6103: For example:
 6104: 
 6105: @example
 6106: s" foo" nextname create
 6107: @end example
 6108: 
 6109: @noindent
 6110: is equivalent to:
 6111: 
 6112: @example
 6113: create foo
 6114: @end example
 6115: 
 6116: @noindent
 6117: @code{nextname} works with any defining word.
 6118: 
 6119: 
 6120: @node User-defined Defining Words, Deferred words, Supplying names, Defining Words
 6121: @subsection User-defined Defining Words
 6122: @cindex user-defined defining words
 6123: @cindex defining words, user-defined
 6124: 
 6125: You can create a new defining word by wrapping defining-time code around
 6126: an existing defining word and putting the sequence in a colon
 6127: definition. 
 6128: 
 6129: @c anton: This example is very complex and leads in a quite different
 6130: @c direction from the CREATE-DOES> stuff that follows.  It should probably
 6131: @c be done elsewhere, or as a subsubsection of this subsection (or as a
 6132: @c subsection of Defining Words)
 6133: 
 6134: For example, suppose that you have a word @code{stats} that
 6135: gathers statistics about colon definitions given the @i{xt} of the
 6136: definition, and you want every colon definition in your application to
 6137: make a call to @code{stats}. You can define and use a new version of
 6138: @code{:} like this:
 6139: 
 6140: @example
 6141: : stats ( xt -- ) DUP ." (Gathering statistics for " . ." )"
 6142:   ... ;  \ other code
 6143: 
 6144: : my: : latestxt postpone literal ['] stats compile, ;
 6145: 
 6146: my: foo + - ;
 6147: @end example
 6148: 
 6149: When @code{foo} is defined using @code{my:} these steps occur:
 6150: 
 6151: @itemize @bullet
 6152: @item
 6153: @code{my:} is executed.
 6154: @item
 6155: The @code{:} within the definition (the one between @code{my:} and
 6156: @code{latestxt}) is executed, and does just what it always does; it parses
 6157: the input stream for a name, builds a dictionary header for the name
 6158: @code{foo} and switches @code{state} from interpret to compile.
 6159: @item
 6160: The word @code{latestxt} is executed. It puts the @i{xt} for the word that is
 6161: being defined -- @code{foo} -- onto the stack.
 6162: @item
 6163: The code that was produced by @code{postpone literal} is executed; this
 6164: causes the value on the stack to be compiled as a literal in the code
 6165: area of @code{foo}.
 6166: @item
 6167: The code @code{['] stats} compiles a literal into the definition of
 6168: @code{my:}. When @code{compile,} is executed, that literal -- the
 6169: execution token for @code{stats} -- is layed down in the code area of
 6170: @code{foo} , following the literal@footnote{Strictly speaking, the
 6171: mechanism that @code{compile,} uses to convert an @i{xt} into something
 6172: in the code area is implementation-dependent. A threaded implementation
 6173: might spit out the execution token directly whilst another
 6174: implementation might spit out a native code sequence.}.
 6175: @item
 6176: At this point, the execution of @code{my:} is complete, and control
 6177: returns to the text interpreter. The text interpreter is in compile
 6178: state, so subsequent text @code{+ -} is compiled into the definition of
 6179: @code{foo} and the @code{;} terminates the definition as always.
 6180: @end itemize
 6181: 
 6182: You can use @code{see} to decompile a word that was defined using
 6183: @code{my:} and see how it is different from a normal @code{:}
 6184: definition. For example:
 6185: 
 6186: @example
 6187: : bar + - ;  \ like foo but using : rather than my:
 6188: see bar
 6189: : bar
 6190:   + - ;
 6191: see foo
 6192: : foo
 6193:   107645672 stats + - ;
 6194: 
 6195: \ use ' foo . to show that 107645672 is the xt for foo
 6196: @end example
 6197: 
 6198: You can use techniques like this to make new defining words in terms of
 6199: @i{any} existing defining word.
 6200: 
 6201: 
 6202: @cindex defining defining words
 6203: @cindex @code{CREATE} ... @code{DOES>}
 6204: If you want the words defined with your defining words to behave
 6205: differently from words defined with standard defining words, you can
 6206: write your defining word like this:
 6207: 
 6208: @example
 6209: : def-word ( "name" -- )
 6210:     CREATE @i{code1}
 6211: DOES> ( ... -- ... )
 6212:     @i{code2} ;
 6213: 
 6214: def-word name
 6215: @end example
 6216: 
 6217: @cindex child words
 6218: This fragment defines a @dfn{defining word} @code{def-word} and then
 6219: executes it.  When @code{def-word} executes, it @code{CREATE}s a new
 6220: word, @code{name}, and executes the code @i{code1}. The code @i{code2}
 6221: is not executed at this time. The word @code{name} is sometimes called a
 6222: @dfn{child} of @code{def-word}.
 6223: 
 6224: When you execute @code{name}, the address of the body of @code{name} is
 6225: put on the data stack and @i{code2} is executed (the address of the body
 6226: of @code{name} is the address @code{HERE} returns immediately after the
 6227: @code{CREATE}, i.e., the address a @code{create}d word returns by
 6228: default).
 6229: 
 6230: @c anton:
 6231: @c www.dictionary.com says:
 6232: @c at·a·vism: 1.The reappearance of a characteristic in an organism after
 6233: @c several generations of absence, usually caused by the chance
 6234: @c recombination of genes.  2.An individual or a part that exhibits
 6235: @c atavism. Also called throwback.  3.The return of a trait or recurrence
 6236: @c of previous behavior after a period of absence.
 6237: @c
 6238: @c Doesn't seem to fit.
 6239: 
 6240: @c @cindex atavism in child words
 6241: You can use @code{def-word} to define a set of child words that behave
 6242: similarly; they all have a common run-time behaviour determined by
 6243: @i{code2}. Typically, the @i{code1} sequence builds a data area in the
 6244: body of the child word. The structure of the data is common to all
 6245: children of @code{def-word}, but the data values are specific -- and
 6246: private -- to each child word. When a child word is executed, the
 6247: address of its private data area is passed as a parameter on TOS to be
 6248: used and manipulated@footnote{It is legitimate both to read and write to
 6249: this data area.} by @i{code2}.
 6250: 
 6251: The two fragments of code that make up the defining words act (are
 6252: executed) at two completely separate times:
 6253: 
 6254: @itemize @bullet
 6255: @item
 6256: At @i{define time}, the defining word executes @i{code1} to generate a
 6257: child word
 6258: @item
 6259: At @i{child execution time}, when a child word is invoked, @i{code2}
 6260: is executed, using parameters (data) that are private and specific to
 6261: the child word.
 6262: @end itemize
 6263: 
 6264: Another way of understanding the behaviour of @code{def-word} and
 6265: @code{name} is to say that, if you make the following definitions:
 6266: @example
 6267: : def-word1 ( "name" -- )
 6268:     CREATE @i{code1} ;
 6269: 
 6270: : action1 ( ... -- ... )
 6271:     @i{code2} ;
 6272: 
 6273: def-word1 name1
 6274: @end example
 6275: 
 6276: @noindent
 6277: Then using @code{name1 action1} is equivalent to using @code{name}.
 6278: 
 6279: The classic example is that you can define @code{CONSTANT} in this way:
 6280: 
 6281: @example
 6282: : CONSTANT ( w "name" -- )
 6283:     CREATE ,
 6284: DOES> ( -- w )
 6285:     @@ ;
 6286: @end example
 6287: 
 6288: @comment There is a beautiful description of how this works and what
 6289: @comment it does in the Forthwrite 100th edition.. as well as an elegant
 6290: @comment commentary on the Counting Fruits problem.
 6291: 
 6292: When you create a constant with @code{5 CONSTANT five}, a set of
 6293: define-time actions take place; first a new word @code{five} is created,
 6294: then the value 5 is laid down in the body of @code{five} with
 6295: @code{,}. When @code{five} is executed, the address of the body is put on
 6296: the stack, and @code{@@} retrieves the value 5. The word @code{five} has
 6297: no code of its own; it simply contains a data field and a pointer to the
 6298: code that follows @code{DOES>} in its defining word. That makes words
 6299: created in this way very compact.
 6300: 
 6301: The final example in this section is intended to remind you that space
 6302: reserved in @code{CREATE}d words is @i{data} space and therefore can be
 6303: both read and written by a Standard program@footnote{Exercise: use this
 6304: example as a starting point for your own implementation of @code{Value}
 6305: and @code{TO} -- if you get stuck, investigate the behaviour of @code{'} and
 6306: @code{[']}.}:
 6307: 
 6308: @example
 6309: : foo ( "name" -- )
 6310:     CREATE -1 ,
 6311: DOES> ( -- )
 6312:     @@ . ;
 6313: 
 6314: foo first-word
 6315: foo second-word
 6316: 
 6317: 123 ' first-word >BODY !
 6318: @end example
 6319: 
 6320: If @code{first-word} had been a @code{CREATE}d word, we could simply
 6321: have executed it to get the address of its data field. However, since it
 6322: was defined to have @code{DOES>} actions, its execution semantics are to
 6323: perform those @code{DOES>} actions. To get the address of its data field
 6324: it's necessary to use @code{'} to get its xt, then @code{>BODY} to
 6325: translate the xt into the address of the data field.  When you execute
 6326: @code{first-word}, it will display @code{123}. When you execute
 6327: @code{second-word} it will display @code{-1}.
 6328: 
 6329: @cindex stack effect of @code{DOES>}-parts
 6330: @cindex @code{DOES>}-parts, stack effect
 6331: In the examples above the stack comment after the @code{DOES>} specifies
 6332: the stack effect of the defined words, not the stack effect of the
 6333: following code (the following code expects the address of the body on
 6334: the top of stack, which is not reflected in the stack comment). This is
 6335: the convention that I use and recommend (it clashes a bit with using
 6336: locals declarations for stack effect specification, though).
 6337: 
 6338: @menu
 6339: * CREATE..DOES> applications::  
 6340: * CREATE..DOES> details::       
 6341: * Advanced does> usage example::  
 6342: * Const-does>::                 
 6343: @end menu
 6344: 
 6345: @node CREATE..DOES> applications, CREATE..DOES> details, User-defined Defining Words, User-defined Defining Words
 6346: @subsubsection Applications of @code{CREATE..DOES>}
 6347: @cindex @code{CREATE} ... @code{DOES>}, applications
 6348: 
 6349: You may wonder how to use this feature. Here are some usage patterns:
 6350: 
 6351: @cindex factoring similar colon definitions
 6352: When you see a sequence of code occurring several times, and you can
 6353: identify a meaning, you will factor it out as a colon definition. When
 6354: you see similar colon definitions, you can factor them using
 6355: @code{CREATE..DOES>}. E.g., an assembler usually defines several words
 6356: that look very similar:
 6357: @example
 6358: : ori, ( reg-target reg-source n -- )
 6359:     0 asm-reg-reg-imm ;
 6360: : andi, ( reg-target reg-source n -- )
 6361:     1 asm-reg-reg-imm ;
 6362: @end example
 6363: 
 6364: @noindent
 6365: This could be factored with:
 6366: @example
 6367: : reg-reg-imm ( op-code -- )
 6368:     CREATE ,
 6369: DOES> ( reg-target reg-source n -- )
 6370:     @@ asm-reg-reg-imm ;
 6371: 
 6372: 0 reg-reg-imm ori,
 6373: 1 reg-reg-imm andi,
 6374: @end example
 6375: 
 6376: @cindex currying
 6377: Another view of @code{CREATE..DOES>} is to consider it as a crude way to
 6378: supply a part of the parameters for a word (known as @dfn{currying} in
 6379: the functional language community). E.g., @code{+} needs two
 6380: parameters. Creating versions of @code{+} with one parameter fixed can
 6381: be done like this:
 6382: 
 6383: @example
 6384: : curry+ ( n1 "name" -- )
 6385:     CREATE ,
 6386: DOES> ( n2 -- n1+n2 )
 6387:     @@ + ;
 6388: 
 6389:  3 curry+ 3+
 6390: -2 curry+ 2-
 6391: @end example
 6392: 
 6393: 
 6394: @node CREATE..DOES> details, Advanced does> usage example, CREATE..DOES> applications, User-defined Defining Words
 6395: @subsubsection The gory details of @code{CREATE..DOES>}
 6396: @cindex @code{CREATE} ... @code{DOES>}, details
 6397: 
 6398: doc-does>
 6399: 
 6400: @cindex @code{DOES>} in a separate definition
 6401: This means that you need not use @code{CREATE} and @code{DOES>} in the
 6402: same definition; you can put the @code{DOES>}-part in a separate
 6403: definition. This allows us to, e.g., select among different @code{DOES>}-parts:
 6404: @example
 6405: : does1 
 6406: DOES> ( ... -- ... )
 6407:     ... ;
 6408: 
 6409: : does2
 6410: DOES> ( ... -- ... )
 6411:     ... ;
 6412: 
 6413: : def-word ( ... -- ... )
 6414:     create ...
 6415:     IF
 6416:        does1
 6417:     ELSE
 6418:        does2
 6419:     ENDIF ;
 6420: @end example
 6421: 
 6422: In this example, the selection of whether to use @code{does1} or
 6423: @code{does2} is made at definition-time; at the time that the child word is
 6424: @code{CREATE}d.
 6425: 
 6426: @cindex @code{DOES>} in interpretation state
 6427: In a standard program you can apply a @code{DOES>}-part only if the last
 6428: word was defined with @code{CREATE}. In Gforth, the @code{DOES>}-part
 6429: will override the behaviour of the last word defined in any case. In a
 6430: standard program, you can use @code{DOES>} only in a colon
 6431: definition. In Gforth, you can also use it in interpretation state, in a
 6432: kind of one-shot mode; for example:
 6433: @example
 6434: CREATE name ( ... -- ... )
 6435:   @i{initialization}
 6436: DOES>
 6437:   @i{code} ;
 6438: @end example
 6439: 
 6440: @noindent
 6441: is equivalent to the standard:
 6442: @example
 6443: :noname
 6444: DOES>
 6445:     @i{code} ;
 6446: CREATE name EXECUTE ( ... -- ... )
 6447:     @i{initialization}
 6448: @end example
 6449: 
 6450: doc->body
 6451: 
 6452: @node Advanced does> usage example, Const-does>, CREATE..DOES> details, User-defined Defining Words
 6453: @subsubsection Advanced does> usage example
 6454: 
 6455: The MIPS disassembler (@file{arch/mips/disasm.fs}) contains many words
 6456: for disassembling instructions, that follow a very repetetive scheme:
 6457: 
 6458: @example
 6459: :noname @var{disasm-operands} s" @var{inst-name}" type ;
 6460: @var{entry-num} cells @var{table} + !
 6461: @end example
 6462: 
 6463: Of course, this inspires the idea to factor out the commonalities to
 6464: allow a definition like
 6465: 
 6466: @example
 6467: @var{disasm-operands} @var{entry-num} @var{table} define-inst @var{inst-name}
 6468: @end example
 6469: 
 6470: The parameters @var{disasm-operands} and @var{table} are usually
 6471: correlated.  Moreover, before I wrote the disassembler, there already
 6472: existed code that defines instructions like this:
 6473: 
 6474: @example
 6475: @var{entry-num} @var{inst-format} @var{inst-name}
 6476: @end example
 6477: 
 6478: This code comes from the assembler and resides in
 6479: @file{arch/mips/insts.fs}.
 6480: 
 6481: So I had to define the @var{inst-format} words that performed the scheme
 6482: above when executed.  At first I chose to use run-time code-generation:
 6483: 
 6484: @example
 6485: : @var{inst-format} ( entry-num "name" -- ; compiled code: addr w -- )
 6486:   :noname Postpone @var{disasm-operands}
 6487:   name Postpone sliteral Postpone type Postpone ;
 6488:   swap cells @var{table} + ! ;
 6489: @end example
 6490: 
 6491: Note that this supplies the other two parameters of the scheme above.
 6492: 
 6493: An alternative would have been to write this using
 6494: @code{create}/@code{does>}:
 6495: 
 6496: @example
 6497: : @var{inst-format} ( entry-num "name" -- )
 6498:   here name string, ( entry-num c-addr ) \ parse and save "name"
 6499:   noname create , ( entry-num )
 6500:   latestxt swap cells @var{table} + !
 6501: does> ( addr w -- )
 6502:   \ disassemble instruction w at addr
 6503:   @@ >r 
 6504:   @var{disasm-operands}
 6505:   r> count type ;
 6506: @end example
 6507: 
 6508: Somehow the first solution is simpler, mainly because it's simpler to
 6509: shift a string from definition-time to use-time with @code{sliteral}
 6510: than with @code{string,} and friends.
 6511: 
 6512: I wrote a lot of words following this scheme and soon thought about
 6513: factoring out the commonalities among them.  Note that this uses a
 6514: two-level defining word, i.e., a word that defines ordinary defining
 6515: words.
 6516: 
 6517: This time a solution involving @code{postpone} and friends seemed more
 6518: difficult (try it as an exercise), so I decided to use a
 6519: @code{create}/@code{does>} word; since I was already at it, I also used
 6520: @code{create}/@code{does>} for the lower level (try using
 6521: @code{postpone} etc. as an exercise), resulting in the following
 6522: definition:
 6523: 
 6524: @example
 6525: : define-format ( disasm-xt table-xt -- )
 6526:     \ define an instruction format that uses disasm-xt for
 6527:     \ disassembling and enters the defined instructions into table
 6528:     \ table-xt
 6529:     create 2,
 6530: does> ( u "inst" -- )
 6531:     \ defines an anonymous word for disassembling instruction inst,
 6532:     \ and enters it as u-th entry into table-xt
 6533:     2@@ swap here name string, ( u table-xt disasm-xt c-addr ) \ remember string
 6534:     noname create 2,      \ define anonymous word
 6535:     execute latestxt swap ! \ enter xt of defined word into table-xt
 6536: does> ( addr w -- )
 6537:     \ disassemble instruction w at addr
 6538:     2@@ >r ( addr w disasm-xt R: c-addr )
 6539:     execute ( R: c-addr ) \ disassemble operands
 6540:     r> count type ; \ print name 
 6541: @end example
 6542: 
 6543: Note that the tables here (in contrast to above) do the @code{cells +}
 6544: by themselves (that's why you have to pass an xt).  This word is used in
 6545: the following way:
 6546: 
 6547: @example
 6548: ' @var{disasm-operands} ' @var{table} define-format @var{inst-format}
 6549: @end example
 6550: 
 6551: As shown above, the defined instruction format is then used like this:
 6552: 
 6553: @example
 6554: @var{entry-num} @var{inst-format} @var{inst-name}
 6555: @end example
 6556: 
 6557: In terms of currying, this kind of two-level defining word provides the
 6558: parameters in three stages: first @var{disasm-operands} and @var{table},
 6559: then @var{entry-num} and @var{inst-name}, finally @code{addr w}, i.e.,
 6560: the instruction to be disassembled.  
 6561: 
 6562: Of course this did not quite fit all the instruction format names used
 6563: in @file{insts.fs}, so I had to define a few wrappers that conditioned
 6564: the parameters into the right form.
 6565: 
 6566: If you have trouble following this section, don't worry.  First, this is
 6567: involved and takes time (and probably some playing around) to
 6568: understand; second, this is the first two-level
 6569: @code{create}/@code{does>} word I have written in seventeen years of
 6570: Forth; and if I did not have @file{insts.fs} to start with, I may well
 6571: have elected to use just a one-level defining word (with some repeating
 6572: of parameters when using the defining word). So it is not necessary to
 6573: understand this, but it may improve your understanding of Forth.
 6574: 
 6575: 
 6576: @node Const-does>,  , Advanced does> usage example, User-defined Defining Words
 6577: @subsubsection @code{Const-does>}
 6578: 
 6579: A frequent use of @code{create}...@code{does>} is for transferring some
 6580: values from definition-time to run-time.  Gforth supports this use with
 6581: 
 6582: doc-const-does>
 6583: 
 6584: A typical use of this word is:
 6585: 
 6586: @example
 6587: : curry+ ( n1 "name" -- )
 6588: 1 0 CONST-DOES> ( n2 -- n1+n2 )
 6589:     + ;
 6590: 
 6591: 3 curry+ 3+
 6592: @end example
 6593: 
 6594: Here the @code{1 0} means that 1 cell and 0 floats are transferred from
 6595: definition to run-time.
 6596: 
 6597: The advantages of using @code{const-does>} are:
 6598: 
 6599: @itemize
 6600: 
 6601: @item
 6602: You don't have to deal with storing and retrieving the values, i.e.,
 6603: your program becomes more writable and readable.
 6604: 
 6605: @item
 6606: When using @code{does>}, you have to introduce a @code{@@} that cannot
 6607: be optimized away (because you could change the data using
 6608: @code{>body}...@code{!}); @code{const-does>} avoids this problem.
 6609: 
 6610: @end itemize
 6611: 
 6612: An ANS Forth implementation of @code{const-does>} is available in
 6613: @file{compat/const-does.fs}.
 6614: 
 6615: 
 6616: @node Deferred words, Aliases, User-defined Defining Words, Defining Words
 6617: @subsection Deferred words
 6618: @cindex deferred words
 6619: 
 6620: The defining word @code{Defer} allows you to define a word by name
 6621: without defining its behaviour; the definition of its behaviour is
 6622: deferred. Here are two situation where this can be useful:
 6623: 
 6624: @itemize @bullet
 6625: @item
 6626: Where you want to allow the behaviour of a word to be altered later, and
 6627: for all precompiled references to the word to change when its behaviour
 6628: is changed.
 6629: @item
 6630: For mutual recursion; @xref{Calls and returns}.
 6631: @end itemize
 6632: 
 6633: In the following example, @code{foo} always invokes the version of
 6634: @code{greet} that prints ``@code{Good morning}'' whilst @code{bar}
 6635: always invokes the version that prints ``@code{Hello}''. There is no way
 6636: of getting @code{foo} to use the later version without re-ordering the
 6637: source code and recompiling it.
 6638: 
 6639: @example
 6640: : greet ." Good morning" ;
 6641: : foo ... greet ... ;
 6642: : greet ." Hello" ;
 6643: : bar ... greet ... ;
 6644: @end example
 6645: 
 6646: This problem can be solved by defining @code{greet} as a @code{Defer}red
 6647: word. The behaviour of a @code{Defer}red word can be defined and
 6648: redefined at any time by using @code{IS} to associate the xt of a
 6649: previously-defined word with it. The previous example becomes:
 6650: 
 6651: @example
 6652: Defer greet ( -- )
 6653: : foo ... greet ... ;
 6654: : bar ... greet ... ;
 6655: : greet1 ( -- ) ." Good morning" ;
 6656: : greet2 ( -- ) ." Hello" ;
 6657: ' greet2 IS greet  \ make greet behave like greet2
 6658: @end example
 6659: 
 6660: @progstyle
 6661: You should write a stack comment for every deferred word, and put only
 6662: XTs into deferred words that conform to this stack effect.  Otherwise
 6663: it's too difficult to use the deferred word.
 6664: 
 6665: A deferred word can be used to improve the statistics-gathering example
 6666: from @ref{User-defined Defining Words}; rather than edit the
 6667: application's source code to change every @code{:} to a @code{my:}, do
 6668: this:
 6669: 
 6670: @example
 6671: : real: : ;     \ retain access to the original
 6672: defer :         \ redefine as a deferred word
 6673: ' my: IS :      \ use special version of :
 6674: \
 6675: \ load application here
 6676: \
 6677: ' real: IS :    \ go back to the original
 6678: @end example
 6679: 
 6680: 
 6681: One thing to note is that @code{IS} has special compilation semantics,
 6682: such that it parses the name at compile time (like @code{TO}):
 6683: 
 6684: @example
 6685: : set-greet ( xt -- )
 6686:   IS greet ;
 6687: 
 6688: ' greet1 set-greet
 6689: @end example
 6690: 
 6691: In situations where @code{IS} does not fit, use @code{defer!} instead.
 6692: 
 6693: A deferred word can only inherit execution semantics from the xt
 6694: (because that is all that an xt can represent -- for more discussion of
 6695: this @pxref{Tokens for Words}); by default it will have default
 6696: interpretation and compilation semantics deriving from this execution
 6697: semantics.  However, you can change the interpretation and compilation
 6698: semantics of the deferred word in the usual ways:
 6699: 
 6700: @example
 6701: : bar .... ; immediate
 6702: Defer fred immediate
 6703: Defer jim
 6704: 
 6705: ' bar IS jim  \ jim has default semantics
 6706: ' bar IS fred \ fred is immediate
 6707: @end example
 6708: 
 6709: doc-defer
 6710: doc-defer!
 6711: doc-is
 6712: doc-defer@
 6713: doc-action-of
 6714: @comment TODO document these: what's defers [is]
 6715: doc-defers
 6716: 
 6717: @c Use @code{words-deferred} to see a list of deferred words.
 6718: 
 6719: Definitions of these words (except @code{defers}) in ANS Forth are
 6720: provided in @file{compat/defer.fs}.
 6721: 
 6722: 
 6723: @node Aliases,  , Deferred words, Defining Words
 6724: @subsection Aliases
 6725: @cindex aliases
 6726: 
 6727: The defining word @code{Alias} allows you to define a word by name that
 6728: has the same behaviour as some other word. Here are two situation where
 6729: this can be useful:
 6730: 
 6731: @itemize @bullet
 6732: @item
 6733: When you want access to a word's definition from a different word list
 6734: (for an example of this, see the definition of the @code{Root} word list
 6735: in the Gforth source).
 6736: @item
 6737: When you want to create a synonym; a definition that can be known by
 6738: either of two names (for example, @code{THEN} and @code{ENDIF} are
 6739: aliases).
 6740: @end itemize
 6741: 
 6742: Like deferred words, an alias has default compilation and interpretation
 6743: semantics at the beginning (not the modifications of the other word),
 6744: but you can change them in the usual ways (@code{immediate},
 6745: @code{compile-only}). For example:
 6746: 
 6747: @example
 6748: : foo ... ; immediate
 6749: 
 6750: ' foo Alias bar \ bar is not an immediate word
 6751: ' foo Alias fooby immediate \ fooby is an immediate word
 6752: @end example
 6753: 
 6754: Words that are aliases have the same xt, different headers in the
 6755: dictionary, and consequently different name tokens (@pxref{Tokens for
 6756: Words}) and possibly different immediate flags.  An alias can only have
 6757: default or immediate compilation semantics; you can define aliases for
 6758: combined words with @code{interpret/compile:} -- see @ref{Combined words}.
 6759: 
 6760: doc-alias
 6761: 
 6762: 
 6763: @node Interpretation and Compilation Semantics, Tokens for Words, Defining Words, Words
 6764: @section Interpretation and Compilation Semantics
 6765: @cindex semantics, interpretation and compilation
 6766: 
 6767: @c !! state and ' are used without explanation
 6768: @c example for immediate/compile-only? or is the tutorial enough
 6769: 
 6770: @cindex interpretation semantics
 6771: The @dfn{interpretation semantics} of a (named) word are what the text
 6772: interpreter does when it encounters the word in interpret state. It also
 6773: appears in some other contexts, e.g., the execution token returned by
 6774: @code{' @i{word}} identifies the interpretation semantics of @i{word}
 6775: (in other words, @code{' @i{word} execute} is equivalent to
 6776: interpret-state text interpretation of @code{@i{word}}).
 6777: 
 6778: @cindex compilation semantics
 6779: The @dfn{compilation semantics} of a (named) word are what the text
 6780: interpreter does when it encounters the word in compile state. It also
 6781: appears in other contexts, e.g, @code{POSTPONE @i{word}}
 6782: compiles@footnote{In standard terminology, ``appends to the current
 6783: definition''.} the compilation semantics of @i{word}.
 6784: 
 6785: @cindex execution semantics
 6786: The standard also talks about @dfn{execution semantics}. They are used
 6787: only for defining the interpretation and compilation semantics of many
 6788: words. By default, the interpretation semantics of a word are to
 6789: @code{execute} its execution semantics, and the compilation semantics of
 6790: a word are to @code{compile,} its execution semantics.@footnote{In
 6791: standard terminology: The default interpretation semantics are its
 6792: execution semantics; the default compilation semantics are to append its
 6793: execution semantics to the execution semantics of the current
 6794: definition.}
 6795: 
 6796: Unnamed words (@pxref{Anonymous Definitions}) cannot be encountered by
 6797: the text interpreter, ticked, or @code{postpone}d, so they have no
 6798: interpretation or compilation semantics.  Their behaviour is represented
 6799: by their XT (@pxref{Tokens for Words}), and we call it execution
 6800: semantics, too.
 6801: 
 6802: @comment TODO expand, make it co-operate with new sections on text interpreter.
 6803: 
 6804: @cindex immediate words
 6805: @cindex compile-only words
 6806: You can change the semantics of the most-recently defined word:
 6807: 
 6808: 
 6809: doc-immediate
 6810: doc-compile-only
 6811: doc-restrict
 6812: 
 6813: By convention, words with non-default compilation semantics (e.g.,
 6814: immediate words) often have names surrounded with brackets (e.g.,
 6815: @code{[']}, @pxref{Execution token}).
 6816: 
 6817: Note that ticking (@code{'}) a compile-only word gives an error
 6818: (``Interpreting a compile-only word'').
 6819: 
 6820: @menu
 6821: * Combined words::              
 6822: @end menu
 6823: 
 6824: 
 6825: @node Combined words,  , Interpretation and Compilation Semantics, Interpretation and Compilation Semantics
 6826: @subsection Combined Words
 6827: @cindex combined words
 6828: 
 6829: Gforth allows you to define @dfn{combined words} -- words that have an
 6830: arbitrary combination of interpretation and compilation semantics.
 6831: 
 6832: doc-interpret/compile:
 6833: 
 6834: This feature was introduced for implementing @code{TO} and @code{S"}. I
 6835: recommend that you do not define such words, as cute as they may be:
 6836: they make it hard to get at both parts of the word in some contexts.
 6837: E.g., assume you want to get an execution token for the compilation
 6838: part. Instead, define two words, one that embodies the interpretation
 6839: part, and one that embodies the compilation part.  Once you have done
 6840: that, you can define a combined word with @code{interpret/compile:} for
 6841: the convenience of your users.
 6842: 
 6843: You might try to use this feature to provide an optimizing
 6844: implementation of the default compilation semantics of a word. For
 6845: example, by defining:
 6846: @example
 6847: :noname
 6848:    foo bar ;
 6849: :noname
 6850:    POSTPONE foo POSTPONE bar ;
 6851: interpret/compile: opti-foobar
 6852: @end example
 6853: 
 6854: @noindent
 6855: as an optimizing version of:
 6856: 
 6857: @example
 6858: : foobar
 6859:     foo bar ;
 6860: @end example
 6861: 
 6862: Unfortunately, this does not work correctly with @code{[compile]},
 6863: because @code{[compile]} assumes that the compilation semantics of all
 6864: @code{interpret/compile:} words are non-default. I.e., @code{[compile]
 6865: opti-foobar} would compile compilation semantics, whereas
 6866: @code{[compile] foobar} would compile interpretation semantics.
 6867: 
 6868: @cindex state-smart words (are a bad idea)
 6869: @anchor{state-smartness}
 6870: Some people try to use @dfn{state-smart} words to emulate the feature provided
 6871: by @code{interpret/compile:} (words are state-smart if they check
 6872: @code{STATE} during execution). E.g., they would try to code
 6873: @code{foobar} like this:
 6874: 
 6875: @example
 6876: : foobar
 6877:   STATE @@
 6878:   IF ( compilation state )
 6879:     POSTPONE foo POSTPONE bar
 6880:   ELSE
 6881:     foo bar
 6882:   ENDIF ; immediate
 6883: @end example
 6884: 
 6885: Although this works if @code{foobar} is only processed by the text
 6886: interpreter, it does not work in other contexts (like @code{'} or
 6887: @code{POSTPONE}). E.g., @code{' foobar} will produce an execution token
 6888: for a state-smart word, not for the interpretation semantics of the
 6889: original @code{foobar}; when you execute this execution token (directly
 6890: with @code{EXECUTE} or indirectly through @code{COMPILE,}) in compile
 6891: state, the result will not be what you expected (i.e., it will not
 6892: perform @code{foo bar}). State-smart words are a bad idea. Simply don't
 6893: write them@footnote{For a more detailed discussion of this topic, see
 6894: M. Anton Ertl,
 6895: @cite{@uref{http://www.complang.tuwien.ac.at/papers/ertl98.ps.gz,@code{State}-smartness---Why
 6896: it is Evil and How to Exorcise it}}, EuroForth '98.}!
 6897: 
 6898: @cindex defining words with arbitrary semantics combinations
 6899: It is also possible to write defining words that define words with
 6900: arbitrary combinations of interpretation and compilation semantics. In
 6901: general, they look like this:
 6902: 
 6903: @example
 6904: : def-word
 6905:     create-interpret/compile
 6906:     @i{code1}
 6907: interpretation>
 6908:     @i{code2}
 6909: <interpretation
 6910: compilation>
 6911:     @i{code3}
 6912: <compilation ;
 6913: @end example
 6914: 
 6915: For a @i{word} defined with @code{def-word}, the interpretation
 6916: semantics are to push the address of the body of @i{word} and perform
 6917: @i{code2}, and the compilation semantics are to push the address of
 6918: the body of @i{word} and perform @i{code3}. E.g., @code{constant}
 6919: can also be defined like this (except that the defined constants don't
 6920: behave correctly when @code{[compile]}d):
 6921: 
 6922: @example
 6923: : constant ( n "name" -- )
 6924:     create-interpret/compile
 6925:     ,
 6926: interpretation> ( -- n )
 6927:     @@
 6928: <interpretation
 6929: compilation> ( compilation. -- ; run-time. -- n )
 6930:     @@ postpone literal
 6931: <compilation ;
 6932: @end example
 6933: 
 6934: 
 6935: doc-create-interpret/compile
 6936: doc-interpretation>
 6937: doc-<interpretation
 6938: doc-compilation>
 6939: doc-<compilation
 6940: 
 6941: 
 6942: Words defined with @code{interpret/compile:} and
 6943: @code{create-interpret/compile} have an extended header structure that
 6944: differs from other words; however, unless you try to access them with
 6945: plain address arithmetic, you should not notice this. Words for
 6946: accessing the header structure usually know how to deal with this; e.g.,
 6947: @code{'} @i{word} @code{>body} also gives you the body of a word created
 6948: with @code{create-interpret/compile}.
 6949: 
 6950: 
 6951: @c -------------------------------------------------------------
 6952: @node Tokens for Words, Compiling words, Interpretation and Compilation Semantics, Words
 6953: @section Tokens for Words
 6954: @cindex tokens for words
 6955: 
 6956: This section describes the creation and use of tokens that represent
 6957: words.
 6958: 
 6959: @menu
 6960: * Execution token::             represents execution/interpretation semantics
 6961: * Compilation token::           represents compilation semantics
 6962: * Name token::                  represents named words
 6963: @end menu
 6964: 
 6965: @node Execution token, Compilation token, Tokens for Words, Tokens for Words
 6966: @subsection Execution token
 6967: 
 6968: @cindex xt
 6969: @cindex execution token
 6970: An @dfn{execution token} (@i{XT}) represents some behaviour of a word.
 6971: You can use @code{execute} to invoke this behaviour.
 6972: 
 6973: @cindex tick (')
 6974: You can use @code{'} to get an execution token that represents the
 6975: interpretation semantics of a named word:
 6976: 
 6977: @example
 6978: 5 ' .   ( n xt ) 
 6979: execute ( )      \ execute the xt (i.e., ".")
 6980: @end example
 6981: 
 6982: doc-'
 6983: 
 6984: @code{'} parses at run-time; there is also a word @code{[']} that parses
 6985: when it is compiled, and compiles the resulting XT:
 6986: 
 6987: @example
 6988: : foo ['] . execute ;
 6989: 5 foo
 6990: : bar ' execute ; \ by contrast,
 6991: 5 bar .           \ ' parses "." when bar executes
 6992: @end example
 6993: 
 6994: doc-[']
 6995: 
 6996: If you want the execution token of @i{word}, write @code{['] @i{word}}
 6997: in compiled code and @code{' @i{word}} in interpreted code.  Gforth's
 6998: @code{'} and @code{[']} behave somewhat unusually by complaining about
 6999: compile-only words (because these words have no interpretation
 7000: semantics).  You might get what you want by using @code{COMP' @i{word}
 7001: DROP} or @code{[COMP'] @i{word} DROP} (for details @pxref{Compilation
 7002: token}).
 7003: 
 7004: Another way to get an XT is @code{:noname} or @code{latestxt}
 7005: (@pxref{Anonymous Definitions}).  For anonymous words this gives an xt
 7006: for the only behaviour the word has (the execution semantics).  For
 7007: named words, @code{latestxt} produces an XT for the same behaviour it
 7008: would produce if the word was defined anonymously.
 7009: 
 7010: @example
 7011: :noname ." hello" ;
 7012: execute
 7013: @end example
 7014: 
 7015: An XT occupies one cell and can be manipulated like any other cell.
 7016: 
 7017: @cindex code field address
 7018: @cindex CFA
 7019: In ANS Forth the XT is just an abstract data type (i.e., defined by the
 7020: operations that produce or consume it).  For old hands: In Gforth, the
 7021: XT is implemented as a code field address (CFA).
 7022: 
 7023: doc-execute
 7024: doc-perform
 7025: 
 7026: @node Compilation token, Name token, Execution token, Tokens for Words
 7027: @subsection Compilation token
 7028: 
 7029: @cindex compilation token
 7030: @cindex CT (compilation token)
 7031: Gforth represents the compilation semantics of a named word by a
 7032: @dfn{compilation token} consisting of two cells: @i{w xt}. The top cell
 7033: @i{xt} is an execution token. The compilation semantics represented by
 7034: the compilation token can be performed with @code{execute}, which
 7035: consumes the whole compilation token, with an additional stack effect
 7036: determined by the represented compilation semantics.
 7037: 
 7038: At present, the @i{w} part of a compilation token is an execution token,
 7039: and the @i{xt} part represents either @code{execute} or
 7040: @code{compile,}@footnote{Depending upon the compilation semantics of the
 7041: word. If the word has default compilation semantics, the @i{xt} will
 7042: represent @code{compile,}. Otherwise (e.g., for immediate words), the
 7043: @i{xt} will represent @code{execute}.}. However, don't rely on that
 7044: knowledge, unless necessary; future versions of Gforth may introduce
 7045: unusual compilation tokens (e.g., a compilation token that represents
 7046: the compilation semantics of a literal).
 7047: 
 7048: You can perform the compilation semantics represented by the compilation
 7049: token with @code{execute}.  You can compile the compilation semantics
 7050: with @code{postpone,}. I.e., @code{COMP' @i{word} postpone,} is
 7051: equivalent to @code{postpone @i{word}}.
 7052: 
 7053: doc-[comp']
 7054: doc-comp'
 7055: doc-postpone,
 7056: 
 7057: @node Name token,  , Compilation token, Tokens for Words
 7058: @subsection Name token
 7059: 
 7060: @cindex name token
 7061: Gforth represents named words by the @dfn{name token}, (@i{nt}).  Name
 7062: token is an abstract data type that occurs as argument or result of the
 7063: words below.
 7064: 
 7065: @c !! put this elswhere?
 7066: @cindex name field address
 7067: @cindex NFA
 7068: The closest thing to the nt in older Forth systems is the name field
 7069: address (NFA), but there are significant differences: in older Forth
 7070: systems each word had a unique NFA, LFA, CFA and PFA (in this order, or
 7071: LFA, NFA, CFA, PFA) and there were words for getting from one to the
 7072: next.  In contrast, in Gforth 0@dots{}n nts correspond to one xt; there
 7073: is a link field in the structure identified by the name token, but
 7074: searching usually uses a hash table external to these structures; the
 7075: name in Gforth has a cell-wide count-and-flags field, and the nt is not
 7076: implemented as the address of that count field.
 7077: 
 7078: doc-find-name
 7079: doc-latest
 7080: doc->name
 7081: doc-name>int
 7082: doc-name?int
 7083: doc-name>comp
 7084: doc-name>string
 7085: doc-id.
 7086: doc-.name
 7087: doc-.id
 7088: 
 7089: @c ----------------------------------------------------------
 7090: @node Compiling words, The Text Interpreter, Tokens for Words, Words
 7091: @section Compiling words
 7092: @cindex compiling words
 7093: @cindex macros
 7094: 
 7095: In contrast to most other languages, Forth has no strict boundary
 7096: between compilation and run-time.  E.g., you can run arbitrary code
 7097: between defining words (or for computing data used by defining words
 7098: like @code{constant}). Moreover, @code{Immediate} (@pxref{Interpretation
 7099: and Compilation Semantics} and @code{[}...@code{]} (see below) allow
 7100: running arbitrary code while compiling a colon definition (exception:
 7101: you must not allot dictionary space).
 7102: 
 7103: @menu
 7104: * Literals::                    Compiling data values
 7105: * Macros::                      Compiling words
 7106: @end menu
 7107: 
 7108: @node Literals, Macros, Compiling words, Compiling words
 7109: @subsection Literals
 7110: @cindex Literals
 7111: 
 7112: The simplest and most frequent example is to compute a literal during
 7113: compilation.  E.g., the following definition prints an array of strings,
 7114: one string per line:
 7115: 
 7116: @example
 7117: : .strings ( addr u -- ) \ gforth
 7118:     2* cells bounds U+DO
 7119: 	cr i 2@@ type
 7120:     2 cells +LOOP ;  
 7121: @end example
 7122: 
 7123: With a simple-minded compiler like Gforth's, this computes @code{2
 7124: cells} on every loop iteration.  You can compute this value once and for
 7125: all at compile time and compile it into the definition like this:
 7126: 
 7127: @example
 7128: : .strings ( addr u -- ) \ gforth
 7129:     2* cells bounds U+DO
 7130: 	cr i 2@@ type
 7131:     [ 2 cells ] literal +LOOP ;  
 7132: @end example
 7133: 
 7134: @code{[} switches the text interpreter to interpret state (you will get
 7135: an @code{ok} prompt if you type this example interactively and insert a
 7136: newline between @code{[} and @code{]}), so it performs the
 7137: interpretation semantics of @code{2 cells}; this computes a number.
 7138: @code{]} switches the text interpreter back into compile state.  It then
 7139: performs @code{Literal}'s compilation semantics, which are to compile
 7140: this number into the current word.  You can decompile the word with
 7141: @code{see .strings} to see the effect on the compiled code.
 7142: 
 7143: You can also optimize the @code{2* cells} into @code{[ 2 cells ] literal
 7144: *} in this way.
 7145: 
 7146: doc-[
 7147: doc-]
 7148: doc-literal
 7149: doc-]L
 7150: 
 7151: There are also words for compiling other data types than single cells as
 7152: literals:
 7153: 
 7154: doc-2literal
 7155: doc-fliteral
 7156: doc-sliteral
 7157: 
 7158: @cindex colon-sys, passing data across @code{:}
 7159: @cindex @code{:}, passing data across
 7160: You might be tempted to pass data from outside a colon definition to the
 7161: inside on the data stack.  This does not work, because @code{:} puhes a
 7162: colon-sys, making stuff below unaccessible.  E.g., this does not work:
 7163: 
 7164: @example
 7165: 5 : foo literal ; \ error: "unstructured"
 7166: @end example
 7167: 
 7168: Instead, you have to pass the value in some other way, e.g., through a
 7169: variable:
 7170: 
 7171: @example
 7172: variable temp
 7173: 5 temp !
 7174: : foo [ temp @@ ] literal ;
 7175: @end example
 7176: 
 7177: 
 7178: @node Macros,  , Literals, Compiling words
 7179: @subsection Macros
 7180: @cindex Macros
 7181: @cindex compiling compilation semantics
 7182: 
 7183: @code{Literal} and friends compile data values into the current
 7184: definition.  You can also write words that compile other words into the
 7185: current definition.  E.g.,
 7186: 
 7187: @example
 7188: : compile-+ ( -- ) \ compiled code: ( n1 n2 -- n )
 7189:   POSTPONE + ;
 7190: 
 7191: : foo ( n1 n2 -- n )
 7192:   [ compile-+ ] ;
 7193: 1 2 foo .
 7194: @end example
 7195: 
 7196: This is equivalent to @code{: foo + ;} (@code{see foo} to check this).
 7197: What happens in this example?  @code{Postpone} compiles the compilation
 7198: semantics of @code{+} into @code{compile-+}; later the text interpreter
 7199: executes @code{compile-+} and thus the compilation semantics of +, which
 7200: compile (the execution semantics of) @code{+} into
 7201: @code{foo}.@footnote{A recent RFI answer requires that compiling words
 7202: should only be executed in compile state, so this example is not
 7203: guaranteed to work on all standard systems, but on any decent system it
 7204: will work.}
 7205: 
 7206: doc-postpone
 7207: doc-[compile]
 7208: 
 7209: Compiling words like @code{compile-+} are usually immediate (or similar)
 7210: so you do not have to switch to interpret state to execute them;
 7211: mopifying the last example accordingly produces:
 7212: 
 7213: @example
 7214: : [compile-+] ( compilation: --; interpretation: -- )
 7215:   \ compiled code: ( n1 n2 -- n )
 7216:   POSTPONE + ; immediate
 7217: 
 7218: : foo ( n1 n2 -- n )
 7219:   [compile-+] ;
 7220: 1 2 foo .
 7221: @end example
 7222: 
 7223: Immediate compiling words are similar to macros in other languages (in
 7224: particular, Lisp).  The important differences to macros in, e.g., C are:
 7225: 
 7226: @itemize @bullet
 7227: 
 7228: @item
 7229: You use the same language for defining and processing macros, not a
 7230: separate preprocessing language and processor.
 7231: 
 7232: @item
 7233: Consequently, the full power of Forth is available in macro definitions.
 7234: E.g., you can perform arbitrarily complex computations, or generate
 7235: different code conditionally or in a loop (e.g., @pxref{Advanced macros
 7236: Tutorial}).  This power is very useful when writing a parser generators
 7237: or other code-generating software.
 7238: 
 7239: @item
 7240: Macros defined using @code{postpone} etc. deal with the language at a
 7241: higher level than strings; name binding happens at macro definition
 7242: time, so you can avoid the pitfalls of name collisions that can happen
 7243: in C macros.  Of course, Forth is a liberal language and also allows to
 7244: shoot yourself in the foot with text-interpreted macros like
 7245: 
 7246: @example
 7247: : [compile-+] s" +" evaluate ; immediate
 7248: @end example
 7249: 
 7250: Apart from binding the name at macro use time, using @code{evaluate}
 7251: also makes your definition @code{state}-smart (@pxref{state-smartness}).
 7252: @end itemize
 7253: 
 7254: You may want the macro to compile a number into a word.  The word to do
 7255: it is @code{literal}, but you have to @code{postpone} it, so its
 7256: compilation semantics take effect when the macro is executed, not when
 7257: it is compiled:
 7258: 
 7259: @example
 7260: : [compile-5] ( -- ) \ compiled code: ( -- n )
 7261:   5 POSTPONE literal ; immediate
 7262: 
 7263: : foo [compile-5] ;
 7264: foo .
 7265: @end example
 7266: 
 7267: You may want to pass parameters to a macro, that the macro should
 7268: compile into the current definition.  If the parameter is a number, then
 7269: you can use @code{postpone literal} (similar for other values).
 7270: 
 7271: If you want to pass a word that is to be compiled, the usual way is to
 7272: pass an execution token and @code{compile,} it:
 7273: 
 7274: @example
 7275: : twice1 ( xt -- ) \ compiled code: ... -- ...
 7276:   dup compile, compile, ;
 7277: 
 7278: : 2+ ( n1 -- n2 )
 7279:   [ ' 1+ twice1 ] ;
 7280: @end example
 7281: 
 7282: doc-compile,
 7283: 
 7284: An alternative available in Gforth, that allows you to pass compile-only
 7285: words as parameters is to use the compilation token (@pxref{Compilation
 7286: token}).  The same example in this technique:
 7287: 
 7288: @example
 7289: : twice ( ... ct -- ... ) \ compiled code: ... -- ...
 7290:   2dup 2>r execute 2r> execute ;
 7291: 
 7292: : 2+ ( n1 -- n2 )
 7293:   [ comp' 1+ twice ] ;
 7294: @end example
 7295: 
 7296: In the example above @code{2>r} and @code{2r>} ensure that @code{twice}
 7297: works even if the executed compilation semantics has an effect on the
 7298: data stack.
 7299: 
 7300: You can also define complete definitions with these words; this provides
 7301: an alternative to using @code{does>} (@pxref{User-defined Defining
 7302: Words}).  E.g., instead of
 7303: 
 7304: @example
 7305: : curry+ ( n1 "name" -- )
 7306:     CREATE ,
 7307: DOES> ( n2 -- n1+n2 )
 7308:     @@ + ;
 7309: @end example
 7310: 
 7311: you could define
 7312: 
 7313: @example
 7314: : curry+ ( n1 "name" -- )
 7315:   \ name execution: ( n2 -- n1+n2 )
 7316:   >r : r> POSTPONE literal POSTPONE + POSTPONE ; ;
 7317: 
 7318: -3 curry+ 3-
 7319: see 3-
 7320: @end example
 7321: 
 7322: The sequence @code{>r : r>} is necessary, because @code{:} puts a
 7323: colon-sys on the data stack that makes everything below it unaccessible.
 7324: 
 7325: This way of writing defining words is sometimes more, sometimes less
 7326: convenient than using @code{does>} (@pxref{Advanced does> usage
 7327: example}).  One advantage of this method is that it can be optimized
 7328: better, because the compiler knows that the value compiled with
 7329: @code{literal} is fixed, whereas the data associated with a
 7330: @code{create}d word can be changed.
 7331: 
 7332: @c ----------------------------------------------------------
 7333: @node The Text Interpreter, The Input Stream, Compiling words, Words
 7334: @section  The Text Interpreter
 7335: @cindex interpreter - outer
 7336: @cindex text interpreter
 7337: @cindex outer interpreter
 7338: 
 7339: @c Should we really describe all these ugly details?  IMO the text
 7340: @c interpreter should be much cleaner, but that may not be possible within
 7341: @c ANS Forth. - anton
 7342: @c nac-> I wanted to explain how it works to show how you can exploit
 7343: @c it in your own programs. When I was writing a cross-compiler, figuring out
 7344: @c some of these gory details was very helpful to me. None of the textbooks
 7345: @c I've seen cover it, and the most modern Forth textbook -- Forth Inc's,
 7346: @c seems to positively avoid going into too much detail for some of
 7347: @c the internals.
 7348: 
 7349: @c anton: ok.  I wonder, though, if this is the right place; for some stuff
 7350: @c it is; for the ugly details, I would prefer another place.  I wonder
 7351: @c whether we should have a chapter before "Words" that describes some
 7352: @c basic concepts referred to in words, and a chapter after "Words" that
 7353: @c describes implementation details.
 7354: 
 7355: The text interpreter@footnote{This is an expanded version of the
 7356: material in @ref{Introducing the Text Interpreter}.} is an endless loop
 7357: that processes input from the current input device. It is also called
 7358: the outer interpreter, in contrast to the inner interpreter
 7359: (@pxref{Engine}) which executes the compiled Forth code on interpretive
 7360: implementations.
 7361: 
 7362: @cindex interpret state
 7363: @cindex compile state
 7364: The text interpreter operates in one of two states: @dfn{interpret
 7365: state} and @dfn{compile state}. The current state is defined by the
 7366: aptly-named variable @code{state}.
 7367: 
 7368: This section starts by describing how the text interpreter behaves when
 7369: it is in interpret state, processing input from the user input device --
 7370: the keyboard. This is the mode that a Forth system is in after it starts
 7371: up.
 7372: 
 7373: @cindex input buffer
 7374: @cindex terminal input buffer
 7375: The text interpreter works from an area of memory called the @dfn{input
 7376: buffer}@footnote{When the text interpreter is processing input from the
 7377: keyboard, this area of memory is called the @dfn{terminal input buffer}
 7378: (TIB) and is addressed by the (obsolescent) words @code{TIB} and
 7379: @code{#TIB}.}, which stores your keyboard input when you press the
 7380: @key{RET} key. Starting at the beginning of the input buffer, it skips
 7381: leading spaces (called @dfn{delimiters}) then parses a string (a
 7382: sequence of non-space characters) until it reaches either a space
 7383: character or the end of the buffer. Having parsed a string, it makes two
 7384: attempts to process it:
 7385: 
 7386: @cindex dictionary
 7387: @itemize @bullet
 7388: @item
 7389: It looks for the string in a @dfn{dictionary} of definitions. If the
 7390: string is found, the string names a @dfn{definition} (also known as a
 7391: @dfn{word}) and the dictionary search returns information that allows
 7392: the text interpreter to perform the word's @dfn{interpretation
 7393: semantics}. In most cases, this simply means that the word will be
 7394: executed.
 7395: @item
 7396: If the string is not found in the dictionary, the text interpreter
 7397: attempts to treat it as a number, using the rules described in
 7398: @ref{Number Conversion}. If the string represents a legal number in the
 7399: current radix, the number is pushed onto a parameter stack (the data
 7400: stack for integers, the floating-point stack for floating-point
 7401: numbers).
 7402: @end itemize
 7403: 
 7404: If both attempts fail, or if the word is found in the dictionary but has
 7405: no interpretation semantics@footnote{This happens if the word was
 7406: defined as @code{COMPILE-ONLY}.} the text interpreter discards the
 7407: remainder of the input buffer, issues an error message and waits for
 7408: more input. If one of the attempts succeeds, the text interpreter
 7409: repeats the parsing process until the whole of the input buffer has been
 7410: processed, at which point it prints the status message ``@code{ ok}''
 7411: and waits for more input.
 7412: 
 7413: @c anton: this should be in the input stream subsection (or below it)
 7414: 
 7415: @cindex parse area
 7416: The text interpreter keeps track of its position in the input buffer by
 7417: updating a variable called @code{>IN} (pronounced ``to-in''). The value
 7418: of @code{>IN} starts out as 0, indicating an offset of 0 from the start
 7419: of the input buffer. The region from offset @code{>IN @@} to the end of
 7420: the input buffer is called the @dfn{parse area}@footnote{In other words,
 7421: the text interpreter processes the contents of the input buffer by
 7422: parsing strings from the parse area until the parse area is empty.}.
 7423: This example shows how @code{>IN} changes as the text interpreter parses
 7424: the input buffer:
 7425: 
 7426: @example
 7427: : remaining >IN @@ SOURCE 2 PICK - -ROT + SWAP
 7428:   CR ." ->" TYPE ." <-" ; IMMEDIATE 
 7429: 
 7430: 1 2 3 remaining + remaining . 
 7431: 
 7432: : foo 1 2 3 remaining SWAP remaining ;
 7433: @end example
 7434: 
 7435: @noindent
 7436: The result is:
 7437: 
 7438: @example
 7439: ->+ remaining .<-
 7440: ->.<-5  ok
 7441: 
 7442: ->SWAP remaining ;-<
 7443: ->;<-  ok
 7444: @end example
 7445: 
 7446: @cindex parsing words
 7447: The value of @code{>IN} can also be modified by a word in the input
 7448: buffer that is executed by the text interpreter.  This means that a word
 7449: can ``trick'' the text interpreter into either skipping a section of the
 7450: input buffer@footnote{This is how parsing words work.} or into parsing a
 7451: section twice. For example:
 7452: 
 7453: @example
 7454: : lat ." <<foo>>" ;
 7455: : flat ." <<bar>>" >IN DUP @@ 3 - SWAP ! ;
 7456: @end example
 7457: 
 7458: @noindent
 7459: When @code{flat} is executed, this output is produced@footnote{Exercise
 7460: for the reader: what would happen if the @code{3} were replaced with
 7461: @code{4}?}:
 7462: 
 7463: @example
 7464: <<bar>><<foo>>
 7465: @end example
 7466: 
 7467: This technique can be used to work around some of the interoperability
 7468: problems of parsing words.  Of course, it's better to avoid parsing
 7469: words where possible.
 7470: 
 7471: @noindent
 7472: Two important notes about the behaviour of the text interpreter:
 7473: 
 7474: @itemize @bullet
 7475: @item
 7476: It processes each input string to completion before parsing additional
 7477: characters from the input buffer.
 7478: @item
 7479: It treats the input buffer as a read-only region (and so must your code).
 7480: @end itemize
 7481: 
 7482: @noindent
 7483: When the text interpreter is in compile state, its behaviour changes in
 7484: these ways:
 7485: 
 7486: @itemize @bullet
 7487: @item
 7488: If a parsed string is found in the dictionary, the text interpreter will
 7489: perform the word's @dfn{compilation semantics}. In most cases, this
 7490: simply means that the execution semantics of the word will be appended
 7491: to the current definition.
 7492: @item
 7493: When a number is encountered, it is compiled into the current definition
 7494: (as a literal) rather than being pushed onto a parameter stack.
 7495: @item
 7496: If an error occurs, @code{state} is modified to put the text interpreter
 7497: back into interpret state.
 7498: @item
 7499: Each time a line is entered from the keyboard, Gforth prints
 7500: ``@code{ compiled}'' rather than `` @code{ok}''.
 7501: @end itemize
 7502: 
 7503: @cindex text interpreter - input sources
 7504: When the text interpreter is using an input device other than the
 7505: keyboard, its behaviour changes in these ways:
 7506: 
 7507: @itemize @bullet
 7508: @item
 7509: When the parse area is empty, the text interpreter attempts to refill
 7510: the input buffer from the input source. When the input source is
 7511: exhausted, the input source is set back to the previous input source.
 7512: @item
 7513: It doesn't print out ``@code{ ok}'' or ``@code{ compiled}'' messages each
 7514: time the parse area is emptied.
 7515: @item
 7516: If an error occurs, the input source is set back to the user input
 7517: device.
 7518: @end itemize
 7519: 
 7520: You can read about this in more detail in @ref{Input Sources}.
 7521: 
 7522: doc->in
 7523: doc-source
 7524: 
 7525: doc-tib
 7526: doc-#tib
 7527: 
 7528: 
 7529: @menu
 7530: * Input Sources::               
 7531: * Number Conversion::           
 7532: * Interpret/Compile states::    
 7533: * Interpreter Directives::      
 7534: @end menu
 7535: 
 7536: @node Input Sources, Number Conversion, The Text Interpreter, The Text Interpreter
 7537: @subsection Input Sources
 7538: @cindex input sources
 7539: @cindex text interpreter - input sources
 7540: 
 7541: By default, the text interpreter processes input from the user input
 7542: device (the keyboard) when Forth starts up. The text interpreter can
 7543: process input from any of these sources:
 7544: 
 7545: @itemize @bullet
 7546: @item
 7547: The user input device -- the keyboard.
 7548: @item
 7549: A file, using the words described in @ref{Forth source files}.
 7550: @item
 7551: A block, using the words described in @ref{Blocks}.
 7552: @item
 7553: A text string, using @code{evaluate}.
 7554: @end itemize
 7555: 
 7556: A program can identify the current input device from the values of
 7557: @code{source-id} and @code{blk}.
 7558: 
 7559: 
 7560: doc-source-id
 7561: doc-blk
 7562: 
 7563: doc-save-input
 7564: doc-restore-input
 7565: 
 7566: doc-evaluate
 7567: doc-query
 7568: 
 7569: 
 7570: 
 7571: @node Number Conversion, Interpret/Compile states, Input Sources, The Text Interpreter
 7572: @subsection Number Conversion
 7573: @cindex number conversion
 7574: @cindex double-cell numbers, input format
 7575: @cindex input format for double-cell numbers
 7576: @cindex single-cell numbers, input format
 7577: @cindex input format for single-cell numbers
 7578: @cindex floating-point numbers, input format
 7579: @cindex input format for floating-point numbers
 7580: 
 7581: This section describes the rules that the text interpreter uses when it
 7582: tries to convert a string into a number.
 7583: 
 7584: Let <digit> represent any character that is a legal digit in the current
 7585: number base@footnote{For example, 0-9 when the number base is decimal or
 7586: 0-9, A-F when the number base is hexadecimal.}.
 7587: 
 7588: Let <decimal digit> represent any character in the range 0-9.
 7589: 
 7590: Let @{@i{a b}@} represent the @i{optional} presence of any of the characters
 7591: in the braces (@i{a} or @i{b} or neither).
 7592: 
 7593: Let * represent any number of instances of the previous character
 7594: (including none).
 7595: 
 7596: Let any other character represent itself.
 7597: 
 7598: @noindent
 7599: Now, the conversion rules are:
 7600: 
 7601: @itemize @bullet
 7602: @item
 7603: A string of the form <digit><digit>* is treated as a single-precision
 7604: (cell-sized) positive integer. Examples are 0 123 6784532 32343212343456 42
 7605: @item
 7606: A string of the form -<digit><digit>* is treated as a single-precision
 7607: (cell-sized) negative integer, and is represented using 2's-complement
 7608: arithmetic. Examples are -45 -5681 -0
 7609: @item
 7610: A string of the form <digit><digit>*.<digit>* is treated as a double-precision
 7611: (double-cell-sized) positive integer. Examples are 3465. 3.465 34.65
 7612: (all three of these represent the same number).
 7613: @item
 7614: A string of the form -<digit><digit>*.<digit>* is treated as a
 7615: double-precision (double-cell-sized) negative integer, and is
 7616: represented using 2's-complement arithmetic. Examples are -3465. -3.465
 7617: -34.65 (all three of these represent the same number).
 7618: @item
 7619: A string of the form @{+ -@}<decimal digit>@{.@}<decimal digit>*@{e
 7620: E@}@{+ -@}<decimal digit><decimal digit>* is treated as a floating-point
 7621: number. Examples are 1e 1e0 1.e 1.e0 +1e+0 (which all represent the same
 7622: number) +12.E-4
 7623: @end itemize
 7624: 
 7625: By default, the number base used for integer number conversion is given
 7626: by the contents of the variable @code{base}.  Note that a lot of
 7627: confusion can result from unexpected values of @code{base}.  If you
 7628: change @code{base} anywhere, make sure to save the old value and restore
 7629: it afterwards.  In general I recommend keeping @code{base} decimal, and
 7630: using the prefixes described below for the popular non-decimal bases.
 7631: 
 7632: doc-dpl
 7633: doc-base
 7634: doc-hex
 7635: doc-decimal
 7636: 
 7637: @cindex '-prefix for character strings
 7638: @cindex &-prefix for decimal numbers
 7639: @cindex #-prefix for decimal numbers
 7640: @cindex %-prefix for binary numbers
 7641: @cindex $-prefix for hexadecimal numbers
 7642: @cindex 0x-prefix for hexadecimal numbers
 7643: Gforth allows you to override the value of @code{base} by using a
 7644: prefix@footnote{Some Forth implementations provide a similar scheme by
 7645: implementing @code{$} etc. as parsing words that process the subsequent
 7646: number in the input stream and push it onto the stack. For example, see
 7647: @cite{Number Conversion and Literals}, by Wil Baden; Forth Dimensions
 7648: 20(3) pages 26--27. In such implementations, unlike in Gforth, a space
 7649: is required between the prefix and the number.} before the first digit
 7650: of an (integer) number. The following prefixes are supported:
 7651: 
 7652: @itemize @bullet
 7653: @item
 7654: @code{&} -- decimal
 7655: @item
 7656: @code{#} -- decimal
 7657: @item
 7658: @code{%} -- binary
 7659: @item
 7660: @code{$} -- hexadecimal
 7661: @item
 7662: @code{0x} -- hexadecimal, if base<33.
 7663: @item
 7664: @code{'} -- numeric value (e.g., ASCII code) of next character; an
 7665: optional @code{'} may be present after the character.
 7666: @end itemize
 7667: 
 7668: Here are some examples, with the equivalent decimal number shown after
 7669: in braces:
 7670: 
 7671: -$41 (-65), %1001101 (205), %1001.0001 (145 - a double-precision number),
 7672: 'A (65),
 7673: -'a' (-97),
 7674: &905 (905), $abc (2478), $ABC (2478).
 7675: 
 7676: @cindex number conversion - traps for the unwary
 7677: @noindent
 7678: Number conversion has a number of traps for the unwary:
 7679: 
 7680: @itemize @bullet
 7681: @item
 7682: You cannot determine the current number base using the code sequence
 7683: @code{base @@ .} -- the number base is always 10 in the current number
 7684: base. Instead, use something like @code{base @@ dec.}
 7685: @item
 7686: If the number base is set to a value greater than 14 (for example,
 7687: hexadecimal), the number 123E4 is ambiguous; the conversion rules allow
 7688: it to be intepreted as either a single-precision integer or a
 7689: floating-point number (Gforth treats it as an integer). The ambiguity
 7690: can be resolved by explicitly stating the sign of the mantissa and/or
 7691: exponent: 123E+4 or +123E4 -- if the number base is decimal, no
 7692: ambiguity arises; either representation will be treated as a
 7693: floating-point number.
 7694: @item
 7695: There is a word @code{bin} but it does @i{not} set the number base!
 7696: It is used to specify file types.
 7697: @item
 7698: ANS Forth requires the @code{.} of a double-precision number to be the
 7699: final character in the string.  Gforth allows the @code{.} to be
 7700: anywhere after the first digit.
 7701: @item
 7702: The number conversion process does not check for overflow.
 7703: @item
 7704: In an ANS Forth program @code{base} is required to be decimal when
 7705: converting floating-point numbers.  In Gforth, number conversion to
 7706: floating-point numbers always uses base &10, irrespective of the value
 7707: of @code{base}.
 7708: @end itemize
 7709: 
 7710: You can read numbers into your programs with the words described in
 7711: @ref{Input}.
 7712: 
 7713: @node Interpret/Compile states, Interpreter Directives, Number Conversion, The Text Interpreter
 7714: @subsection Interpret/Compile states
 7715: @cindex Interpret/Compile states
 7716: 
 7717: A standard program is not permitted to change @code{state}
 7718: explicitly. However, it can change @code{state} implicitly, using the
 7719: words @code{[} and @code{]}. When @code{[} is executed it switches
 7720: @code{state} to interpret state, and therefore the text interpreter
 7721: starts interpreting. When @code{]} is executed it switches @code{state}
 7722: to compile state and therefore the text interpreter starts
 7723: compiling. The most common usage for these words is for switching into
 7724: interpret state and back from within a colon definition; this technique
 7725: can be used to compile a literal (for an example, @pxref{Literals}) or
 7726: for conditional compilation (for an example, @pxref{Interpreter
 7727: Directives}).
 7728: 
 7729: 
 7730: @c This is a bad example: It's non-standard, and it's not necessary.
 7731: @c However, I can't think of a good example for switching into compile
 7732: @c state when there is no current word (@code{state}-smart words are not a
 7733: @c good reason).  So maybe we should use an example for switching into
 7734: @c interpret @code{state} in a colon def. - anton
 7735: @c nac-> I agree. I started out by putting in the example, then realised
 7736: @c that it was non-ANS, so wrote more words around it. I hope this
 7737: @c re-written version is acceptable to you. I do want to keep the example
 7738: @c as it is helpful for showing what is and what is not portable, particularly
 7739: @c where it outlaws a style in common use.
 7740: 
 7741: @c anton: it's more important to show what's portable.  After we have done
 7742: @c that, we can also show what's not.  In any case, I have written a
 7743: @c section Compiling Words which also deals with [ ].
 7744: 
 7745: @c  !! The following example does not work in Gforth 0.5.9 or later.
 7746: 
 7747: @c  @code{[} and @code{]} also give you the ability to switch into compile
 7748: @c  state and back, but we cannot think of any useful Standard application
 7749: @c  for this ability. Pre-ANS Forth textbooks have examples like this:
 7750: 
 7751: @c  @example
 7752: @c  : AA ." this is A" ;
 7753: @c  : BB ." this is B" ;
 7754: @c  : CC ." this is C" ;
 7755: 
 7756: @c  create table ] aa bb cc [
 7757: 
 7758: @c  : go ( n -- ) \ n is offset into table.. 0 for 1st entry
 7759: @c    cells table + @@ execute ;
 7760: @c  @end example
 7761: 
 7762: @c  This example builds a jump table; @code{0 go} will display ``@code{this
 7763: @c  is A}''. Using @code{[} and @code{]} in this example is equivalent to
 7764: @c  defining @code{table} like this:
 7765: 
 7766: @c  @example
 7767: @c  create table ' aa COMPILE, ' bb COMPILE, ' cc COMPILE,
 7768: @c  @end example
 7769: 
 7770: @c  The problem with this code is that the definition of @code{table} is not
 7771: @c  portable -- it @i{compile}s execution tokens into code space. Whilst it
 7772: @c  @i{may} work on systems where code space and data space co-incide, the
 7773: @c  Standard only allows data space to be assigned for a @code{CREATE}d
 7774: @c  word. In addition, the Standard only allows @code{@@} to access data
 7775: @c  space, whilst this example is using it to access code space. The only
 7776: @c  portable, Standard way to build this table is to build it in data space,
 7777: @c  like this:
 7778: 
 7779: @c  @example
 7780: @c  create table ' aa , ' bb , ' cc ,
 7781: @c  @end example
 7782: 
 7783: @c  doc-state
 7784: 
 7785: 
 7786: @node Interpreter Directives,  , Interpret/Compile states, The Text Interpreter
 7787: @subsection Interpreter Directives
 7788: @cindex interpreter directives
 7789: @cindex conditional compilation
 7790: 
 7791: These words are usually used in interpret state; typically to control
 7792: which parts of a source file are processed by the text
 7793: interpreter. There are only a few ANS Forth Standard words, but Gforth
 7794: supplements these with a rich set of immediate control structure words
 7795: to compensate for the fact that the non-immediate versions can only be
 7796: used in compile state (@pxref{Control Structures}). Typical usages:
 7797: 
 7798: @example
 7799: FALSE Constant HAVE-ASSEMBLER
 7800: .
 7801: .
 7802: HAVE-ASSEMBLER [IF]
 7803: : ASSEMBLER-FEATURE
 7804:   ...
 7805: ;
 7806: [ENDIF]
 7807: .
 7808: .
 7809: : SEE
 7810:   ... \ general-purpose SEE code
 7811:   [ HAVE-ASSEMBLER [IF] ]
 7812:   ... \ assembler-specific SEE code
 7813:   [ [ENDIF] ]
 7814: ;
 7815: @end example
 7816: 
 7817: 
 7818: doc-[IF]
 7819: doc-[ELSE]
 7820: doc-[THEN]
 7821: doc-[ENDIF]
 7822: 
 7823: doc-[IFDEF]
 7824: doc-[IFUNDEF]
 7825: 
 7826: doc-[?DO]
 7827: doc-[DO]
 7828: doc-[FOR]
 7829: doc-[LOOP]
 7830: doc-[+LOOP]
 7831: doc-[NEXT]
 7832: 
 7833: doc-[BEGIN]
 7834: doc-[UNTIL]
 7835: doc-[AGAIN]
 7836: doc-[WHILE]
 7837: doc-[REPEAT]
 7838: 
 7839: 
 7840: @c -------------------------------------------------------------
 7841: @node The Input Stream, Word Lists, The Text Interpreter, Words
 7842: @section The Input Stream
 7843: @cindex input stream
 7844: 
 7845: @c !! integrate this better with the "Text Interpreter" section
 7846: The text interpreter reads from the input stream, which can come from
 7847: several sources (@pxref{Input Sources}).  Some words, in particular
 7848: defining words, but also words like @code{'}, read parameters from the
 7849: input stream instead of from the stack.
 7850: 
 7851: Such words are called parsing words, because they parse the input
 7852: stream.  Parsing words are hard to use in other words, because it is
 7853: hard to pass program-generated parameters through the input stream.
 7854: They also usually have an unintuitive combination of interpretation and
 7855: compilation semantics when implemented naively, leading to various
 7856: approaches that try to produce a more intuitive behaviour
 7857: (@pxref{Combined words}).
 7858: 
 7859: It should be obvious by now that parsing words are a bad idea.  If you
 7860: want to implement a parsing word for convenience, also provide a factor
 7861: of the word that does not parse, but takes the parameters on the stack.
 7862: To implement the parsing word on top if it, you can use the following
 7863: words:
 7864: 
 7865: @c anton: these belong in the input stream section
 7866: doc-parse
 7867: doc-parse-name
 7868: doc-parse-word
 7869: doc-name
 7870: doc-word
 7871: doc-\"-parse
 7872: doc-refill
 7873: 
 7874: Conversely, if you have the bad luck (or lack of foresight) to have to
 7875: deal with parsing words without having such factors, how do you pass a
 7876: string that is not in the input stream to it?
 7877: 
 7878: doc-execute-parsing
 7879: 
 7880: A definition of this word in ANS Forth is provided in
 7881: @file{compat/execute-parsing.fs}.
 7882: 
 7883: If you want to run a parsing word on a file, the following word should
 7884: help:
 7885: 
 7886: doc-execute-parsing-file
 7887: 
 7888: @c -------------------------------------------------------------
 7889: @node Word Lists, Environmental Queries, The Input Stream, Words
 7890: @section Word Lists
 7891: @cindex word lists
 7892: @cindex header space
 7893: 
 7894: A wordlist is a list of named words; you can add new words and look up
 7895: words by name (and you can remove words in a restricted way with
 7896: markers).  Every named (and @code{reveal}ed) word is in one wordlist.
 7897: 
 7898: @cindex search order stack
 7899: The text interpreter searches the wordlists present in the search order
 7900: (a stack of wordlists), from the top to the bottom.  Within each
 7901: wordlist, the search starts conceptually at the newest word; i.e., if
 7902: two words in a wordlist have the same name, the newer word is found.
 7903: 
 7904: @cindex compilation word list
 7905: New words are added to the @dfn{compilation wordlist} (aka current
 7906: wordlist).
 7907: 
 7908: @cindex wid
 7909: A word list is identified by a cell-sized word list identifier (@i{wid})
 7910: in much the same way as a file is identified by a file handle. The
 7911: numerical value of the wid has no (portable) meaning, and might change
 7912: from session to session.
 7913: 
 7914: The ANS Forth ``Search order'' word set is intended to provide a set of
 7915: low-level tools that allow various different schemes to be
 7916: implemented. Gforth also provides @code{vocabulary}, a traditional Forth
 7917: word.  @file{compat/vocabulary.fs} provides an implementation in ANS
 7918: Forth.
 7919: 
 7920: @comment TODO: locals section refers to here, saying that every word list (aka
 7921: @comment vocabulary) has its own methods for searching etc. Need to document that.
 7922: @c anton: but better in a separate subsection on wordlist internals
 7923: 
 7924: @comment TODO: document markers, reveal, tables, mappedwordlist
 7925: 
 7926: @comment the gforthman- prefix is used to pick out the true definition of a
 7927: @comment word from the source files, rather than some alias.
 7928: 
 7929: doc-forth-wordlist
 7930: doc-definitions
 7931: doc-get-current
 7932: doc-set-current
 7933: doc-get-order
 7934: doc---gforthman-set-order
 7935: doc-wordlist
 7936: doc-table
 7937: doc->order
 7938: doc-previous
 7939: doc-also
 7940: doc---gforthman-forth
 7941: doc-only
 7942: doc---gforthman-order
 7943: 
 7944: doc-find
 7945: doc-search-wordlist
 7946: 
 7947: doc-words
 7948: doc-vlist
 7949: @c doc-words-deferred
 7950: 
 7951: @c doc-mappedwordlist @c map-structure undefined, implemantation-specific
 7952: doc-root
 7953: doc-vocabulary
 7954: doc-seal
 7955: doc-vocs
 7956: doc-current
 7957: doc-context
 7958: 
 7959: 
 7960: @menu
 7961: * Vocabularies::                
 7962: * Why use word lists?::         
 7963: * Word list example::           
 7964: @end menu
 7965: 
 7966: @node Vocabularies, Why use word lists?, Word Lists, Word Lists
 7967: @subsection Vocabularies
 7968: @cindex Vocabularies, detailed explanation
 7969: 
 7970: Here is an example of creating and using a new wordlist using ANS
 7971: Forth words:
 7972: 
 7973: @example
 7974: wordlist constant my-new-words-wordlist
 7975: : my-new-words get-order nip my-new-words-wordlist swap set-order ;
 7976: 
 7977: \ add it to the search order
 7978: also my-new-words
 7979: 
 7980: \ alternatively, add it to the search order and make it
 7981: \ the compilation word list
 7982: also my-new-words definitions
 7983: \ type "order" to see the problem
 7984: @end example
 7985: 
 7986: The problem with this example is that @code{order} has no way to
 7987: associate the name @code{my-new-words} with the wid of the word list (in
 7988: Gforth, @code{order} and @code{vocs} will display @code{???}  for a wid
 7989: that has no associated name). There is no Standard way of associating a
 7990: name with a wid.
 7991: 
 7992: In Gforth, this example can be re-coded using @code{vocabulary}, which
 7993: associates a name with a wid:
 7994: 
 7995: @example
 7996: vocabulary my-new-words
 7997: 
 7998: \ add it to the search order
 7999: also my-new-words
 8000: 
 8001: \ alternatively, add it to the search order and make it
 8002: \ the compilation word list
 8003: my-new-words definitions
 8004: \ type "order" to see that the problem is solved
 8005: @end example
 8006: 
 8007: 
 8008: @node Why use word lists?, Word list example, Vocabularies, Word Lists
 8009: @subsection Why use word lists?
 8010: @cindex word lists - why use them?
 8011: 
 8012: Here are some reasons why people use wordlists:
 8013: 
 8014: @itemize @bullet
 8015: 
 8016: @c anton: Gforth's hashing implementation makes the search speed
 8017: @c independent from the number of words.  But it is linear with the number
 8018: @c of wordlists that have to be searched, so in effect using more wordlists
 8019: @c actually slows down compilation.
 8020: 
 8021: @c @item
 8022: @c To improve compilation speed by reducing the number of header space
 8023: @c entries that must be searched. This is achieved by creating a new
 8024: @c word list that contains all of the definitions that are used in the
 8025: @c definition of a Forth system but which would not usually be used by
 8026: @c programs running on that system. That word list would be on the search
 8027: @c list when the Forth system was compiled but would be removed from the
 8028: @c search list for normal operation. This can be a useful technique for
 8029: @c low-performance systems (for example, 8-bit processors in embedded
 8030: @c systems) but is unlikely to be necessary in high-performance desktop
 8031: @c systems.
 8032: 
 8033: @item
 8034: To prevent a set of words from being used outside the context in which
 8035: they are valid. Two classic examples of this are an integrated editor
 8036: (all of the edit commands are defined in a separate word list; the
 8037: search order is set to the editor word list when the editor is invoked;
 8038: the old search order is restored when the editor is terminated) and an
 8039: integrated assembler (the op-codes for the machine are defined in a
 8040: separate word list which is used when a @code{CODE} word is defined).
 8041: 
 8042: @item
 8043: To organize the words of an application or library into a user-visible
 8044: set (in @code{forth-wordlist} or some other common wordlist) and a set
 8045: of helper words used just for the implementation (hidden in a separate
 8046: wordlist).  This keeps @code{words}' output smaller, separates
 8047: implementation and interface, and reduces the chance of name conflicts
 8048: within the common wordlist.
 8049: 
 8050: @item
 8051: To prevent a name-space clash between multiple definitions with the same
 8052: name. For example, when building a cross-compiler you might have a word
 8053: @code{IF} that generates conditional code for your target system. By
 8054: placing this definition in a different word list you can control whether
 8055: the host system's @code{IF} or the target system's @code{IF} get used in
 8056: any particular context by controlling the order of the word lists on the
 8057: search order stack.
 8058: 
 8059: @end itemize
 8060: 
 8061: The downsides of using wordlists are:
 8062: 
 8063: @itemize
 8064: 
 8065: @item
 8066: Debugging becomes more cumbersome.
 8067: 
 8068: @item
 8069: Name conflicts worked around with wordlists are still there, and you
 8070: have to arrange the search order carefully to get the desired results;
 8071: if you forget to do that, you get hard-to-find errors (as in any case
 8072: where you read the code differently from the compiler; @code{see} can
 8073: help seeing which of several possible words the name resolves to in such
 8074: cases).  @code{See} displays just the name of the words, not what
 8075: wordlist they belong to, so it might be misleading.  Using unique names
 8076: is a better approach to avoid name conflicts.
 8077: 
 8078: @item
 8079: You have to explicitly undo any changes to the search order.  In many
 8080: cases it would be more convenient if this happened implicitly.  Gforth
 8081: currently does not provide such a feature, but it may do so in the
 8082: future.
 8083: @end itemize
 8084: 
 8085: 
 8086: @node Word list example,  , Why use word lists?, Word Lists
 8087: @subsection Word list example
 8088: @cindex word lists - example
 8089: 
 8090: The following example is from the
 8091: @uref{http://www.complang.tuwien.ac.at/forth/garbage-collection.zip,
 8092: garbage collector} and uses wordlists to separate public words from
 8093: helper words:
 8094: 
 8095: @example
 8096: get-current ( wid )
 8097: vocabulary garbage-collector also garbage-collector definitions
 8098: ... \ define helper words
 8099: ( wid ) set-current \ restore original (i.e., public) compilation wordlist
 8100: ... \ define the public (i.e., API) words
 8101:     \ they can refer to the helper words
 8102: previous \ restore original search order (helper words become invisible)
 8103: @end example
 8104: 
 8105: @c -------------------------------------------------------------
 8106: @node Environmental Queries, Files, Word Lists, Words
 8107: @section Environmental Queries
 8108: @cindex environmental queries
 8109: 
 8110: ANS Forth introduced the idea of ``environmental queries'' as a way
 8111: for a program running on a system to determine certain characteristics of the system.
 8112: The Standard specifies a number of strings that might be recognised by a system.
 8113: 
 8114: The Standard requires that the header space used for environmental queries
 8115: be distinct from the header space used for definitions.
 8116: 
 8117: Typically, environmental queries are supported by creating a set of
 8118: definitions in a word list that is @i{only} used during environmental
 8119: queries; that is what Gforth does. There is no Standard way of adding
 8120: definitions to the set of recognised environmental queries, but any
 8121: implementation that supports the loading of optional word sets must have
 8122: some mechanism for doing this (after loading the word set, the
 8123: associated environmental query string must return @code{true}). In
 8124: Gforth, the word list used to honour environmental queries can be
 8125: manipulated just like any other word list.
 8126: 
 8127: 
 8128: doc-environment?
 8129: doc-environment-wordlist
 8130: 
 8131: doc-gforth
 8132: doc-os-class
 8133: 
 8134: 
 8135: Note that, whilst the documentation for (e.g.) @code{gforth} shows it
 8136: returning two items on the stack, querying it using @code{environment?}
 8137: will return an additional item; the @code{true} flag that shows that the
 8138: string was recognised.
 8139: 
 8140: @comment TODO Document the standard strings or note where they are documented herein
 8141: 
 8142: Here are some examples of using environmental queries:
 8143: 
 8144: @example
 8145: s" address-unit-bits" environment? 0=
 8146: [IF]
 8147:      cr .( environmental attribute address-units-bits unknown... ) cr
 8148: [ELSE]
 8149:      drop \ ensure balanced stack effect
 8150: [THEN]
 8151: 
 8152: \ this might occur in the prelude of a standard program that uses THROW
 8153: s" exception" environment? [IF]
 8154:    0= [IF]
 8155:       : throw abort" exception thrown" ;
 8156:    [THEN]
 8157: [ELSE] \ we don't know, so make sure
 8158:    : throw abort" exception thrown" ;
 8159: [THEN]
 8160: 
 8161: s" gforth" environment? [IF] .( Gforth version ) TYPE
 8162:                         [ELSE] .( Not Gforth..) [THEN]
 8163: 
 8164: \ a program using v*
 8165: s" gforth" environment? [IF]
 8166:   s" 0.5.0" compare 0< [IF] \ v* is a primitive since 0.5.0
 8167:    : v* ( f_addr1 nstride1 f_addr2 nstride2 ucount -- r )
 8168:      >r swap 2swap swap 0e r> 0 ?DO
 8169:        dup f@ over + 2swap dup f@ f* f+ over + 2swap
 8170:      LOOP
 8171:      2drop 2drop ; 
 8172:   [THEN]
 8173: [ELSE] \ 
 8174:   : v* ( f_addr1 nstride1 f_addr2 nstride2 ucount -- r )
 8175:   ...
 8176: [THEN]
 8177: @end example
 8178: 
 8179: Here is an example of adding a definition to the environment word list:
 8180: 
 8181: @example
 8182: get-current environment-wordlist set-current
 8183: true constant block
 8184: true constant block-ext
 8185: set-current
 8186: @end example
 8187: 
 8188: You can see what definitions are in the environment word list like this:
 8189: 
 8190: @example
 8191: environment-wordlist >order words previous
 8192: @end example
 8193: 
 8194: 
 8195: @c -------------------------------------------------------------
 8196: @node Files, Blocks, Environmental Queries, Words
 8197: @section Files
 8198: @cindex files
 8199: @cindex I/O - file-handling
 8200: 
 8201: Gforth provides facilities for accessing files that are stored in the
 8202: host operating system's file-system. Files that are processed by Gforth
 8203: can be divided into two categories:
 8204: 
 8205: @itemize @bullet
 8206: @item
 8207: Files that are processed by the Text Interpreter (@dfn{Forth source files}).
 8208: @item
 8209: Files that are processed by some other program (@dfn{general files}).
 8210: @end itemize
 8211: 
 8212: @menu
 8213: * Forth source files::          
 8214: * General files::               
 8215: * Search Paths::                
 8216: @end menu
 8217: 
 8218: @c -------------------------------------------------------------
 8219: @node Forth source files, General files, Files, Files
 8220: @subsection Forth source files
 8221: @cindex including files
 8222: @cindex Forth source files
 8223: 
 8224: The simplest way to interpret the contents of a file is to use one of
 8225: these two formats:
 8226: 
 8227: @example
 8228: include mysource.fs
 8229: s" mysource.fs" included
 8230: @end example
 8231: 
 8232: You usually want to include a file only if it is not included already
 8233: (by, say, another source file). In that case, you can use one of these
 8234: three formats:
 8235: 
 8236: @example
 8237: require mysource.fs
 8238: needs mysource.fs
 8239: s" mysource.fs" required
 8240: @end example
 8241: 
 8242: @cindex stack effect of included files
 8243: @cindex including files, stack effect
 8244: It is good practice to write your source files such that interpreting them
 8245: does not change the stack. Source files designed in this way can be used with
 8246: @code{required} and friends without complications. For example:
 8247: 
 8248: @example
 8249: 1024 require foo.fs drop
 8250: @end example
 8251: 
 8252: Here you want to pass the argument 1024 (e.g., a buffer size) to
 8253: @file{foo.fs}.  Interpreting @file{foo.fs} has the stack effect ( n -- n
 8254: ), which allows its use with @code{require}.  Of course with such
 8255: parameters to required files, you have to ensure that the first
 8256: @code{require} fits for all uses (i.e., @code{require} it early in the
 8257: master load file).
 8258: 
 8259: doc-include-file
 8260: doc-included
 8261: doc-included?
 8262: doc-include
 8263: doc-required
 8264: doc-require
 8265: doc-needs
 8266: @c doc-init-included-files @c internal
 8267: doc-sourcefilename
 8268: doc-sourceline#
 8269: 
 8270: A definition in ANS Forth for @code{required} is provided in
 8271: @file{compat/required.fs}.
 8272: 
 8273: @c -------------------------------------------------------------
 8274: @node General files, Search Paths, Forth source files, Files
 8275: @subsection General files
 8276: @cindex general files
 8277: @cindex file-handling
 8278: 
 8279: Files are opened/created by name and type. The following file access
 8280: methods (FAMs) are recognised:
 8281: 
 8282: @cindex fam (file access method)
 8283: doc-r/o
 8284: doc-r/w
 8285: doc-w/o
 8286: doc-bin
 8287: 
 8288: 
 8289: When a file is opened/created, it returns a file identifier,
 8290: @i{wfileid} that is used for all other file commands. All file
 8291: commands also return a status value, @i{wior}, that is 0 for a
 8292: successful operation and an implementation-defined non-zero value in the
 8293: case of an error.
 8294: 
 8295: 
 8296: doc-open-file
 8297: doc-create-file
 8298: 
 8299: doc-close-file
 8300: doc-delete-file
 8301: doc-rename-file
 8302: doc-read-file
 8303: doc-read-line
 8304: doc-key-file
 8305: doc-key?-file
 8306: doc-write-file
 8307: doc-write-line
 8308: doc-emit-file
 8309: doc-flush-file
 8310: 
 8311: doc-file-status
 8312: doc-file-position
 8313: doc-reposition-file
 8314: doc-file-size
 8315: doc-resize-file
 8316: 
 8317: doc-slurp-file
 8318: doc-slurp-fid
 8319: doc-stdin
 8320: doc-stdout
 8321: doc-stderr
 8322: 
 8323: @c ---------------------------------------------------------
 8324: @node Search Paths,  , General files, Files
 8325: @subsection Search Paths
 8326: @cindex path for @code{included}
 8327: @cindex file search path
 8328: @cindex @code{include} search path
 8329: @cindex search path for files
 8330: 
 8331: If you specify an absolute filename (i.e., a filename starting with
 8332: @file{/} or @file{~}, or with @file{:} in the second position (as in
 8333: @samp{C:...})) for @code{included} and friends, that file is included
 8334: just as you would expect.
 8335: 
 8336: If the filename starts with @file{./}, this refers to the directory that
 8337: the present file was @code{included} from.  This allows files to include
 8338: other files relative to their own position (irrespective of the current
 8339: working directory or the absolute position).  This feature is essential
 8340: for libraries consisting of several files, where a file may include
 8341: other files from the library.  It corresponds to @code{#include "..."}
 8342: in C. If the current input source is not a file, @file{.} refers to the
 8343: directory of the innermost file being included, or, if there is no file
 8344: being included, to the current working directory.
 8345: 
 8346: For relative filenames (not starting with @file{./}), Gforth uses a
 8347: search path similar to Forth's search order (@pxref{Word Lists}). It
 8348: tries to find the given filename in the directories present in the path,
 8349: and includes the first one it finds. There are separate search paths for
 8350: Forth source files and general files.  If the search path contains the
 8351: directory @file{.}, this refers to the directory of the current file, or
 8352: the working directory, as if the file had been specified with @file{./}.
 8353: 
 8354: Use @file{~+} to refer to the current working directory (as in the
 8355: @code{bash}).
 8356: 
 8357: @c anton: fold the following subsubsections into this subsection?
 8358: 
 8359: @menu
 8360: * Source Search Paths::         
 8361: * General Search Paths::        
 8362: @end menu
 8363: 
 8364: @c ---------------------------------------------------------
 8365: @node Source Search Paths, General Search Paths, Search Paths, Search Paths
 8366: @subsubsection Source Search Paths
 8367: @cindex search path control, source files
 8368: 
 8369: The search path is initialized when you start Gforth (@pxref{Invoking
 8370: Gforth}). You can display it and change it using @code{fpath} in
 8371: combination with the general path handling words.
 8372: 
 8373: doc-fpath
 8374: @c the functionality of the following words is easily available through
 8375: @c   fpath and the general path words.  The may go away.
 8376: @c doc-.fpath
 8377: @c doc-fpath+
 8378: @c doc-fpath=
 8379: @c doc-open-fpath-file
 8380: 
 8381: @noindent
 8382: Here is an example of using @code{fpath} and @code{require}:
 8383: 
 8384: @example
 8385: fpath path= /usr/lib/forth/|./
 8386: require timer.fs
 8387: @end example
 8388: 
 8389: 
 8390: @c ---------------------------------------------------------
 8391: @node General Search Paths,  , Source Search Paths, Search Paths
 8392: @subsubsection General Search Paths
 8393: @cindex search path control, source files
 8394: 
 8395: Your application may need to search files in several directories, like
 8396: @code{included} does. To facilitate this, Gforth allows you to define
 8397: and use your own search paths, by providing generic equivalents of the
 8398: Forth search path words:
 8399: 
 8400: doc-open-path-file
 8401: doc-path-allot
 8402: doc-clear-path
 8403: doc-also-path
 8404: doc-.path
 8405: doc-path+
 8406: doc-path=
 8407: 
 8408: @c anton: better define a word for it, say "path-allot ( ucount -- path-addr )
 8409: 
 8410: Here's an example of creating an empty search path:
 8411: @c
 8412: @example
 8413: create mypath 500 path-allot \ maximum length 500 chars (is checked)
 8414: @end example
 8415: 
 8416: @c -------------------------------------------------------------
 8417: @node Blocks, Other I/O, Files, Words
 8418: @section Blocks
 8419: @cindex I/O - blocks
 8420: @cindex blocks
 8421: 
 8422: When you run Gforth on a modern desk-top computer, it runs under the
 8423: control of an operating system which provides certain services.  One of
 8424: these services is @var{file services}, which allows Forth source code
 8425: and data to be stored in files and read into Gforth (@pxref{Files}).
 8426: 
 8427: Traditionally, Forth has been an important programming language on
 8428: systems where it has interfaced directly to the underlying hardware with
 8429: no intervening operating system. Forth provides a mechanism, called
 8430: @dfn{blocks}, for accessing mass storage on such systems.
 8431: 
 8432: A block is a 1024-byte data area, which can be used to hold data or
 8433: Forth source code. No structure is imposed on the contents of the
 8434: block. A block is identified by its number; blocks are numbered
 8435: contiguously from 1 to an implementation-defined maximum.
 8436: 
 8437: A typical system that used blocks but no operating system might use a
 8438: single floppy-disk drive for mass storage, with the disks formatted to
 8439: provide 256-byte sectors. Blocks would be implemented by assigning the
 8440: first four sectors of the disk to block 1, the second four sectors to
 8441: block 2 and so on, up to the limit of the capacity of the disk. The disk
 8442: would not contain any file system information, just the set of blocks.
 8443: 
 8444: @cindex blocks file
 8445: On systems that do provide file services, blocks are typically
 8446: implemented by storing a sequence of blocks within a single @dfn{blocks
 8447: file}.  The size of the blocks file will be an exact multiple of 1024
 8448: bytes, corresponding to the number of blocks it contains. This is the
 8449: mechanism that Gforth uses.
 8450: 
 8451: @cindex @file{blocks.fb}
 8452: Only one blocks file can be open at a time. If you use block words without
 8453: having specified a blocks file, Gforth defaults to the blocks file
 8454: @file{blocks.fb}. Gforth uses the Forth search path when attempting to
 8455: locate a blocks file (@pxref{Source Search Paths}).
 8456: 
 8457: @cindex block buffers
 8458: When you read and write blocks under program control, Gforth uses a
 8459: number of @dfn{block buffers} as intermediate storage. These buffers are
 8460: not used when you use @code{load} to interpret the contents of a block.
 8461: 
 8462: The behaviour of the block buffers is analagous to that of a cache.
 8463: Each block buffer has three states:
 8464: 
 8465: @itemize @bullet
 8466: @item
 8467: Unassigned
 8468: @item
 8469: Assigned-clean
 8470: @item
 8471: Assigned-dirty
 8472: @end itemize
 8473: 
 8474: Initially, all block buffers are @i{unassigned}. In order to access a
 8475: block, the block (specified by its block number) must be assigned to a
 8476: block buffer.
 8477: 
 8478: The assignment of a block to a block buffer is performed by @code{block}
 8479: or @code{buffer}. Use @code{block} when you wish to modify the existing
 8480: contents of a block. Use @code{buffer} when you don't care about the
 8481: existing contents of the block@footnote{The ANS Forth definition of
 8482: @code{buffer} is intended not to cause disk I/O; if the data associated
 8483: with the particular block is already stored in a block buffer due to an
 8484: earlier @code{block} command, @code{buffer} will return that block
 8485: buffer and the existing contents of the block will be
 8486: available. Otherwise, @code{buffer} will simply assign a new, empty
 8487: block buffer for the block.}.
 8488: 
 8489: Once a block has been assigned to a block buffer using @code{block} or
 8490: @code{buffer}, that block buffer becomes the @i{current block
 8491: buffer}. Data may only be manipulated (read or written) within the
 8492: current block buffer.
 8493: 
 8494: When the contents of the current block buffer has been modified it is
 8495: necessary, @emph{before calling @code{block} or @code{buffer} again}, to
 8496: either abandon the changes (by doing nothing) or mark the block as
 8497: changed (assigned-dirty), using @code{update}. Using @code{update} does
 8498: not change the blocks file; it simply changes a block buffer's state to
 8499: @i{assigned-dirty}.  The block will be written implicitly when it's
 8500: buffer is needed for another block, or explicitly by @code{flush} or
 8501: @code{save-buffers}.
 8502: 
 8503: word @code{Flush} writes all @i{assigned-dirty} blocks back to the
 8504: blocks file on disk. Leaving Gforth with @code{bye} also performs a
 8505: @code{flush}.
 8506: 
 8507: In Gforth, @code{block} and @code{buffer} use a @i{direct-mapped}
 8508: algorithm to assign a block buffer to a block. That means that any
 8509: particular block can only be assigned to one specific block buffer,
 8510: called (for the particular operation) the @i{victim buffer}. If the
 8511: victim buffer is @i{unassigned} or @i{assigned-clean} it is allocated to
 8512: the new block immediately. If it is @i{assigned-dirty} its current
 8513: contents are written back to the blocks file on disk before it is
 8514: allocated to the new block.
 8515: 
 8516: Although no structure is imposed on the contents of a block, it is
 8517: traditional to display the contents as 16 lines each of 64 characters.  A
 8518: block provides a single, continuous stream of input (for example, it
 8519: acts as a single parse area) -- there are no end-of-line characters
 8520: within a block, and no end-of-file character at the end of a
 8521: block. There are two consequences of this:
 8522: 
 8523: @itemize @bullet
 8524: @item
 8525: The last character of one line wraps straight into the first character
 8526: of the following line
 8527: @item
 8528: The word @code{\} -- comment to end of line -- requires special
 8529: treatment; in the context of a block it causes all characters until the
 8530: end of the current 64-character ``line'' to be ignored.
 8531: @end itemize
 8532: 
 8533: In Gforth, when you use @code{block} with a non-existent block number,
 8534: the current blocks file will be extended to the appropriate size and the
 8535: block buffer will be initialised with spaces.
 8536: 
 8537: Gforth includes a simple block editor (type @code{use blocked.fb 0 list}
 8538: for details) but doesn't encourage the use of blocks; the mechanism is
 8539: only provided for backward compatibility -- ANS Forth requires blocks to
 8540: be available when files are.
 8541: 
 8542: Common techniques that are used when working with blocks include:
 8543: 
 8544: @itemize @bullet
 8545: @item
 8546: A screen editor that allows you to edit blocks without leaving the Forth
 8547: environment.
 8548: @item
 8549: Shadow screens; where every code block has an associated block
 8550: containing comments (for example: code in odd block numbers, comments in
 8551: even block numbers). Typically, the block editor provides a convenient
 8552: mechanism to toggle between code and comments.
 8553: @item
 8554: Load blocks; a single block (typically block 1) contains a number of
 8555: @code{thru} commands which @code{load} the whole of the application.
 8556: @end itemize
 8557: 
 8558: See Frank Sergeant's Pygmy Forth to see just how well blocks can be
 8559: integrated into a Forth programming environment.
 8560: 
 8561: @comment TODO what about errors on open-blocks?
 8562: 
 8563: doc-open-blocks
 8564: doc-use
 8565: doc-block-offset
 8566: doc-get-block-fid
 8567: doc-block-position
 8568: 
 8569: doc-list
 8570: doc-scr
 8571: 
 8572: doc---gforthman-block
 8573: doc-buffer
 8574: 
 8575: doc-empty-buffers
 8576: doc-empty-buffer
 8577: doc-update
 8578: doc-updated?
 8579: doc-save-buffers
 8580: doc-save-buffer
 8581: doc-flush
 8582: 
 8583: doc-load
 8584: doc-thru
 8585: doc-+load
 8586: doc-+thru
 8587: doc---gforthman--->
 8588: doc-block-included
 8589: 
 8590: 
 8591: @c -------------------------------------------------------------
 8592: @node Other I/O, OS command line arguments, Blocks, Words
 8593: @section Other I/O
 8594: @cindex I/O - keyboard and display
 8595: 
 8596: @menu
 8597: * Simple numeric output::       Predefined formats
 8598: * Formatted numeric output::    Formatted (pictured) output
 8599: * String Formats::              How Forth stores strings in memory
 8600: * Displaying characters and strings::  Other stuff
 8601: * Input::                       Input
 8602: * Pipes::                       How to create your own pipes
 8603: * Xchars and Unicode::          Non-ASCII characters
 8604: @end menu
 8605: 
 8606: @node Simple numeric output, Formatted numeric output, Other I/O, Other I/O
 8607: @subsection Simple numeric output
 8608: @cindex numeric output - simple/free-format
 8609: 
 8610: The simplest output functions are those that display numbers from the
 8611: data or floating-point stacks. Floating-point output is always displayed
 8612: using base 10. Numbers displayed from the data stack use the value stored
 8613: in @code{base}.
 8614: 
 8615: 
 8616: doc-.
 8617: doc-dec.
 8618: doc-hex.
 8619: doc-u.
 8620: doc-.r
 8621: doc-u.r
 8622: doc-d.
 8623: doc-ud.
 8624: doc-d.r
 8625: doc-ud.r
 8626: doc-f.
 8627: doc-fe.
 8628: doc-fs.
 8629: doc-f.rdp
 8630: 
 8631: Examples of printing the number 1234.5678E23 in the different floating-point output
 8632: formats are shown below:
 8633: 
 8634: @example
 8635: f. 123456779999999000000000000.
 8636: fe. 123.456779999999E24
 8637: fs. 1.23456779999999E26
 8638: @end example
 8639: 
 8640: 
 8641: @node Formatted numeric output, String Formats, Simple numeric output, Other I/O
 8642: @subsection Formatted numeric output
 8643: @cindex formatted numeric output
 8644: @cindex pictured numeric output
 8645: @cindex numeric output - formatted
 8646: 
 8647: Forth traditionally uses a technique called @dfn{pictured numeric
 8648: output} for formatted printing of integers.  In this technique, digits
 8649: are extracted from the number (using the current output radix defined by
 8650: @code{base}), converted to ASCII codes and appended to a string that is
 8651: built in a scratch-pad area of memory (@pxref{core-idef,
 8652: Implementation-defined options, Implementation-defined
 8653: options}). Arbitrary characters can be appended to the string during the
 8654: extraction process. The completed string is specified by an address
 8655: and length and can be manipulated (@code{TYPE}ed, copied, modified)
 8656: under program control.
 8657: 
 8658: All of the integer output words described in the previous section
 8659: (@pxref{Simple numeric output}) are implemented in Gforth using pictured
 8660: numeric output.
 8661: 
 8662: Three important things to remember about pictured numeric output:
 8663: 
 8664: @itemize @bullet
 8665: @item
 8666: It always operates on double-precision numbers; to display a
 8667: single-precision number, convert it first (for ways of doing this
 8668: @pxref{Double precision}).
 8669: @item
 8670: It always treats the double-precision number as though it were
 8671: unsigned. The examples below show ways of printing signed numbers.
 8672: @item
 8673: The string is built up from right to left; least significant digit first.
 8674: @end itemize
 8675: 
 8676: 
 8677: doc-<#
 8678: doc-<<#
 8679: doc-#
 8680: doc-#s
 8681: doc-hold
 8682: doc-sign
 8683: doc-#>
 8684: doc-#>>
 8685: 
 8686: doc-represent
 8687: doc-f>str-rdp
 8688: doc-f>buf-rdp
 8689: 
 8690: 
 8691: @noindent
 8692: Here are some examples of using pictured numeric output:
 8693: 
 8694: @example
 8695: : my-u. ( u -- )
 8696:   \ Simplest use of pns.. behaves like Standard u. 
 8697:   0              \ convert to unsigned double
 8698:   <<#            \ start conversion
 8699:   #s             \ convert all digits
 8700:   #>             \ complete conversion
 8701:   TYPE SPACE     \ display, with trailing space
 8702:   #>> ;          \ release hold area
 8703: 
 8704: : cents-only ( u -- )
 8705:   0              \ convert to unsigned double
 8706:   <<#            \ start conversion
 8707:   # #            \ convert two least-significant digits
 8708:   #>             \ complete conversion, discard other digits
 8709:   TYPE SPACE     \ display, with trailing space
 8710:   #>> ;          \ release hold area
 8711: 
 8712: : dollars-and-cents ( u -- )
 8713:   0              \ convert to unsigned double
 8714:   <<#            \ start conversion
 8715:   # #            \ convert two least-significant digits
 8716:   [char] . hold  \ insert decimal point
 8717:   #s             \ convert remaining digits
 8718:   [char] $ hold  \ append currency symbol
 8719:   #>             \ complete conversion
 8720:   TYPE SPACE     \ display, with trailing space
 8721:   #>> ;          \ release hold area
 8722: 
 8723: : my-. ( n -- )
 8724:   \ handling negatives.. behaves like Standard .
 8725:   s>d            \ convert to signed double
 8726:   swap over dabs \ leave sign byte followed by unsigned double
 8727:   <<#            \ start conversion
 8728:   #s             \ convert all digits
 8729:   rot sign       \ get at sign byte, append "-" if needed
 8730:   #>             \ complete conversion
 8731:   TYPE SPACE     \ display, with trailing space
 8732:   #>> ;          \ release hold area
 8733: 
 8734: : account. ( n -- )
 8735:   \ accountants don't like minus signs, they use parentheses
 8736:   \ for negative numbers
 8737:   s>d            \ convert to signed double
 8738:   swap over dabs \ leave sign byte followed by unsigned double
 8739:   <<#            \ start conversion
 8740:   2 pick         \ get copy of sign byte
 8741:   0< IF [char] ) hold THEN \ right-most character of output
 8742:   #s             \ convert all digits
 8743:   rot            \ get at sign byte
 8744:   0< IF [char] ( hold THEN
 8745:   #>             \ complete conversion
 8746:   TYPE SPACE     \ display, with trailing space
 8747:   #>> ;          \ release hold area
 8748: 
 8749: @end example
 8750: 
 8751: Here are some examples of using these words:
 8752: 
 8753: @example
 8754: 1 my-u. 1
 8755: hex -1 my-u. decimal FFFFFFFF
 8756: 1 cents-only 01
 8757: 1234 cents-only 34
 8758: 2 dollars-and-cents $0.02
 8759: 1234 dollars-and-cents $12.34
 8760: 123 my-. 123
 8761: -123 my. -123
 8762: 123 account. 123
 8763: -456 account. (456)
 8764: @end example
 8765: 
 8766: 
 8767: @node String Formats, Displaying characters and strings, Formatted numeric output, Other I/O
 8768: @subsection String Formats
 8769: @cindex strings - see character strings
 8770: @cindex character strings - formats
 8771: @cindex I/O - see character strings
 8772: @cindex counted strings
 8773: 
 8774: @c anton: this does not really belong here; maybe the memory section,
 8775: @c  or the principles chapter
 8776: 
 8777: Forth commonly uses two different methods for representing character
 8778: strings:
 8779: 
 8780: @itemize @bullet
 8781: @item
 8782: @cindex address of counted string
 8783: @cindex counted string
 8784: As a @dfn{counted string}, represented by a @i{c-addr}. The char
 8785: addressed by @i{c-addr} contains a character-count, @i{n}, of the
 8786: string and the string occupies the subsequent @i{n} char addresses in
 8787: memory.
 8788: @item
 8789: As cell pair on the stack; @i{c-addr u}, where @i{u} is the length
 8790: of the string in characters, and @i{c-addr} is the address of the
 8791: first byte of the string.
 8792: @end itemize
 8793: 
 8794: ANS Forth encourages the use of the second format when representing
 8795: strings.
 8796: 
 8797: 
 8798: doc-count
 8799: 
 8800: 
 8801: For words that move, copy and search for strings see @ref{Memory
 8802: Blocks}. For words that display characters and strings see
 8803: @ref{Displaying characters and strings}.
 8804: 
 8805: @node Displaying characters and strings, Input, String Formats, Other I/O
 8806: @subsection Displaying characters and strings
 8807: @cindex characters - compiling and displaying
 8808: @cindex character strings - compiling and displaying
 8809: 
 8810: This section starts with a glossary of Forth words and ends with a set
 8811: of examples.
 8812: 
 8813: 
 8814: doc-bl
 8815: doc-space
 8816: doc-spaces
 8817: doc-emit
 8818: doc-toupper
 8819: doc-."
 8820: doc-.(
 8821: doc-.\"
 8822: doc-type
 8823: doc-typewhite
 8824: doc-cr
 8825: @cindex cursor control
 8826: doc-at-xy
 8827: doc-page
 8828: doc-s"
 8829: doc-s\"
 8830: doc-c"
 8831: doc-char
 8832: doc-[char]
 8833: 
 8834: 
 8835: @noindent
 8836: As an example, consider the following text, stored in a file @file{test.fs}:
 8837: 
 8838: @example
 8839: .( text-1)
 8840: : my-word
 8841:   ." text-2" cr
 8842:   .( text-3)
 8843: ;
 8844: 
 8845: ." text-4"
 8846: 
 8847: : my-char
 8848:   [char] ALPHABET emit
 8849:   char emit
 8850: ;
 8851: @end example
 8852: 
 8853: When you load this code into Gforth, the following output is generated:
 8854: 
 8855: @example
 8856: @kbd{include test.fs @key{RET}} text-1text-3text-4 ok
 8857: @end example
 8858: 
 8859: @itemize @bullet
 8860: @item
 8861: Messages @code{text-1} and @code{text-3} are displayed because @code{.(} 
 8862: is an immediate word; it behaves in the same way whether it is used inside
 8863: or outside a colon definition.
 8864: @item
 8865: Message @code{text-4} is displayed because of Gforth's added interpretation
 8866: semantics for @code{."}.
 8867: @item
 8868: Message @code{text-2} is @i{not} displayed, because the text interpreter
 8869: performs the compilation semantics for @code{."} within the definition of
 8870: @code{my-word}.
 8871: @end itemize
 8872: 
 8873: Here are some examples of executing @code{my-word} and @code{my-char}:
 8874: 
 8875: @example
 8876: @kbd{my-word @key{RET}} text-2
 8877:  ok
 8878: @kbd{my-char fred @key{RET}} Af ok
 8879: @kbd{my-char jim @key{RET}} Aj ok
 8880: @end example
 8881: 
 8882: @itemize @bullet
 8883: @item
 8884: Message @code{text-2} is displayed because of the run-time behaviour of
 8885: @code{."}.
 8886: @item
 8887: @code{[char]} compiles the ``A'' from ``ALPHABET'' and puts its display code
 8888: on the stack at run-time. @code{emit} always displays the character
 8889: when @code{my-char} is executed.
 8890: @item
 8891: @code{char} parses a string at run-time and the second @code{emit} displays
 8892: the first character of the string.
 8893: @item
 8894: If you type @code{see my-char} you can see that @code{[char]} discarded
 8895: the text ``LPHABET'' and only compiled the display code for ``A'' into the
 8896: definition of @code{my-char}.
 8897: @end itemize
 8898: 
 8899: 
 8900: 
 8901: @node Input, Pipes, Displaying characters and strings, Other I/O
 8902: @subsection Input
 8903: @cindex input
 8904: @cindex I/O - see input
 8905: @cindex parsing a string
 8906: 
 8907: For ways of storing character strings in memory see @ref{String Formats}.
 8908: 
 8909: @comment TODO examples for >number >float accept key key? pad parse word refill
 8910: @comment then index them
 8911: 
 8912: 
 8913: doc-key
 8914: doc-key?
 8915: doc-ekey
 8916: doc-ekey>char
 8917: doc-ekey?
 8918: 
 8919: Gforth recognizes various keys available on ANSI terminals (in MS-DOS
 8920: you need the ANSI.SYS driver to get that behaviour).  These are the
 8921: keyboard events produced by various common keys:
 8922: 
 8923: doc-k-left
 8924: doc-k-right
 8925: doc-k-up	
 8926: doc-k-down	
 8927: doc-k-home	
 8928: doc-k-end	
 8929: doc-k-prior
 8930: doc-k-next
 8931: doc-k-insert
 8932: doc-k-delete
 8933: 
 8934: The function keys (aka keypad keys) are:
 8935: 
 8936: doc-k1
 8937: doc-k2
 8938: doc-k3
 8939: doc-k4
 8940: doc-k5
 8941: doc-k6
 8942: doc-k7
 8943: doc-k8
 8944: doc-k9
 8945: doc-k10
 8946: doc-k11
 8947: doc-k12
 8948: 
 8949: Note that K11 and K12 are not as widely available.  The shifted
 8950: function keys are also not very widely available:
 8951: 
 8952: doc-s-k8
 8953: doc-s-k1
 8954: doc-s-k2
 8955: doc-s-k3
 8956: doc-s-k4
 8957: doc-s-k5
 8958: doc-s-k6
 8959: doc-s-k7
 8960: doc-s-k8
 8961: doc-s-k9
 8962: doc-s-k10
 8963: doc-s-k11
 8964: doc-s-k12
 8965: 
 8966: Words for inputting one line from the keyboard:
 8967: 
 8968: doc-accept
 8969: doc-edit-line
 8970: 
 8971: Conversion words:
 8972: 
 8973: doc-s>number?
 8974: doc-s>unumber?
 8975: doc->number
 8976: doc->float
 8977: 
 8978: 
 8979: @comment obsolescent words..
 8980: Obsolescent input and conversion words:
 8981: 
 8982: doc-convert
 8983: doc-expect
 8984: doc-span
 8985: 
 8986: 
 8987: @node Pipes, Xchars and Unicode, Input, Other I/O
 8988: @subsection Pipes
 8989: @cindex pipes, creating your own
 8990: 
 8991: In addition to using Gforth in pipes created by other processes
 8992: (@pxref{Gforth in pipes}), you can create your own pipe with
 8993: @code{open-pipe}, and read from or write to it.
 8994: 
 8995: doc-open-pipe
 8996: doc-close-pipe
 8997: 
 8998: If you write to a pipe, Gforth can throw a @code{broken-pipe-error}; if
 8999: you don't catch this exception, Gforth will catch it and exit, usually
 9000: silently (@pxref{Gforth in pipes}).  Since you probably do not want
 9001: this, you should wrap a @code{catch} or @code{try} block around the code
 9002: from @code{open-pipe} to @code{close-pipe}, so you can deal with the
 9003: problem yourself, and then return to regular processing.
 9004: 
 9005: doc-broken-pipe-error
 9006: 
 9007: @node Xchars and Unicode,  , Pipes, Other I/O
 9008: @subsection Xchars and Unicode
 9009: 
 9010: This chapter needs completion
 9011: 
 9012: @node OS command line arguments, Locals, Other I/O, Words
 9013: @section OS command line arguments
 9014: @cindex OS command line arguments
 9015: @cindex command line arguments, OS
 9016: @cindex arguments, OS command line
 9017: 
 9018: The usual way to pass arguments to Gforth programs on the command line
 9019: is via the @option{-e} option, e.g.
 9020: 
 9021: @example
 9022: gforth -e "123 456" foo.fs -e bye
 9023: @end example
 9024: 
 9025: However, you may want to interpret the command-line arguments directly.
 9026: In that case, you can access the (image-specific) command-line arguments
 9027: through @code{next-arg}:
 9028: 
 9029: doc-next-arg
 9030: 
 9031: Here's an example program @file{echo.fs} for @code{next-arg}:
 9032: 
 9033: @example
 9034: : echo ( -- )
 9035:     begin
 9036: 	next-arg 2dup 0 0 d<> while
 9037: 	    type space
 9038:     repeat
 9039:     2drop ;
 9040: 
 9041: echo cr bye
 9042: @end example
 9043: 
 9044: This can be invoked with
 9045: 
 9046: @example
 9047: gforth echo.fs hello world
 9048: @end example
 9049: 
 9050: and it will print
 9051: 
 9052: @example
 9053: hello world
 9054: @end example
 9055: 
 9056: The next lower level of dealing with the OS command line are the
 9057: following words:
 9058: 
 9059: doc-arg
 9060: doc-shift-args
 9061: 
 9062: Finally, at the lowest level Gforth provides the following words:
 9063: 
 9064: doc-argc
 9065: doc-argv
 9066: 
 9067: @c -------------------------------------------------------------
 9068: @node Locals, Structures, OS command line arguments, Words
 9069: @section Locals
 9070: @cindex locals
 9071: 
 9072: Local variables can make Forth programming more enjoyable and Forth
 9073: programs easier to read. Unfortunately, the locals of ANS Forth are
 9074: laden with restrictions. Therefore, we provide not only the ANS Forth
 9075: locals wordset, but also our own, more powerful locals wordset (we
 9076: implemented the ANS Forth locals wordset through our locals wordset).
 9077: 
 9078: The ideas in this section have also been published in M. Anton Ertl,
 9079: @cite{@uref{http://www.complang.tuwien.ac.at/papers/ertl94l.ps.gz,
 9080: Automatic Scoping of Local Variables}}, EuroForth '94.
 9081: 
 9082: @menu
 9083: * Gforth locals::               
 9084: * ANS Forth locals::            
 9085: @end menu
 9086: 
 9087: @node Gforth locals, ANS Forth locals, Locals, Locals
 9088: @subsection Gforth locals
 9089: @cindex Gforth locals
 9090: @cindex locals, Gforth style
 9091: 
 9092: Locals can be defined with
 9093: 
 9094: @example
 9095: @{ local1 local2 ... -- comment @}
 9096: @end example
 9097: or
 9098: @example
 9099: @{ local1 local2 ... @}
 9100: @end example
 9101: 
 9102: E.g.,
 9103: @example
 9104: : max @{ n1 n2 -- n3 @}
 9105:  n1 n2 > if
 9106:    n1
 9107:  else
 9108:    n2
 9109:  endif ;
 9110: @end example
 9111: 
 9112: The similarity of locals definitions with stack comments is intended. A
 9113: locals definition often replaces the stack comment of a word. The order
 9114: of the locals corresponds to the order in a stack comment and everything
 9115: after the @code{--} is really a comment.
 9116: 
 9117: This similarity has one disadvantage: It is too easy to confuse locals
 9118: declarations with stack comments, causing bugs and making them hard to
 9119: find. However, this problem can be avoided by appropriate coding
 9120: conventions: Do not use both notations in the same program. If you do,
 9121: they should be distinguished using additional means, e.g. by position.
 9122: 
 9123: @cindex types of locals
 9124: @cindex locals types
 9125: The name of the local may be preceded by a type specifier, e.g.,
 9126: @code{F:} for a floating point value:
 9127: 
 9128: @example
 9129: : CX* @{ F: Ar F: Ai F: Br F: Bi -- Cr Ci @}
 9130: \ complex multiplication
 9131:  Ar Br f* Ai Bi f* f-
 9132:  Ar Bi f* Ai Br f* f+ ;
 9133: @end example
 9134: 
 9135: @cindex flavours of locals
 9136: @cindex locals flavours
 9137: @cindex value-flavoured locals
 9138: @cindex variable-flavoured locals
 9139: Gforth currently supports cells (@code{W:}, @code{W^}), doubles
 9140: (@code{D:}, @code{D^}), floats (@code{F:}, @code{F^}) and characters
 9141: (@code{C:}, @code{C^}) in two flavours: a value-flavoured local (defined
 9142: with @code{W:}, @code{D:} etc.) produces its value and can be changed
 9143: with @code{TO}. A variable-flavoured local (defined with @code{W^} etc.)
 9144: produces its address (which becomes invalid when the variable's scope is
 9145: left). E.g., the standard word @code{emit} can be defined in terms of
 9146: @code{type} like this:
 9147: 
 9148: @example
 9149: : emit @{ C^ char* -- @}
 9150:     char* 1 type ;
 9151: @end example
 9152: 
 9153: @cindex default type of locals
 9154: @cindex locals, default type
 9155: A local without type specifier is a @code{W:} local. Both flavours of
 9156: locals are initialized with values from the data or FP stack.
 9157: 
 9158: Currently there is no way to define locals with user-defined data
 9159: structures, but we are working on it.
 9160: 
 9161: Gforth allows defining locals everywhere in a colon definition. This
 9162: poses the following questions:
 9163: 
 9164: @menu
 9165: * Where are locals visible by name?::  
 9166: * How long do locals live?::    
 9167: * Locals programming style::    
 9168: * Locals implementation::       
 9169: @end menu
 9170: 
 9171: @node Where are locals visible by name?, How long do locals live?, Gforth locals, Gforth locals
 9172: @subsubsection Where are locals visible by name?
 9173: @cindex locals visibility
 9174: @cindex visibility of locals
 9175: @cindex scope of locals
 9176: 
 9177: Basically, the answer is that locals are visible where you would expect
 9178: it in block-structured languages, and sometimes a little longer. If you
 9179: want to restrict the scope of a local, enclose its definition in
 9180: @code{SCOPE}...@code{ENDSCOPE}.
 9181: 
 9182: 
 9183: doc-scope
 9184: doc-endscope
 9185: 
 9186: 
 9187: These words behave like control structure words, so you can use them
 9188: with @code{CS-PICK} and @code{CS-ROLL} to restrict the scope in
 9189: arbitrary ways.
 9190: 
 9191: If you want a more exact answer to the visibility question, here's the
 9192: basic principle: A local is visible in all places that can only be
 9193: reached through the definition of the local@footnote{In compiler
 9194: construction terminology, all places dominated by the definition of the
 9195: local.}. In other words, it is not visible in places that can be reached
 9196: without going through the definition of the local. E.g., locals defined
 9197: in @code{IF}...@code{ENDIF} are visible until the @code{ENDIF}, locals
 9198: defined in @code{BEGIN}...@code{UNTIL} are visible after the
 9199: @code{UNTIL} (until, e.g., a subsequent @code{ENDSCOPE}).
 9200: 
 9201: The reasoning behind this solution is: We want to have the locals
 9202: visible as long as it is meaningful. The user can always make the
 9203: visibility shorter by using explicit scoping. In a place that can
 9204: only be reached through the definition of a local, the meaning of a
 9205: local name is clear. In other places it is not: How is the local
 9206: initialized at the control flow path that does not contain the
 9207: definition? Which local is meant, if the same name is defined twice in
 9208: two independent control flow paths?
 9209: 
 9210: This should be enough detail for nearly all users, so you can skip the
 9211: rest of this section. If you really must know all the gory details and
 9212: options, read on.
 9213: 
 9214: In order to implement this rule, the compiler has to know which places
 9215: are unreachable. It knows this automatically after @code{AHEAD},
 9216: @code{AGAIN}, @code{EXIT} and @code{LEAVE}; in other cases (e.g., after
 9217: most @code{THROW}s), you can use the word @code{UNREACHABLE} to tell the
 9218: compiler that the control flow never reaches that place. If
 9219: @code{UNREACHABLE} is not used where it could, the only consequence is
 9220: that the visibility of some locals is more limited than the rule above
 9221: says. If @code{UNREACHABLE} is used where it should not (i.e., if you
 9222: lie to the compiler), buggy code will be produced.
 9223: 
 9224: 
 9225: doc-unreachable
 9226: 
 9227: 
 9228: Another problem with this rule is that at @code{BEGIN}, the compiler
 9229: does not know which locals will be visible on the incoming
 9230: back-edge. All problems discussed in the following are due to this
 9231: ignorance of the compiler (we discuss the problems using @code{BEGIN}
 9232: loops as examples; the discussion also applies to @code{?DO} and other
 9233: loops). Perhaps the most insidious example is:
 9234: @example
 9235: AHEAD
 9236: BEGIN
 9237:   x
 9238: [ 1 CS-ROLL ] THEN
 9239:   @{ x @}
 9240:   ...
 9241: UNTIL
 9242: @end example
 9243: 
 9244: This should be legal according to the visibility rule. The use of
 9245: @code{x} can only be reached through the definition; but that appears
 9246: textually below the use.
 9247: 
 9248: From this example it is clear that the visibility rules cannot be fully
 9249: implemented without major headaches. Our implementation treats common
 9250: cases as advertised and the exceptions are treated in a safe way: The
 9251: compiler makes a reasonable guess about the locals visible after a
 9252: @code{BEGIN}; if it is too pessimistic, the
 9253: user will get a spurious error about the local not being defined; if the
 9254: compiler is too optimistic, it will notice this later and issue a
 9255: warning. In the case above the compiler would complain about @code{x}
 9256: being undefined at its use. You can see from the obscure examples in
 9257: this section that it takes quite unusual control structures to get the
 9258: compiler into trouble, and even then it will often do fine.
 9259: 
 9260: If the @code{BEGIN} is reachable from above, the most optimistic guess
 9261: is that all locals visible before the @code{BEGIN} will also be
 9262: visible after the @code{BEGIN}. This guess is valid for all loops that
 9263: are entered only through the @code{BEGIN}, in particular, for normal
 9264: @code{BEGIN}...@code{WHILE}...@code{REPEAT} and
 9265: @code{BEGIN}...@code{UNTIL} loops and it is implemented in our
 9266: compiler. When the branch to the @code{BEGIN} is finally generated by
 9267: @code{AGAIN} or @code{UNTIL}, the compiler checks the guess and
 9268: warns the user if it was too optimistic:
 9269: @example
 9270: IF
 9271:   @{ x @}
 9272: BEGIN
 9273:   \ x ? 
 9274: [ 1 cs-roll ] THEN
 9275:   ...
 9276: UNTIL
 9277: @end example
 9278: 
 9279: Here, @code{x} lives only until the @code{BEGIN}, but the compiler
 9280: optimistically assumes that it lives until the @code{THEN}. It notices
 9281: this difference when it compiles the @code{UNTIL} and issues a
 9282: warning. The user can avoid the warning, and make sure that @code{x}
 9283: is not used in the wrong area by using explicit scoping:
 9284: @example
 9285: IF
 9286:   SCOPE
 9287:   @{ x @}
 9288:   ENDSCOPE
 9289: BEGIN
 9290: [ 1 cs-roll ] THEN
 9291:   ...
 9292: UNTIL
 9293: @end example
 9294: 
 9295: Since the guess is optimistic, there will be no spurious error messages
 9296: about undefined locals.
 9297: 
 9298: If the @code{BEGIN} is not reachable from above (e.g., after
 9299: @code{AHEAD} or @code{EXIT}), the compiler cannot even make an
 9300: optimistic guess, as the locals visible after the @code{BEGIN} may be
 9301: defined later. Therefore, the compiler assumes that no locals are
 9302: visible after the @code{BEGIN}. However, the user can use
 9303: @code{ASSUME-LIVE} to make the compiler assume that the same locals are
 9304: visible at the BEGIN as at the point where the top control-flow stack
 9305: item was created.
 9306: 
 9307: 
 9308: doc-assume-live
 9309: 
 9310: 
 9311: @noindent
 9312: E.g.,
 9313: @example
 9314: @{ x @}
 9315: AHEAD
 9316: ASSUME-LIVE
 9317: BEGIN
 9318:   x
 9319: [ 1 CS-ROLL ] THEN
 9320:   ...
 9321: UNTIL
 9322: @end example
 9323: 
 9324: Other cases where the locals are defined before the @code{BEGIN} can be
 9325: handled by inserting an appropriate @code{CS-ROLL} before the
 9326: @code{ASSUME-LIVE} (and changing the control-flow stack manipulation
 9327: behind the @code{ASSUME-LIVE}).
 9328: 
 9329: Cases where locals are defined after the @code{BEGIN} (but should be
 9330: visible immediately after the @code{BEGIN}) can only be handled by
 9331: rearranging the loop. E.g., the ``most insidious'' example above can be
 9332: arranged into:
 9333: @example
 9334: BEGIN
 9335:   @{ x @}
 9336:   ... 0=
 9337: WHILE
 9338:   x
 9339: REPEAT
 9340: @end example
 9341: 
 9342: @node How long do locals live?, Locals programming style, Where are locals visible by name?, Gforth locals
 9343: @subsubsection How long do locals live?
 9344: @cindex locals lifetime
 9345: @cindex lifetime of locals
 9346: 
 9347: The right answer for the lifetime question would be: A local lives at
 9348: least as long as it can be accessed. For a value-flavoured local this
 9349: means: until the end of its visibility. However, a variable-flavoured
 9350: local could be accessed through its address far beyond its visibility
 9351: scope. Ultimately, this would mean that such locals would have to be
 9352: garbage collected. Since this entails un-Forth-like implementation
 9353: complexities, I adopted the same cowardly solution as some other
 9354: languages (e.g., C): The local lives only as long as it is visible;
 9355: afterwards its address is invalid (and programs that access it
 9356: afterwards are erroneous).
 9357: 
 9358: @node Locals programming style, Locals implementation, How long do locals live?, Gforth locals
 9359: @subsubsection Locals programming style
 9360: @cindex locals programming style
 9361: @cindex programming style, locals
 9362: 
 9363: The freedom to define locals anywhere has the potential to change
 9364: programming styles dramatically. In particular, the need to use the
 9365: return stack for intermediate storage vanishes. Moreover, all stack
 9366: manipulations (except @code{PICK}s and @code{ROLL}s with run-time
 9367: determined arguments) can be eliminated: If the stack items are in the
 9368: wrong order, just write a locals definition for all of them; then
 9369: write the items in the order you want.
 9370: 
 9371: This seems a little far-fetched and eliminating stack manipulations is
 9372: unlikely to become a conscious programming objective. Still, the number
 9373: of stack manipulations will be reduced dramatically if local variables
 9374: are used liberally (e.g., compare @code{max} (@pxref{Gforth locals}) with
 9375: a traditional implementation of @code{max}).
 9376: 
 9377: This shows one potential benefit of locals: making Forth programs more
 9378: readable. Of course, this benefit will only be realized if the
 9379: programmers continue to honour the principle of factoring instead of
 9380: using the added latitude to make the words longer.
 9381: 
 9382: @cindex single-assignment style for locals
 9383: Using @code{TO} can and should be avoided.  Without @code{TO},
 9384: every value-flavoured local has only a single assignment and many
 9385: advantages of functional languages apply to Forth. I.e., programs are
 9386: easier to analyse, to optimize and to read: It is clear from the
 9387: definition what the local stands for, it does not turn into something
 9388: different later.
 9389: 
 9390: E.g., a definition using @code{TO} might look like this:
 9391: @example
 9392: : strcmp @{ addr1 u1 addr2 u2 -- n @}
 9393:  u1 u2 min 0
 9394:  ?do
 9395:    addr1 c@@ addr2 c@@ -
 9396:    ?dup-if
 9397:      unloop exit
 9398:    then
 9399:    addr1 char+ TO addr1
 9400:    addr2 char+ TO addr2
 9401:  loop
 9402:  u1 u2 - ;
 9403: @end example
 9404: Here, @code{TO} is used to update @code{addr1} and @code{addr2} at
 9405: every loop iteration. @code{strcmp} is a typical example of the
 9406: readability problems of using @code{TO}. When you start reading
 9407: @code{strcmp}, you think that @code{addr1} refers to the start of the
 9408: string. Only near the end of the loop you realize that it is something
 9409: else.
 9410: 
 9411: This can be avoided by defining two locals at the start of the loop that
 9412: are initialized with the right value for the current iteration.
 9413: @example
 9414: : strcmp @{ addr1 u1 addr2 u2 -- n @}
 9415:  addr1 addr2
 9416:  u1 u2 min 0 
 9417:  ?do @{ s1 s2 @}
 9418:    s1 c@@ s2 c@@ -
 9419:    ?dup-if
 9420:      unloop exit
 9421:    then
 9422:    s1 char+ s2 char+
 9423:  loop
 9424:  2drop
 9425:  u1 u2 - ;
 9426: @end example
 9427: Here it is clear from the start that @code{s1} has a different value
 9428: in every loop iteration.
 9429: 
 9430: @node Locals implementation,  , Locals programming style, Gforth locals
 9431: @subsubsection Locals implementation
 9432: @cindex locals implementation
 9433: @cindex implementation of locals
 9434: 
 9435: @cindex locals stack
 9436: Gforth uses an extra locals stack. The most compelling reason for
 9437: this is that the return stack is not float-aligned; using an extra stack
 9438: also eliminates the problems and restrictions of using the return stack
 9439: as locals stack. Like the other stacks, the locals stack grows toward
 9440: lower addresses. A few primitives allow an efficient implementation:
 9441: 
 9442: 
 9443: doc-@local#
 9444: doc-f@local#
 9445: doc-laddr#
 9446: doc-lp+!#
 9447: doc-lp!
 9448: doc->l
 9449: doc-f>l
 9450: 
 9451: 
 9452: In addition to these primitives, some specializations of these
 9453: primitives for commonly occurring inline arguments are provided for
 9454: efficiency reasons, e.g., @code{@@local0} as specialization of
 9455: @code{@@local#} for the inline argument 0. The following compiling words
 9456: compile the right specialized version, or the general version, as
 9457: appropriate:
 9458: 
 9459: 
 9460: @c doc-compile-@local
 9461: @c doc-compile-f@local
 9462: doc-compile-lp+!
 9463: 
 9464: 
 9465: Combinations of conditional branches and @code{lp+!#} like
 9466: @code{?branch-lp+!#} (the locals pointer is only changed if the branch
 9467: is taken) are provided for efficiency and correctness in loops.
 9468: 
 9469: A special area in the dictionary space is reserved for keeping the
 9470: local variable names. @code{@{} switches the dictionary pointer to this
 9471: area and @code{@}} switches it back and generates the locals
 9472: initializing code. @code{W:} etc.@ are normal defining words. This
 9473: special area is cleared at the start of every colon definition.
 9474: 
 9475: @cindex word list for defining locals
 9476: A special feature of Gforth's dictionary is used to implement the
 9477: definition of locals without type specifiers: every word list (aka
 9478: vocabulary) has its own methods for searching
 9479: etc. (@pxref{Word Lists}). For the present purpose we defined a word list
 9480: with a special search method: When it is searched for a word, it
 9481: actually creates that word using @code{W:}. @code{@{} changes the search
 9482: order to first search the word list containing @code{@}}, @code{W:} etc.,
 9483: and then the word list for defining locals without type specifiers.
 9484: 
 9485: The lifetime rules support a stack discipline within a colon
 9486: definition: The lifetime of a local is either nested with other locals
 9487: lifetimes or it does not overlap them.
 9488: 
 9489: At @code{BEGIN}, @code{IF}, and @code{AHEAD} no code for locals stack
 9490: pointer manipulation is generated. Between control structure words
 9491: locals definitions can push locals onto the locals stack. @code{AGAIN}
 9492: is the simplest of the other three control flow words. It has to
 9493: restore the locals stack depth of the corresponding @code{BEGIN}
 9494: before branching. The code looks like this:
 9495: @format
 9496: @code{lp+!#} current-locals-size @minus{} dest-locals-size
 9497: @code{branch} <begin>
 9498: @end format
 9499: 
 9500: @code{UNTIL} is a little more complicated: If it branches back, it
 9501: must adjust the stack just like @code{AGAIN}. But if it falls through,
 9502: the locals stack must not be changed. The compiler generates the
 9503: following code:
 9504: @format
 9505: @code{?branch-lp+!#} <begin> current-locals-size @minus{} dest-locals-size
 9506: @end format
 9507: The locals stack pointer is only adjusted if the branch is taken.
 9508: 
 9509: @code{THEN} can produce somewhat inefficient code:
 9510: @format
 9511: @code{lp+!#} current-locals-size @minus{} orig-locals-size
 9512: <orig target>:
 9513: @code{lp+!#} orig-locals-size @minus{} new-locals-size
 9514: @end format
 9515: The second @code{lp+!#} adjusts the locals stack pointer from the
 9516: level at the @i{orig} point to the level after the @code{THEN}. The
 9517: first @code{lp+!#} adjusts the locals stack pointer from the current
 9518: level to the level at the orig point, so the complete effect is an
 9519: adjustment from the current level to the right level after the
 9520: @code{THEN}.
 9521: 
 9522: @cindex locals information on the control-flow stack
 9523: @cindex control-flow stack items, locals information
 9524: In a conventional Forth implementation a dest control-flow stack entry
 9525: is just the target address and an orig entry is just the address to be
 9526: patched. Our locals implementation adds a word list to every orig or dest
 9527: item. It is the list of locals visible (or assumed visible) at the point
 9528: described by the entry. Our implementation also adds a tag to identify
 9529: the kind of entry, in particular to differentiate between live and dead
 9530: (reachable and unreachable) orig entries.
 9531: 
 9532: A few unusual operations have to be performed on locals word lists:
 9533: 
 9534: 
 9535: doc-common-list
 9536: doc-sub-list?
 9537: doc-list-size
 9538: 
 9539: 
 9540: Several features of our locals word list implementation make these
 9541: operations easy to implement: The locals word lists are organised as
 9542: linked lists; the tails of these lists are shared, if the lists
 9543: contain some of the same locals; and the address of a name is greater
 9544: than the address of the names behind it in the list.
 9545: 
 9546: Another important implementation detail is the variable
 9547: @code{dead-code}. It is used by @code{BEGIN} and @code{THEN} to
 9548: determine if they can be reached directly or only through the branch
 9549: that they resolve. @code{dead-code} is set by @code{UNREACHABLE},
 9550: @code{AHEAD}, @code{EXIT} etc., and cleared at the start of a colon
 9551: definition, by @code{BEGIN} and usually by @code{THEN}.
 9552: 
 9553: Counted loops are similar to other loops in most respects, but
 9554: @code{LEAVE} requires special attention: It performs basically the same
 9555: service as @code{AHEAD}, but it does not create a control-flow stack
 9556: entry. Therefore the information has to be stored elsewhere;
 9557: traditionally, the information was stored in the target fields of the
 9558: branches created by the @code{LEAVE}s, by organizing these fields into a
 9559: linked list. Unfortunately, this clever trick does not provide enough
 9560: space for storing our extended control flow information. Therefore, we
 9561: introduce another stack, the leave stack. It contains the control-flow
 9562: stack entries for all unresolved @code{LEAVE}s.
 9563: 
 9564: Local names are kept until the end of the colon definition, even if
 9565: they are no longer visible in any control-flow path. In a few cases
 9566: this may lead to increased space needs for the locals name area, but
 9567: usually less than reclaiming this space would cost in code size.
 9568: 
 9569: 
 9570: @node ANS Forth locals,  , Gforth locals, Locals
 9571: @subsection ANS Forth locals
 9572: @cindex locals, ANS Forth style
 9573: 
 9574: The ANS Forth locals wordset does not define a syntax for locals, but
 9575: words that make it possible to define various syntaxes. One of the
 9576: possible syntaxes is a subset of the syntax we used in the Gforth locals
 9577: wordset, i.e.:
 9578: 
 9579: @example
 9580: @{ local1 local2 ... -- comment @}
 9581: @end example
 9582: @noindent
 9583: or
 9584: @example
 9585: @{ local1 local2 ... @}
 9586: @end example
 9587: 
 9588: The order of the locals corresponds to the order in a stack comment. The
 9589: restrictions are:
 9590: 
 9591: @itemize @bullet
 9592: @item
 9593: Locals can only be cell-sized values (no type specifiers are allowed).
 9594: @item
 9595: Locals can be defined only outside control structures.
 9596: @item
 9597: Locals can interfere with explicit usage of the return stack. For the
 9598: exact (and long) rules, see the standard. If you don't use return stack
 9599: accessing words in a definition using locals, you will be all right. The
 9600: purpose of this rule is to make locals implementation on the return
 9601: stack easier.
 9602: @item
 9603: The whole definition must be in one line.
 9604: @end itemize
 9605: 
 9606: Locals defined in ANS Forth behave like @code{VALUE}s
 9607: (@pxref{Values}). I.e., they are initialized from the stack. Using their
 9608: name produces their value. Their value can be changed using @code{TO}.
 9609: 
 9610: Since the syntax above is supported by Gforth directly, you need not do
 9611: anything to use it. If you want to port a program using this syntax to
 9612: another ANS Forth system, use @file{compat/anslocal.fs} to implement the
 9613: syntax on the other system.
 9614: 
 9615: Note that a syntax shown in the standard, section A.13 looks
 9616: similar, but is quite different in having the order of locals
 9617: reversed. Beware!
 9618: 
 9619: The ANS Forth locals wordset itself consists of one word:
 9620: 
 9621: doc-(local)
 9622: 
 9623: The ANS Forth locals extension wordset defines a syntax using
 9624: @code{locals|}, but it is so awful that we strongly recommend not to use
 9625: it. We have implemented this syntax to make porting to Gforth easy, but
 9626: do not document it here. The problem with this syntax is that the locals
 9627: are defined in an order reversed with respect to the standard stack
 9628: comment notation, making programs harder to read, and easier to misread
 9629: and miswrite. The only merit of this syntax is that it is easy to
 9630: implement using the ANS Forth locals wordset.
 9631: 
 9632: 
 9633: @c ----------------------------------------------------------
 9634: @node Structures, Object-oriented Forth, Locals, Words
 9635: @section  Structures
 9636: @cindex structures
 9637: @cindex records
 9638: 
 9639: This section presents the structure package that comes with Gforth. A
 9640: version of the package implemented in ANS Forth is available in
 9641: @file{compat/struct.fs}. This package was inspired by a posting on
 9642: comp.lang.forth in 1989 (unfortunately I don't remember, by whom;
 9643: possibly John Hayes). A version of this section has been published in
 9644: M. Anton Ertl,
 9645: @uref{http://www.complang.tuwien.ac.at/forth/objects/structs.html, Yet
 9646: Another Forth Structures Package}, Forth Dimensions 19(3), pages
 9647: 13--16. Marcel Hendrix provided helpful comments.
 9648: 
 9649: @menu
 9650: * Why explicit structure support?::  
 9651: * Structure Usage::             
 9652: * Structure Naming Convention::  
 9653: * Structure Implementation::    
 9654: * Structure Glossary::          
 9655: @end menu
 9656: 
 9657: @node Why explicit structure support?, Structure Usage, Structures, Structures
 9658: @subsection Why explicit structure support?
 9659: 
 9660: @cindex address arithmetic for structures
 9661: @cindex structures using address arithmetic
 9662: If we want to use a structure containing several fields, we could simply
 9663: reserve memory for it, and access the fields using address arithmetic
 9664: (@pxref{Address arithmetic}). As an example, consider a structure with
 9665: the following fields
 9666: 
 9667: @table @code
 9668: @item a
 9669: is a float
 9670: @item b
 9671: is a cell
 9672: @item c
 9673: is a float
 9674: @end table
 9675: 
 9676: Given the (float-aligned) base address of the structure we get the
 9677: address of the field
 9678: 
 9679: @table @code
 9680: @item a
 9681: without doing anything further.
 9682: @item b
 9683: with @code{float+}
 9684: @item c
 9685: with @code{float+ cell+ faligned}
 9686: @end table
 9687: 
 9688: It is easy to see that this can become quite tiring. 
 9689: 
 9690: Moreover, it is not very readable, because seeing a
 9691: @code{cell+} tells us neither which kind of structure is
 9692: accessed nor what field is accessed; we have to somehow infer the kind
 9693: of structure, and then look up in the documentation, which field of
 9694: that structure corresponds to that offset.
 9695: 
 9696: Finally, this kind of address arithmetic also causes maintenance
 9697: troubles: If you add or delete a field somewhere in the middle of the
 9698: structure, you have to find and change all computations for the fields
 9699: afterwards.
 9700: 
 9701: So, instead of using @code{cell+} and friends directly, how
 9702: about storing the offsets in constants:
 9703: 
 9704: @example
 9705: 0 constant a-offset
 9706: 0 float+ constant b-offset
 9707: 0 float+ cell+ faligned c-offset
 9708: @end example
 9709: 
 9710: Now we can get the address of field @code{x} with @code{x-offset
 9711: +}. This is much better in all respects. Of course, you still
 9712: have to change all later offset definitions if you add a field. You can
 9713: fix this by declaring the offsets in the following way:
 9714: 
 9715: @example
 9716: 0 constant a-offset
 9717: a-offset float+ constant b-offset
 9718: b-offset cell+ faligned constant c-offset
 9719: @end example
 9720: 
 9721: Since we always use the offsets with @code{+}, we could use a defining
 9722: word @code{cfield} that includes the @code{+} in the action of the
 9723: defined word:
 9724: 
 9725: @example
 9726: : cfield ( n "name" -- )
 9727:     create ,
 9728: does> ( name execution: addr1 -- addr2 )
 9729:     @@ + ;
 9730: 
 9731: 0 cfield a
 9732: 0 a float+ cfield b
 9733: 0 b cell+ faligned cfield c
 9734: @end example
 9735: 
 9736: Instead of @code{x-offset +}, we now simply write @code{x}.
 9737: 
 9738: The structure field words now can be used quite nicely. However,
 9739: their definition is still a bit cumbersome: We have to repeat the
 9740: name, the information about size and alignment is distributed before
 9741: and after the field definitions etc.  The structure package presented
 9742: here addresses these problems.
 9743: 
 9744: @node Structure Usage, Structure Naming Convention, Why explicit structure support?, Structures
 9745: @subsection Structure Usage
 9746: @cindex structure usage
 9747: 
 9748: @cindex @code{field} usage
 9749: @cindex @code{struct} usage
 9750: @cindex @code{end-struct} usage
 9751: You can define a structure for a (data-less) linked list with:
 9752: @example
 9753: struct
 9754:     cell% field list-next
 9755: end-struct list%
 9756: @end example
 9757: 
 9758: With the address of the list node on the stack, you can compute the
 9759: address of the field that contains the address of the next node with
 9760: @code{list-next}. E.g., you can determine the length of a list
 9761: with:
 9762: 
 9763: @example
 9764: : list-length ( list -- n )
 9765: \ "list" is a pointer to the first element of a linked list
 9766: \ "n" is the length of the list
 9767:     0 BEGIN ( list1 n1 )
 9768:         over
 9769:     WHILE ( list1 n1 )
 9770:         1+ swap list-next @@ swap
 9771:     REPEAT
 9772:     nip ;
 9773: @end example
 9774: 
 9775: You can reserve memory for a list node in the dictionary with
 9776: @code{list% %allot}, which leaves the address of the list node on the
 9777: stack. For the equivalent allocation on the heap you can use @code{list%
 9778: %alloc} (or, for an @code{allocate}-like stack effect (i.e., with ior),
 9779: use @code{list% %allocate}). You can get the the size of a list
 9780: node with @code{list% %size} and its alignment with @code{list%
 9781: %alignment}.
 9782: 
 9783: Note that in ANS Forth the body of a @code{create}d word is
 9784: @code{aligned} but not necessarily @code{faligned};
 9785: therefore, if you do a:
 9786: 
 9787: @example
 9788: create @emph{name} foo% %allot drop
 9789: @end example
 9790: 
 9791: @noindent
 9792: then the memory alloted for @code{foo%} is guaranteed to start at the
 9793: body of @code{@emph{name}} only if @code{foo%} contains only character,
 9794: cell and double fields.  Therefore, if your structure contains floats,
 9795: better use
 9796: 
 9797: @example
 9798: foo% %allot constant @emph{name}
 9799: @end example
 9800: 
 9801: @cindex structures containing structures
 9802: You can include a structure @code{foo%} as a field of
 9803: another structure, like this:
 9804: @example
 9805: struct
 9806: ...
 9807:     foo% field ...
 9808: ...
 9809: end-struct ...
 9810: @end example
 9811: 
 9812: @cindex structure extension
 9813: @cindex extended records
 9814: Instead of starting with an empty structure, you can extend an
 9815: existing structure. E.g., a plain linked list without data, as defined
 9816: above, is hardly useful; You can extend it to a linked list of integers,
 9817: like this:@footnote{This feature is also known as @emph{extended
 9818: records}. It is the main innovation in the Oberon language; in other
 9819: words, adding this feature to Modula-2 led Wirth to create a new
 9820: language, write a new compiler etc.  Adding this feature to Forth just
 9821: required a few lines of code.}
 9822: 
 9823: @example
 9824: list%
 9825:     cell% field intlist-int
 9826: end-struct intlist%
 9827: @end example
 9828: 
 9829: @code{intlist%} is a structure with two fields:
 9830: @code{list-next} and @code{intlist-int}.
 9831: 
 9832: @cindex structures containing arrays
 9833: You can specify an array type containing @emph{n} elements of
 9834: type @code{foo%} like this:
 9835: 
 9836: @example
 9837: foo% @emph{n} *
 9838: @end example
 9839: 
 9840: You can use this array type in any place where you can use a normal
 9841: type, e.g., when defining a @code{field}, or with
 9842: @code{%allot}.
 9843: 
 9844: @cindex first field optimization
 9845: The first field is at the base address of a structure and the word for
 9846: this field (e.g., @code{list-next}) actually does not change the address
 9847: on the stack. You may be tempted to leave it away in the interest of
 9848: run-time and space efficiency. This is not necessary, because the
 9849: structure package optimizes this case: If you compile a first-field
 9850: words, no code is generated. So, in the interest of readability and
 9851: maintainability you should include the word for the field when accessing
 9852: the field.
 9853: 
 9854: 
 9855: @node Structure Naming Convention, Structure Implementation, Structure Usage, Structures
 9856: @subsection Structure Naming Convention
 9857: @cindex structure naming convention
 9858: 
 9859: The field names that come to (my) mind are often quite generic, and,
 9860: if used, would cause frequent name clashes. E.g., many structures
 9861: probably contain a @code{counter} field. The structure names
 9862: that come to (my) mind are often also the logical choice for the names
 9863: of words that create such a structure.
 9864: 
 9865: Therefore, I have adopted the following naming conventions: 
 9866: 
 9867: @itemize @bullet
 9868: @cindex field naming convention
 9869: @item
 9870: The names of fields are of the form
 9871: @code{@emph{struct}-@emph{field}}, where
 9872: @code{@emph{struct}} is the basic name of the structure, and
 9873: @code{@emph{field}} is the basic name of the field. You can
 9874: think of field words as converting the (address of the)
 9875: structure into the (address of the) field.
 9876: 
 9877: @cindex structure naming convention
 9878: @item
 9879: The names of structures are of the form
 9880: @code{@emph{struct}%}, where
 9881: @code{@emph{struct}} is the basic name of the structure.
 9882: @end itemize
 9883: 
 9884: This naming convention does not work that well for fields of extended
 9885: structures; e.g., the integer list structure has a field
 9886: @code{intlist-int}, but has @code{list-next}, not
 9887: @code{intlist-next}.
 9888: 
 9889: @node Structure Implementation, Structure Glossary, Structure Naming Convention, Structures
 9890: @subsection Structure Implementation
 9891: @cindex structure implementation
 9892: @cindex implementation of structures
 9893: 
 9894: The central idea in the implementation is to pass the data about the
 9895: structure being built on the stack, not in some global
 9896: variable. Everything else falls into place naturally once this design
 9897: decision is made.
 9898: 
 9899: The type description on the stack is of the form @emph{align
 9900: size}. Keeping the size on the top-of-stack makes dealing with arrays
 9901: very simple.
 9902: 
 9903: @code{field} is a defining word that uses @code{Create}
 9904: and @code{DOES>}. The body of the field contains the offset
 9905: of the field, and the normal @code{DOES>} action is simply:
 9906: 
 9907: @example
 9908: @@ +
 9909: @end example
 9910: 
 9911: @noindent
 9912: i.e., add the offset to the address, giving the stack effect
 9913: @i{addr1 -- addr2} for a field.
 9914: 
 9915: @cindex first field optimization, implementation
 9916: This simple structure is slightly complicated by the optimization
 9917: for fields with offset 0, which requires a different
 9918: @code{DOES>}-part (because we cannot rely on there being
 9919: something on the stack if such a field is invoked during
 9920: compilation). Therefore, we put the different @code{DOES>}-parts
 9921: in separate words, and decide which one to invoke based on the
 9922: offset. For a zero offset, the field is basically a noop; it is
 9923: immediate, and therefore no code is generated when it is compiled.
 9924: 
 9925: @node Structure Glossary,  , Structure Implementation, Structures
 9926: @subsection Structure Glossary
 9927: @cindex structure glossary
 9928: 
 9929: 
 9930: doc-%align
 9931: doc-%alignment
 9932: doc-%alloc
 9933: doc-%allocate
 9934: doc-%allot
 9935: doc-cell%
 9936: doc-char%
 9937: doc-dfloat%
 9938: doc-double%
 9939: doc-end-struct
 9940: doc-field
 9941: doc-float%
 9942: doc-naligned
 9943: doc-sfloat%
 9944: doc-%size
 9945: doc-struct
 9946: 
 9947: 
 9948: @c -------------------------------------------------------------
 9949: @node Object-oriented Forth, Programming Tools, Structures, Words
 9950: @section Object-oriented Forth
 9951: 
 9952: Gforth comes with three packages for object-oriented programming:
 9953: @file{objects.fs}, @file{oof.fs}, and @file{mini-oof.fs}; none of them
 9954: is preloaded, so you have to @code{include} them before use. The most
 9955: important differences between these packages (and others) are discussed
 9956: in @ref{Comparison with other object models}. All packages are written
 9957: in ANS Forth and can be used with any other ANS Forth.
 9958: 
 9959: @menu
 9960: * Why object-oriented programming?::  
 9961: * Object-Oriented Terminology::  
 9962: * Objects::                     
 9963: * OOF::                         
 9964: * Mini-OOF::                    
 9965: * Comparison with other object models::  
 9966: @end menu
 9967: 
 9968: @c ----------------------------------------------------------------
 9969: @node Why object-oriented programming?, Object-Oriented Terminology, Object-oriented Forth, Object-oriented Forth
 9970: @subsection Why object-oriented programming?
 9971: @cindex object-oriented programming motivation
 9972: @cindex motivation for object-oriented programming
 9973: 
 9974: Often we have to deal with several data structures (@emph{objects}),
 9975: that have to be treated similarly in some respects, but differently in
 9976: others. Graphical objects are the textbook example: circles, triangles,
 9977: dinosaurs, icons, and others, and we may want to add more during program
 9978: development. We want to apply some operations to any graphical object,
 9979: e.g., @code{draw} for displaying it on the screen. However, @code{draw}
 9980: has to do something different for every kind of object.
 9981: @comment TODO add some other operations eg perimeter, area
 9982: @comment and tie in to concrete examples later..
 9983: 
 9984: We could implement @code{draw} as a big @code{CASE}
 9985: control structure that executes the appropriate code depending on the
 9986: kind of object to be drawn. This would be not be very elegant, and,
 9987: moreover, we would have to change @code{draw} every time we add
 9988: a new kind of graphical object (say, a spaceship).
 9989: 
 9990: What we would rather do is: When defining spaceships, we would tell
 9991: the system: ``Here's how you @code{draw} a spaceship; you figure
 9992: out the rest''.
 9993: 
 9994: This is the problem that all systems solve that (rightfully) call
 9995: themselves object-oriented; the object-oriented packages presented here
 9996: solve this problem (and not much else).
 9997: @comment TODO ?list properties of oo systems.. oo vs o-based?
 9998: 
 9999: @c ------------------------------------------------------------------------
10000: @node Object-Oriented Terminology, Objects, Why object-oriented programming?, Object-oriented Forth
10001: @subsection Object-Oriented Terminology
10002: @cindex object-oriented terminology
10003: @cindex terminology for object-oriented programming
10004: 
10005: This section is mainly for reference, so you don't have to understand
10006: all of it right away.  The terminology is mainly Smalltalk-inspired.  In
10007: short:
10008: 
10009: @table @emph
10010: @cindex class
10011: @item class
10012: a data structure definition with some extras.
10013: 
10014: @cindex object
10015: @item object
10016: an instance of the data structure described by the class definition.
10017: 
10018: @cindex instance variables
10019: @item instance variables
10020: fields of the data structure.
10021: 
10022: @cindex selector
10023: @cindex method selector
10024: @cindex virtual function
10025: @item selector
10026: (or @emph{method selector}) a word (e.g.,
10027: @code{draw}) that performs an operation on a variety of data
10028: structures (classes). A selector describes @emph{what} operation to
10029: perform. In C++ terminology: a (pure) virtual function.
10030: 
10031: @cindex method
10032: @item method
10033: the concrete definition that performs the operation
10034: described by the selector for a specific class. A method specifies
10035: @emph{how} the operation is performed for a specific class.
10036: 
10037: @cindex selector invocation
10038: @cindex message send
10039: @cindex invoking a selector
10040: @item selector invocation
10041: a call of a selector. One argument of the call (the TOS (top-of-stack))
10042: is used for determining which method is used. In Smalltalk terminology:
10043: a message (consisting of the selector and the other arguments) is sent
10044: to the object.
10045: 
10046: @cindex receiving object
10047: @item receiving object
10048: the object used for determining the method executed by a selector
10049: invocation. In the @file{objects.fs} model, it is the object that is on
10050: the TOS when the selector is invoked. (@emph{Receiving} comes from
10051: the Smalltalk @emph{message} terminology.)
10052: 
10053: @cindex child class
10054: @cindex parent class
10055: @cindex inheritance
10056: @item child class
10057: a class that has (@emph{inherits}) all properties (instance variables,
10058: selectors, methods) from a @emph{parent class}. In Smalltalk
10059: terminology: The subclass inherits from the superclass. In C++
10060: terminology: The derived class inherits from the base class.
10061: 
10062: @end table
10063: 
10064: @c If you wonder about the message sending terminology, it comes from
10065: @c a time when each object had it's own task and objects communicated via
10066: @c message passing; eventually the Smalltalk developers realized that
10067: @c they can do most things through simple (indirect) calls. They kept the
10068: @c terminology.
10069: 
10070: @c --------------------------------------------------------------
10071: @node Objects, OOF, Object-Oriented Terminology, Object-oriented Forth
10072: @subsection The @file{objects.fs} model
10073: @cindex objects
10074: @cindex object-oriented programming
10075: 
10076: @cindex @file{objects.fs}
10077: @cindex @file{oof.fs}
10078: 
10079: This section describes the @file{objects.fs} package. This material also
10080: has been published in M. Anton Ertl,
10081: @cite{@uref{http://www.complang.tuwien.ac.at/forth/objects/objects.html,
10082: Yet Another Forth Objects Package}}, Forth Dimensions 19(2), pages
10083: 37--43.
10084: @c McKewan's and Zsoter's packages
10085: 
10086: This section assumes that you have read @ref{Structures}.
10087: 
10088: The techniques on which this model is based have been used to implement
10089: the parser generator, Gray, and have also been used in Gforth for
10090: implementing the various flavours of word lists (hashed or not,
10091: case-sensitive or not, special-purpose word lists for locals etc.).
10092: 
10093: 
10094: @menu
10095: * Properties of the Objects model::  
10096: * Basic Objects Usage::         
10097: * The Objects base class::      
10098: * Creating objects::            
10099: * Object-Oriented Programming Style::  
10100: * Class Binding::               
10101: * Method conveniences::         
10102: * Classes and Scoping::         
10103: * Dividing classes::            
10104: * Object Interfaces::           
10105: * Objects Implementation::      
10106: * Objects Glossary::            
10107: @end menu
10108: 
10109: Marcel Hendrix provided helpful comments on this section.
10110: 
10111: @node Properties of the Objects model, Basic Objects Usage, Objects, Objects
10112: @subsubsection Properties of the @file{objects.fs} model
10113: @cindex @file{objects.fs} properties
10114: 
10115: @itemize @bullet
10116: @item
10117: It is straightforward to pass objects on the stack. Passing
10118: selectors on the stack is a little less convenient, but possible.
10119: 
10120: @item
10121: Objects are just data structures in memory, and are referenced by their
10122: address. You can create words for objects with normal defining words
10123: like @code{constant}. Likewise, there is no difference between instance
10124: variables that contain objects and those that contain other data.
10125: 
10126: @item
10127: Late binding is efficient and easy to use.
10128: 
10129: @item
10130: It avoids parsing, and thus avoids problems with state-smartness
10131: and reduced extensibility; for convenience there are a few parsing
10132: words, but they have non-parsing counterparts. There are also a few
10133: defining words that parse. This is hard to avoid, because all standard
10134: defining words parse (except @code{:noname}); however, such
10135: words are not as bad as many other parsing words, because they are not
10136: state-smart.
10137: 
10138: @item
10139: It does not try to incorporate everything. It does a few things and does
10140: them well (IMO). In particular, this model was not designed to support
10141: information hiding (although it has features that may help); you can use
10142: a separate package for achieving this.
10143: 
10144: @item
10145: It is layered; you don't have to learn and use all features to use this
10146: model. Only a few features are necessary (@pxref{Basic Objects Usage},
10147: @pxref{The Objects base class}, @pxref{Creating objects}.), the others
10148: are optional and independent of each other.
10149: 
10150: @item
10151: An implementation in ANS Forth is available.
10152: 
10153: @end itemize
10154: 
10155: 
10156: @node Basic Objects Usage, The Objects base class, Properties of the Objects model, Objects
10157: @subsubsection Basic @file{objects.fs} Usage
10158: @cindex basic objects usage
10159: @cindex objects, basic usage
10160: 
10161: You can define a class for graphical objects like this:
10162: 
10163: @cindex @code{class} usage
10164: @cindex @code{end-class} usage
10165: @cindex @code{selector} usage
10166: @example
10167: object class \ "object" is the parent class
10168:   selector draw ( x y graphical -- )
10169: end-class graphical
10170: @end example
10171: 
10172: This code defines a class @code{graphical} with an
10173: operation @code{draw}.  We can perform the operation
10174: @code{draw} on any @code{graphical} object, e.g.:
10175: 
10176: @example
10177: 100 100 t-rex draw
10178: @end example
10179: 
10180: @noindent
10181: where @code{t-rex} is a word (say, a constant) that produces a
10182: graphical object.
10183: 
10184: @comment TODO add a 2nd operation eg perimeter.. and use for
10185: @comment a concrete example
10186: 
10187: @cindex abstract class
10188: How do we create a graphical object? With the present definitions,
10189: we cannot create a useful graphical object. The class
10190: @code{graphical} describes graphical objects in general, but not
10191: any concrete graphical object type (C++ users would call it an
10192: @emph{abstract class}); e.g., there is no method for the selector
10193: @code{draw} in the class @code{graphical}.
10194: 
10195: For concrete graphical objects, we define child classes of the
10196: class @code{graphical}, e.g.:
10197: 
10198: @cindex @code{overrides} usage
10199: @cindex @code{field} usage in class definition
10200: @example
10201: graphical class \ "graphical" is the parent class
10202:   cell% field circle-radius
10203: 
10204: :noname ( x y circle -- )
10205:   circle-radius @@ draw-circle ;
10206: overrides draw
10207: 
10208: :noname ( n-radius circle -- )
10209:   circle-radius ! ;
10210: overrides construct
10211: 
10212: end-class circle
10213: @end example
10214: 
10215: Here we define a class @code{circle} as a child of @code{graphical},
10216: with field @code{circle-radius} (which behaves just like a field
10217: (@pxref{Structures}); it defines (using @code{overrides}) new methods
10218: for the selectors @code{draw} and @code{construct} (@code{construct} is
10219: defined in @code{object}, the parent class of @code{graphical}).
10220: 
10221: Now we can create a circle on the heap (i.e.,
10222: @code{allocate}d memory) with:
10223: 
10224: @cindex @code{heap-new} usage
10225: @example
10226: 50 circle heap-new constant my-circle
10227: @end example
10228: 
10229: @noindent
10230: @code{heap-new} invokes @code{construct}, thus
10231: initializing the field @code{circle-radius} with 50. We can draw
10232: this new circle at (100,100) with:
10233: 
10234: @example
10235: 100 100 my-circle draw
10236: @end example
10237: 
10238: @cindex selector invocation, restrictions
10239: @cindex class definition, restrictions
10240: Note: You can only invoke a selector if the object on the TOS
10241: (the receiving object) belongs to the class where the selector was
10242: defined or one of its descendents; e.g., you can invoke
10243: @code{draw} only for objects belonging to @code{graphical}
10244: or its descendents (e.g., @code{circle}).  Immediately before
10245: @code{end-class}, the search order has to be the same as
10246: immediately after @code{class}.
10247: 
10248: @node The Objects base class, Creating objects, Basic Objects Usage, Objects
10249: @subsubsection The @file{object.fs} base class
10250: @cindex @code{object} class
10251: 
10252: When you define a class, you have to specify a parent class.  So how do
10253: you start defining classes? There is one class available from the start:
10254: @code{object}. It is ancestor for all classes and so is the
10255: only class that has no parent. It has two selectors: @code{construct}
10256: and @code{print}.
10257: 
10258: @node Creating objects, Object-Oriented Programming Style, The Objects base class, Objects
10259: @subsubsection Creating objects
10260: @cindex creating objects
10261: @cindex object creation
10262: @cindex object allocation options
10263: 
10264: @cindex @code{heap-new} discussion
10265: @cindex @code{dict-new} discussion
10266: @cindex @code{construct} discussion
10267: You can create and initialize an object of a class on the heap with
10268: @code{heap-new} ( ... class -- object ) and in the dictionary
10269: (allocation with @code{allot}) with @code{dict-new} (
10270: ... class -- object ). Both words invoke @code{construct}, which
10271: consumes the stack items indicated by "..." above.
10272: 
10273: @cindex @code{init-object} discussion
10274: @cindex @code{class-inst-size} discussion
10275: If you want to allocate memory for an object yourself, you can get its
10276: alignment and size with @code{class-inst-size 2@@} ( class --
10277: align size ). Once you have memory for an object, you can initialize
10278: it with @code{init-object} ( ... class object -- );
10279: @code{construct} does only a part of the necessary work.
10280: 
10281: @node Object-Oriented Programming Style, Class Binding, Creating objects, Objects
10282: @subsubsection Object-Oriented Programming Style
10283: @cindex object-oriented programming style
10284: @cindex programming style, object-oriented
10285: 
10286: This section is not exhaustive.
10287: 
10288: @cindex stack effects of selectors
10289: @cindex selectors and stack effects
10290: In general, it is a good idea to ensure that all methods for the
10291: same selector have the same stack effect: when you invoke a selector,
10292: you often have no idea which method will be invoked, so, unless all
10293: methods have the same stack effect, you will not know the stack effect
10294: of the selector invocation.
10295: 
10296: One exception to this rule is methods for the selector
10297: @code{construct}. We know which method is invoked, because we
10298: specify the class to be constructed at the same place. Actually, I
10299: defined @code{construct} as a selector only to give the users a
10300: convenient way to specify initialization. The way it is used, a
10301: mechanism different from selector invocation would be more natural
10302: (but probably would take more code and more space to explain).
10303: 
10304: @node Class Binding, Method conveniences, Object-Oriented Programming Style, Objects
10305: @subsubsection Class Binding
10306: @cindex class binding
10307: @cindex early binding
10308: 
10309: @cindex late binding
10310: Normal selector invocations determine the method at run-time depending
10311: on the class of the receiving object. This run-time selection is called
10312: @i{late binding}.
10313: 
10314: Sometimes it's preferable to invoke a different method. For example,
10315: you might want to use the simple method for @code{print}ing
10316: @code{object}s instead of the possibly long-winded @code{print} method
10317: of the receiver class. You can achieve this by replacing the invocation
10318: of @code{print} with:
10319: 
10320: @cindex @code{[bind]} usage
10321: @example
10322: [bind] object print
10323: @end example
10324: 
10325: @noindent
10326: in compiled code or:
10327: 
10328: @cindex @code{bind} usage
10329: @example
10330: bind object print
10331: @end example
10332: 
10333: @cindex class binding, alternative to
10334: @noindent
10335: in interpreted code. Alternatively, you can define the method with a
10336: name (e.g., @code{print-object}), and then invoke it through the
10337: name. Class binding is just a (often more convenient) way to achieve
10338: the same effect; it avoids name clutter and allows you to invoke
10339: methods directly without naming them first.
10340: 
10341: @cindex superclass binding
10342: @cindex parent class binding
10343: A frequent use of class binding is this: When we define a method
10344: for a selector, we often want the method to do what the selector does
10345: in the parent class, and a little more. There is a special word for
10346: this purpose: @code{[parent]}; @code{[parent]
10347: @emph{selector}} is equivalent to @code{[bind] @emph{parent
10348: selector}}, where @code{@emph{parent}} is the parent
10349: class of the current class. E.g., a method definition might look like:
10350: 
10351: @cindex @code{[parent]} usage
10352: @example
10353: :noname
10354:   dup [parent] foo \ do parent's foo on the receiving object
10355:   ... \ do some more
10356: ; overrides foo
10357: @end example
10358: 
10359: @cindex class binding as optimization
10360: In @cite{Object-oriented programming in ANS Forth} (Forth Dimensions,
10361: March 1997), Andrew McKewan presents class binding as an optimization
10362: technique. I recommend not using it for this purpose unless you are in
10363: an emergency. Late binding is pretty fast with this model anyway, so the
10364: benefit of using class binding is small; the cost of using class binding
10365: where it is not appropriate is reduced maintainability.
10366: 
10367: While we are at programming style questions: You should bind
10368: selectors only to ancestor classes of the receiving object. E.g., say,
10369: you know that the receiving object is of class @code{foo} or its
10370: descendents; then you should bind only to @code{foo} and its
10371: ancestors.
10372: 
10373: @node Method conveniences, Classes and Scoping, Class Binding, Objects
10374: @subsubsection Method conveniences
10375: @cindex method conveniences
10376: 
10377: In a method you usually access the receiving object pretty often.  If
10378: you define the method as a plain colon definition (e.g., with
10379: @code{:noname}), you may have to do a lot of stack
10380: gymnastics. To avoid this, you can define the method with @code{m:
10381: ... ;m}. E.g., you could define the method for
10382: @code{draw}ing a @code{circle} with
10383: 
10384: @cindex @code{this} usage
10385: @cindex @code{m:} usage
10386: @cindex @code{;m} usage
10387: @example
10388: m: ( x y circle -- )
10389:   ( x y ) this circle-radius @@ draw-circle ;m
10390: @end example
10391: 
10392: @cindex @code{exit} in @code{m: ... ;m}
10393: @cindex @code{exitm} discussion
10394: @cindex @code{catch} in @code{m: ... ;m}
10395: When this method is executed, the receiver object is removed from the
10396: stack; you can access it with @code{this} (admittedly, in this
10397: example the use of @code{m: ... ;m} offers no advantage). Note
10398: that I specify the stack effect for the whole method (i.e. including
10399: the receiver object), not just for the code between @code{m:}
10400: and @code{;m}. You cannot use @code{exit} in
10401: @code{m:...;m}; instead, use
10402: @code{exitm}.@footnote{Moreover, for any word that calls
10403: @code{catch} and was defined before loading
10404: @code{objects.fs}, you have to redefine it like I redefined
10405: @code{catch}: @code{: catch this >r catch r> to-this ;}}
10406: 
10407: @cindex @code{inst-var} usage
10408: You will frequently use sequences of the form @code{this
10409: @emph{field}} (in the example above: @code{this
10410: circle-radius}). If you use the field only in this way, you can
10411: define it with @code{inst-var} and eliminate the
10412: @code{this} before the field name. E.g., the @code{circle}
10413: class above could also be defined with:
10414: 
10415: @example
10416: graphical class
10417:   cell% inst-var radius
10418: 
10419: m: ( x y circle -- )
10420:   radius @@ draw-circle ;m
10421: overrides draw
10422: 
10423: m: ( n-radius circle -- )
10424:   radius ! ;m
10425: overrides construct
10426: 
10427: end-class circle
10428: @end example
10429: 
10430: @code{radius} can only be used in @code{circle} and its
10431: descendent classes and inside @code{m:...;m}.
10432: 
10433: @cindex @code{inst-value} usage
10434: You can also define fields with @code{inst-value}, which is
10435: to @code{inst-var} what @code{value} is to
10436: @code{variable}.  You can change the value of such a field with
10437: @code{[to-inst]}.  E.g., we could also define the class
10438: @code{circle} like this:
10439: 
10440: @example
10441: graphical class
10442:   inst-value radius
10443: 
10444: m: ( x y circle -- )
10445:   radius draw-circle ;m
10446: overrides draw
10447: 
10448: m: ( n-radius circle -- )
10449:   [to-inst] radius ;m
10450: overrides construct
10451: 
10452: end-class circle
10453: @end example
10454: 
10455: @c !! :m is easy to confuse with m:.  Another name would be better.
10456: 
10457: @c Finally, you can define named methods with @code{:m}.  One use of this
10458: @c feature is the definition of words that occur only in one class and are
10459: @c not intended to be overridden, but which still need method context
10460: @c (e.g., for accessing @code{inst-var}s).  Another use is for methods that
10461: @c would be bound frequently, if defined anonymously.
10462: 
10463: 
10464: @node Classes and Scoping, Dividing classes, Method conveniences, Objects
10465: @subsubsection Classes and Scoping
10466: @cindex classes and scoping
10467: @cindex scoping and classes
10468: 
10469: Inheritance is frequent, unlike structure extension. This exacerbates
10470: the problem with the field name convention (@pxref{Structure Naming
10471: Convention}): One always has to remember in which class the field was
10472: originally defined; changing a part of the class structure would require
10473: changes for renaming in otherwise unaffected code.
10474: 
10475: @cindex @code{inst-var} visibility
10476: @cindex @code{inst-value} visibility
10477: To solve this problem, I added a scoping mechanism (which was not in my
10478: original charter): A field defined with @code{inst-var} (or
10479: @code{inst-value}) is visible only in the class where it is defined and in
10480: the descendent classes of this class.  Using such fields only makes
10481: sense in @code{m:}-defined methods in these classes anyway.
10482: 
10483: This scoping mechanism allows us to use the unadorned field name,
10484: because name clashes with unrelated words become much less likely.
10485: 
10486: @cindex @code{protected} discussion
10487: @cindex @code{private} discussion
10488: Once we have this mechanism, we can also use it for controlling the
10489: visibility of other words: All words defined after
10490: @code{protected} are visible only in the current class and its
10491: descendents. @code{public} restores the compilation
10492: (i.e. @code{current}) word list that was in effect before. If you
10493: have several @code{protected}s without an intervening
10494: @code{public} or @code{set-current}, @code{public}
10495: will restore the compilation word list in effect before the first of
10496: these @code{protected}s.
10497: 
10498: @node Dividing classes, Object Interfaces, Classes and Scoping, Objects
10499: @subsubsection Dividing classes
10500: @cindex Dividing classes
10501: @cindex @code{methods}...@code{end-methods}
10502: 
10503: You may want to do the definition of methods separate from the
10504: definition of the class, its selectors, fields, and instance variables,
10505: i.e., separate the implementation from the definition.  You can do this
10506: in the following way:
10507: 
10508: @example
10509: graphical class
10510:   inst-value radius
10511: end-class circle
10512: 
10513: ... \ do some other stuff
10514: 
10515: circle methods \ now we are ready
10516: 
10517: m: ( x y circle -- )
10518:   radius draw-circle ;m
10519: overrides draw
10520: 
10521: m: ( n-radius circle -- )
10522:   [to-inst] radius ;m
10523: overrides construct
10524: 
10525: end-methods
10526: @end example
10527: 
10528: You can use several @code{methods}...@code{end-methods} sections.  The
10529: only things you can do to the class in these sections are: defining
10530: methods, and overriding the class's selectors.  You must not define new
10531: selectors or fields.
10532: 
10533: Note that you often have to override a selector before using it.  In
10534: particular, you usually have to override @code{construct} with a new
10535: method before you can invoke @code{heap-new} and friends.  E.g., you
10536: must not create a circle before the @code{overrides construct} sequence
10537: in the example above.
10538: 
10539: @node Object Interfaces, Objects Implementation, Dividing classes, Objects
10540: @subsubsection Object Interfaces
10541: @cindex object interfaces
10542: @cindex interfaces for objects
10543: 
10544: In this model you can only call selectors defined in the class of the
10545: receiving objects or in one of its ancestors. If you call a selector
10546: with a receiving object that is not in one of these classes, the
10547: result is undefined; if you are lucky, the program crashes
10548: immediately.
10549: 
10550: @cindex selectors common to hardly-related classes
10551: Now consider the case when you want to have a selector (or several)
10552: available in two classes: You would have to add the selector to a
10553: common ancestor class, in the worst case to @code{object}. You
10554: may not want to do this, e.g., because someone else is responsible for
10555: this ancestor class.
10556: 
10557: The solution for this problem is interfaces. An interface is a
10558: collection of selectors. If a class implements an interface, the
10559: selectors become available to the class and its descendents. A class
10560: can implement an unlimited number of interfaces. For the problem
10561: discussed above, we would define an interface for the selector(s), and
10562: both classes would implement the interface.
10563: 
10564: As an example, consider an interface @code{storage} for
10565: writing objects to disk and getting them back, and a class
10566: @code{foo} that implements it. The code would look like this:
10567: 
10568: @cindex @code{interface} usage
10569: @cindex @code{end-interface} usage
10570: @cindex @code{implementation} usage
10571: @example
10572: interface
10573:   selector write ( file object -- )
10574:   selector read1 ( file object -- )
10575: end-interface storage
10576: 
10577: bar class
10578:   storage implementation
10579: 
10580: ... overrides write
10581: ... overrides read1
10582: ...
10583: end-class foo
10584: @end example
10585: 
10586: @noindent
10587: (I would add a word @code{read} @i{( file -- object )} that uses
10588: @code{read1} internally, but that's beyond the point illustrated
10589: here.)
10590: 
10591: Note that you cannot use @code{protected} in an interface; and
10592: of course you cannot define fields.
10593: 
10594: In the Neon model, all selectors are available for all classes;
10595: therefore it does not need interfaces. The price you pay in this model
10596: is slower late binding, and therefore, added complexity to avoid late
10597: binding.
10598: 
10599: @node Objects Implementation, Objects Glossary, Object Interfaces, Objects
10600: @subsubsection @file{objects.fs} Implementation
10601: @cindex @file{objects.fs} implementation
10602: 
10603: @cindex @code{object-map} discussion
10604: An object is a piece of memory, like one of the data structures
10605: described with @code{struct...end-struct}. It has a field
10606: @code{object-map} that points to the method map for the object's
10607: class.
10608: 
10609: @cindex method map
10610: @cindex virtual function table
10611: The @emph{method map}@footnote{This is Self terminology; in C++
10612: terminology: virtual function table.} is an array that contains the
10613: execution tokens (@i{xt}s) of the methods for the object's class. Each
10614: selector contains an offset into a method map.
10615: 
10616: @cindex @code{selector} implementation, class
10617: @code{selector} is a defining word that uses
10618: @code{CREATE} and @code{DOES>}. The body of the
10619: selector contains the offset; the @code{DOES>} action for a
10620: class selector is, basically:
10621: 
10622: @example
10623: ( object addr ) @@ over object-map @@ + @@ execute
10624: @end example
10625: 
10626: Since @code{object-map} is the first field of the object, it
10627: does not generate any code. As you can see, calling a selector has a
10628: small, constant cost.
10629: 
10630: @cindex @code{current-interface} discussion
10631: @cindex class implementation and representation
10632: A class is basically a @code{struct} combined with a method
10633: map. During the class definition the alignment and size of the class
10634: are passed on the stack, just as with @code{struct}s, so
10635: @code{field} can also be used for defining class
10636: fields. However, passing more items on the stack would be
10637: inconvenient, so @code{class} builds a data structure in memory,
10638: which is accessed through the variable
10639: @code{current-interface}. After its definition is complete, the
10640: class is represented on the stack by a pointer (e.g., as parameter for
10641: a child class definition).
10642: 
10643: A new class starts off with the alignment and size of its parent,
10644: and a copy of the parent's method map. Defining new fields extends the
10645: size and alignment; likewise, defining new selectors extends the
10646: method map. @code{overrides} just stores a new @i{xt} in the method
10647: map at the offset given by the selector.
10648: 
10649: @cindex class binding, implementation
10650: Class binding just gets the @i{xt} at the offset given by the selector
10651: from the class's method map and @code{compile,}s (in the case of
10652: @code{[bind]}) it.
10653: 
10654: @cindex @code{this} implementation
10655: @cindex @code{catch} and @code{this}
10656: @cindex @code{this} and @code{catch}
10657: I implemented @code{this} as a @code{value}. At the
10658: start of an @code{m:...;m} method the old @code{this} is
10659: stored to the return stack and restored at the end; and the object on
10660: the TOS is stored @code{TO this}. This technique has one
10661: disadvantage: If the user does not leave the method via
10662: @code{;m}, but via @code{throw} or @code{exit},
10663: @code{this} is not restored (and @code{exit} may
10664: crash). To deal with the @code{throw} problem, I have redefined
10665: @code{catch} to save and restore @code{this}; the same
10666: should be done with any word that can catch an exception. As for
10667: @code{exit}, I simply forbid it (as a replacement, there is
10668: @code{exitm}).
10669: 
10670: @cindex @code{inst-var} implementation
10671: @code{inst-var} is just the same as @code{field}, with
10672: a different @code{DOES>} action:
10673: @example
10674: @@ this +
10675: @end example
10676: Similar for @code{inst-value}.
10677: 
10678: @cindex class scoping implementation
10679: Each class also has a word list that contains the words defined with
10680: @code{inst-var} and @code{inst-value}, and its protected
10681: words. It also has a pointer to its parent. @code{class} pushes
10682: the word lists of the class and all its ancestors onto the search order stack,
10683: and @code{end-class} drops them.
10684: 
10685: @cindex interface implementation
10686: An interface is like a class without fields, parent and protected
10687: words; i.e., it just has a method map. If a class implements an
10688: interface, its method map contains a pointer to the method map of the
10689: interface. The positive offsets in the map are reserved for class
10690: methods, therefore interface map pointers have negative
10691: offsets. Interfaces have offsets that are unique throughout the
10692: system, unlike class selectors, whose offsets are only unique for the
10693: classes where the selector is available (invokable).
10694: 
10695: This structure means that interface selectors have to perform one
10696: indirection more than class selectors to find their method. Their body
10697: contains the interface map pointer offset in the class method map, and
10698: the method offset in the interface method map. The
10699: @code{does>} action for an interface selector is, basically:
10700: 
10701: @example
10702: ( object selector-body )
10703: 2dup selector-interface @@ ( object selector-body object interface-offset )
10704: swap object-map @@ + @@ ( object selector-body map )
10705: swap selector-offset @@ + @@ execute
10706: @end example
10707: 
10708: where @code{object-map} and @code{selector-offset} are
10709: first fields and generate no code.
10710: 
10711: As a concrete example, consider the following code:
10712: 
10713: @example
10714: interface
10715:   selector if1sel1
10716:   selector if1sel2
10717: end-interface if1
10718: 
10719: object class
10720:   if1 implementation
10721:   selector cl1sel1
10722:   cell% inst-var cl1iv1
10723: 
10724: ' m1 overrides construct
10725: ' m2 overrides if1sel1
10726: ' m3 overrides if1sel2
10727: ' m4 overrides cl1sel2
10728: end-class cl1
10729: 
10730: create obj1 object dict-new drop
10731: create obj2 cl1    dict-new drop
10732: @end example
10733: 
10734: The data structure created by this code (including the data structure
10735: for @code{object}) is shown in the
10736: @uref{objects-implementation.eps,figure}, assuming a cell size of 4.
10737: @comment TODO add this diagram..
10738: 
10739: @node Objects Glossary,  , Objects Implementation, Objects
10740: @subsubsection @file{objects.fs} Glossary
10741: @cindex @file{objects.fs} Glossary
10742: 
10743: 
10744: doc---objects-bind
10745: doc---objects-<bind>
10746: doc---objects-bind'
10747: doc---objects-[bind]
10748: doc---objects-class
10749: doc---objects-class->map
10750: doc---objects-class-inst-size
10751: doc---objects-class-override!
10752: doc---objects-class-previous
10753: doc---objects-class>order
10754: doc---objects-construct
10755: doc---objects-current'
10756: doc---objects-[current]
10757: doc---objects-current-interface
10758: doc---objects-dict-new
10759: doc---objects-end-class
10760: doc---objects-end-class-noname
10761: doc---objects-end-interface
10762: doc---objects-end-interface-noname
10763: doc---objects-end-methods
10764: doc---objects-exitm
10765: doc---objects-heap-new
10766: doc---objects-implementation
10767: doc---objects-init-object
10768: doc---objects-inst-value
10769: doc---objects-inst-var
10770: doc---objects-interface
10771: doc---objects-m:
10772: doc---objects-:m
10773: doc---objects-;m
10774: doc---objects-method
10775: doc---objects-methods
10776: doc---objects-object
10777: doc---objects-overrides
10778: doc---objects-[parent]
10779: doc---objects-print
10780: doc---objects-protected
10781: doc---objects-public
10782: doc---objects-selector
10783: doc---objects-this
10784: doc---objects-<to-inst>
10785: doc---objects-[to-inst]
10786: doc---objects-to-this
10787: doc---objects-xt-new
10788: 
10789: 
10790: @c -------------------------------------------------------------
10791: @node OOF, Mini-OOF, Objects, Object-oriented Forth
10792: @subsection The @file{oof.fs} model
10793: @cindex oof
10794: @cindex object-oriented programming
10795: 
10796: @cindex @file{objects.fs}
10797: @cindex @file{oof.fs}
10798: 
10799: This section describes the @file{oof.fs} package.
10800: 
10801: The package described in this section has been used in bigFORTH since 1991, and
10802: used for two large applications: a chromatographic system used to
10803: create new medicaments, and a graphic user interface library (MINOS).
10804: 
10805: You can find a description (in German) of @file{oof.fs} in @cite{Object
10806: oriented bigFORTH} by Bernd Paysan, published in @cite{Vierte Dimension}
10807: 10(2), 1994.
10808: 
10809: @menu
10810: * Properties of the OOF model::  
10811: * Basic OOF Usage::             
10812: * The OOF base class::          
10813: * Class Declaration::           
10814: * Class Implementation::        
10815: @end menu
10816: 
10817: @node Properties of the OOF model, Basic OOF Usage, OOF, OOF
10818: @subsubsection Properties of the @file{oof.fs} model
10819: @cindex @file{oof.fs} properties
10820: 
10821: @itemize @bullet
10822: @item
10823: This model combines object oriented programming with information
10824: hiding. It helps you writing large application, where scoping is
10825: necessary, because it provides class-oriented scoping.
10826: 
10827: @item
10828: Named objects, object pointers, and object arrays can be created,
10829: selector invocation uses the ``object selector'' syntax. Selector invocation
10830: to objects and/or selectors on the stack is a bit less convenient, but
10831: possible.
10832: 
10833: @item
10834: Selector invocation and instance variable usage of the active object is
10835: straightforward, since both make use of the active object.
10836: 
10837: @item
10838: Late binding is efficient and easy to use.
10839: 
10840: @item
10841: State-smart objects parse selectors. However, extensibility is provided
10842: using a (parsing) selector @code{postpone} and a selector @code{'}.
10843: 
10844: @item
10845: An implementation in ANS Forth is available.
10846: 
10847: @end itemize
10848: 
10849: 
10850: @node Basic OOF Usage, The OOF base class, Properties of the OOF model, OOF
10851: @subsubsection Basic @file{oof.fs} Usage
10852: @cindex @file{oof.fs} usage
10853: 
10854: This section uses the same example as for @code{objects} (@pxref{Basic Objects Usage}).
10855: 
10856: You can define a class for graphical objects like this:
10857: 
10858: @cindex @code{class} usage
10859: @cindex @code{class;} usage
10860: @cindex @code{method} usage
10861: @example
10862: object class graphical \ "object" is the parent class
10863:   method draw ( x y -- )
10864: class;
10865: @end example
10866: 
10867: This code defines a class @code{graphical} with an
10868: operation @code{draw}.  We can perform the operation
10869: @code{draw} on any @code{graphical} object, e.g.:
10870: 
10871: @example
10872: 100 100 t-rex draw
10873: @end example
10874: 
10875: @noindent
10876: where @code{t-rex} is an object or object pointer, created with e.g.
10877: @code{graphical : t-rex}.
10878: 
10879: @cindex abstract class
10880: How do we create a graphical object? With the present definitions,
10881: we cannot create a useful graphical object. The class
10882: @code{graphical} describes graphical objects in general, but not
10883: any concrete graphical object type (C++ users would call it an
10884: @emph{abstract class}); e.g., there is no method for the selector
10885: @code{draw} in the class @code{graphical}.
10886: 
10887: For concrete graphical objects, we define child classes of the
10888: class @code{graphical}, e.g.:
10889: 
10890: @example
10891: graphical class circle \ "graphical" is the parent class
10892:   cell var circle-radius
10893: how:
10894:   : draw ( x y -- )
10895:     circle-radius @@ draw-circle ;
10896: 
10897:   : init ( n-radius -- )
10898:     circle-radius ! ;
10899: class;
10900: @end example
10901: 
10902: Here we define a class @code{circle} as a child of @code{graphical},
10903: with a field @code{circle-radius}; it defines new methods for the
10904: selectors @code{draw} and @code{init} (@code{init} is defined in
10905: @code{object}, the parent class of @code{graphical}).
10906: 
10907: Now we can create a circle in the dictionary with:
10908: 
10909: @example
10910: 50 circle : my-circle
10911: @end example
10912: 
10913: @noindent
10914: @code{:} invokes @code{init}, thus initializing the field
10915: @code{circle-radius} with 50. We can draw this new circle at (100,100)
10916: with:
10917: 
10918: @example
10919: 100 100 my-circle draw
10920: @end example
10921: 
10922: @cindex selector invocation, restrictions
10923: @cindex class definition, restrictions
10924: Note: You can only invoke a selector if the receiving object belongs to
10925: the class where the selector was defined or one of its descendents;
10926: e.g., you can invoke @code{draw} only for objects belonging to
10927: @code{graphical} or its descendents (e.g., @code{circle}). The scoping
10928: mechanism will check if you try to invoke a selector that is not
10929: defined in this class hierarchy, so you'll get an error at compilation
10930: time.
10931: 
10932: 
10933: @node The OOF base class, Class Declaration, Basic OOF Usage, OOF
10934: @subsubsection The @file{oof.fs} base class
10935: @cindex @file{oof.fs} base class
10936: 
10937: When you define a class, you have to specify a parent class.  So how do
10938: you start defining classes? There is one class available from the start:
10939: @code{object}. You have to use it as ancestor for all classes. It is the
10940: only class that has no parent. Classes are also objects, except that
10941: they don't have instance variables; class manipulation such as
10942: inheritance or changing definitions of a class is handled through
10943: selectors of the class @code{object}.
10944: 
10945: @code{object} provides a number of selectors:
10946: 
10947: @itemize @bullet
10948: @item
10949: @code{class} for subclassing, @code{definitions} to add definitions
10950: later on, and @code{class?} to get type informations (is the class a
10951: subclass of the class passed on the stack?).
10952: 
10953: doc---object-class
10954: doc---object-definitions
10955: doc---object-class?
10956: 
10957: 
10958: @item
10959: @code{init} and @code{dispose} as constructor and destructor of the
10960: object. @code{init} is invocated after the object's memory is allocated,
10961: while @code{dispose} also handles deallocation. Thus if you redefine
10962: @code{dispose}, you have to call the parent's dispose with @code{super
10963: dispose}, too.
10964: 
10965: doc---object-init
10966: doc---object-dispose
10967: 
10968: 
10969: @item
10970: @code{new}, @code{new[]}, @code{:}, @code{ptr}, @code{asptr}, and
10971: @code{[]} to create named and unnamed objects and object arrays or
10972: object pointers.
10973: 
10974: doc---object-new
10975: doc---object-new[]
10976: doc---object-:
10977: doc---object-ptr
10978: doc---object-asptr
10979: doc---object-[]
10980: 
10981: 
10982: @item
10983: @code{::} and @code{super} for explicit scoping. You should use explicit
10984: scoping only for super classes or classes with the same set of instance
10985: variables. Explicitly-scoped selectors use early binding.
10986: 
10987: doc---object-::
10988: doc---object-super
10989: 
10990: 
10991: @item
10992: @code{self} to get the address of the object
10993: 
10994: doc---object-self
10995: 
10996: 
10997: @item
10998: @code{bind}, @code{bound}, @code{link}, and @code{is} to assign object
10999: pointers and instance defers.
11000: 
11001: doc---object-bind
11002: doc---object-bound
11003: doc---object-link
11004: doc---object-is
11005: 
11006: 
11007: @item
11008: @code{'} to obtain selector tokens, @code{send} to invocate selectors
11009: form the stack, and @code{postpone} to generate selector invocation code.
11010: 
11011: doc---object-'
11012: doc---object-postpone
11013: 
11014: 
11015: @item
11016: @code{with} and @code{endwith} to select the active object from the
11017: stack, and enable its scope. Using @code{with} and @code{endwith}
11018: also allows you to create code using selector @code{postpone} without being
11019: trapped by the state-smart objects.
11020: 
11021: doc---object-with
11022: doc---object-endwith
11023: 
11024: 
11025: @end itemize
11026: 
11027: @node Class Declaration, Class Implementation, The OOF base class, OOF
11028: @subsubsection Class Declaration
11029: @cindex class declaration
11030: 
11031: @itemize @bullet
11032: @item
11033: Instance variables
11034: 
11035: doc---oof-var
11036: 
11037: 
11038: @item
11039: Object pointers
11040: 
11041: doc---oof-ptr
11042: doc---oof-asptr
11043: 
11044: 
11045: @item
11046: Instance defers
11047: 
11048: doc---oof-defer
11049: 
11050: 
11051: @item
11052: Method selectors
11053: 
11054: doc---oof-early
11055: doc---oof-method
11056: 
11057: 
11058: @item
11059: Class-wide variables
11060: 
11061: doc---oof-static
11062: 
11063: 
11064: @item
11065: End declaration
11066: 
11067: doc---oof-how:
11068: doc---oof-class;
11069: 
11070: 
11071: @end itemize
11072: 
11073: @c -------------------------------------------------------------
11074: @node Class Implementation,  , Class Declaration, OOF
11075: @subsubsection Class Implementation
11076: @cindex class implementation
11077: 
11078: @c -------------------------------------------------------------
11079: @node Mini-OOF, Comparison with other object models, OOF, Object-oriented Forth
11080: @subsection The @file{mini-oof.fs} model
11081: @cindex mini-oof
11082: 
11083: Gforth's third object oriented Forth package is a 12-liner. It uses a
11084: mixture of the @file{objects.fs} and the @file{oof.fs} syntax,
11085: and reduces to the bare minimum of features. This is based on a posting
11086: of Bernd Paysan in comp.lang.forth.
11087: 
11088: @menu
11089: * Basic Mini-OOF Usage::        
11090: * Mini-OOF Example::            
11091: * Mini-OOF Implementation::     
11092: @end menu
11093: 
11094: @c -------------------------------------------------------------
11095: @node Basic Mini-OOF Usage, Mini-OOF Example, Mini-OOF, Mini-OOF
11096: @subsubsection Basic @file{mini-oof.fs} Usage
11097: @cindex mini-oof usage
11098: 
11099: There is a base class (@code{class}, which allocates one cell for the
11100: object pointer) plus seven other words: to define a method, a variable,
11101: a class; to end a class, to resolve binding, to allocate an object and
11102: to compile a class method.
11103: @comment TODO better description of the last one
11104: 
11105: 
11106: doc-object
11107: doc-method
11108: doc-var
11109: doc-class
11110: doc-end-class
11111: doc-defines
11112: doc-new
11113: doc-::
11114: 
11115: 
11116: 
11117: @c -------------------------------------------------------------
11118: @node Mini-OOF Example, Mini-OOF Implementation, Basic Mini-OOF Usage, Mini-OOF
11119: @subsubsection Mini-OOF Example
11120: @cindex mini-oof example
11121: 
11122: A short example shows how to use this package. This example, in slightly
11123: extended form, is supplied as @file{moof-exm.fs}
11124: @comment TODO could flesh this out with some comments from the Forthwrite article
11125: 
11126: @example
11127: object class
11128:   method init
11129:   method draw
11130: end-class graphical
11131: @end example
11132: 
11133: This code defines a class @code{graphical} with an
11134: operation @code{draw}.  We can perform the operation
11135: @code{draw} on any @code{graphical} object, e.g.:
11136: 
11137: @example
11138: 100 100 t-rex draw
11139: @end example
11140: 
11141: where @code{t-rex} is an object or object pointer, created with e.g.
11142: @code{graphical new Constant t-rex}.
11143: 
11144: For concrete graphical objects, we define child classes of the
11145: class @code{graphical}, e.g.:
11146: 
11147: @example
11148: graphical class
11149:   cell var circle-radius
11150: end-class circle \ "graphical" is the parent class
11151: 
11152: :noname ( x y -- )
11153:   circle-radius @@ draw-circle ; circle defines draw
11154: :noname ( r -- )
11155:   circle-radius ! ; circle defines init
11156: @end example
11157: 
11158: There is no implicit init method, so we have to define one. The creation
11159: code of the object now has to call init explicitely.
11160: 
11161: @example
11162: circle new Constant my-circle
11163: 50 my-circle init
11164: @end example
11165: 
11166: It is also possible to add a function to create named objects with
11167: automatic call of @code{init}, given that all objects have @code{init}
11168: on the same place:
11169: 
11170: @example
11171: : new: ( .. o "name" -- )
11172:     new dup Constant init ;
11173: 80 circle new: large-circle
11174: @end example
11175: 
11176: We can draw this new circle at (100,100) with:
11177: 
11178: @example
11179: 100 100 my-circle draw
11180: @end example
11181: 
11182: @node Mini-OOF Implementation,  , Mini-OOF Example, Mini-OOF
11183: @subsubsection @file{mini-oof.fs} Implementation
11184: 
11185: Object-oriented systems with late binding typically use a
11186: ``vtable''-approach: the first variable in each object is a pointer to a
11187: table, which contains the methods as function pointers. The vtable
11188: may also contain other information.
11189: 
11190: So first, let's declare selectors:
11191: 
11192: @example
11193: : method ( m v "name" -- m' v ) Create  over , swap cell+ swap
11194:   DOES> ( ... o -- ... ) @@ over @@ + @@ execute ;
11195: @end example
11196: 
11197: During selector declaration, the number of selectors and instance
11198: variables is on the stack (in address units). @code{method} creates one
11199: selector and increments the selector number. To execute a selector, it
11200: takes the object, fetches the vtable pointer, adds the offset, and
11201: executes the method @i{xt} stored there. Each selector takes the object
11202: it is invoked with as top of stack parameter; it passes the parameters
11203: (including the object) unchanged to the appropriate method which should
11204: consume that object.
11205: 
11206: Now, we also have to declare instance variables
11207: 
11208: @example
11209: : var ( m v size "name" -- m v' ) Create  over , +
11210:   DOES> ( o -- addr ) @@ + ;
11211: @end example
11212: 
11213: As before, a word is created with the current offset. Instance
11214: variables can have different sizes (cells, floats, doubles, chars), so
11215: all we do is take the size and add it to the offset. If your machine
11216: has alignment restrictions, put the proper @code{aligned} or
11217: @code{faligned} before the variable, to adjust the variable
11218: offset. That's why it is on the top of stack.
11219: 
11220: We need a starting point (the base object) and some syntactic sugar:
11221: 
11222: @example
11223: Create object  1 cells , 2 cells ,
11224: : class ( class -- class selectors vars ) dup 2@@ ;
11225: @end example
11226: 
11227: For inheritance, the vtable of the parent object has to be
11228: copied when a new, derived class is declared. This gives all the
11229: methods of the parent class, which can be overridden, though.
11230: 
11231: @example
11232: : end-class  ( class selectors vars "name" -- )
11233:   Create  here >r , dup , 2 cells ?DO ['] noop , 1 cells +LOOP
11234:   cell+ dup cell+ r> rot @@ 2 cells /string move ;
11235: @end example
11236: 
11237: The first line creates the vtable, initialized with
11238: @code{noop}s. The second line is the inheritance mechanism, it
11239: copies the xts from the parent vtable.
11240: 
11241: We still have no way to define new methods, let's do that now:
11242: 
11243: @example
11244: : defines ( xt class "name" -- ) ' >body @@ + ! ;
11245: @end example
11246: 
11247: To allocate a new object, we need a word, too:
11248: 
11249: @example
11250: : new ( class -- o )  here over @@ allot swap over ! ;
11251: @end example
11252: 
11253: Sometimes derived classes want to access the method of the
11254: parent object. There are two ways to achieve this with Mini-OOF:
11255: first, you could use named words, and second, you could look up the
11256: vtable of the parent object.
11257: 
11258: @example
11259: : :: ( class "name" -- ) ' >body @@ + @@ compile, ;
11260: @end example
11261: 
11262: 
11263: Nothing can be more confusing than a good example, so here is
11264: one. First let's declare a text object (called
11265: @code{button}), that stores text and position:
11266: 
11267: @example
11268: object class
11269:   cell var text
11270:   cell var len
11271:   cell var x
11272:   cell var y
11273:   method init
11274:   method draw
11275: end-class button
11276: @end example
11277: 
11278: @noindent
11279: Now, implement the two methods, @code{draw} and @code{init}:
11280: 
11281: @example
11282: :noname ( o -- )
11283:  >r r@@ x @@ r@@ y @@ at-xy  r@@ text @@ r> len @@ type ;
11284:  button defines draw
11285: :noname ( addr u o -- )
11286:  >r 0 r@@ x ! 0 r@@ y ! r@@ len ! r> text ! ;
11287:  button defines init
11288: @end example
11289: 
11290: @noindent
11291: To demonstrate inheritance, we define a class @code{bold-button}, with no
11292: new data and no new selectors:
11293: 
11294: @example
11295: button class
11296: end-class bold-button
11297: 
11298: : bold   27 emit ." [1m" ;
11299: : normal 27 emit ." [0m" ;
11300: @end example
11301: 
11302: @noindent
11303: The class @code{bold-button} has a different draw method to
11304: @code{button}, but the new method is defined in terms of the draw method
11305: for @code{button}:
11306: 
11307: @example
11308: :noname bold [ button :: draw ] normal ; bold-button defines draw
11309: @end example
11310: 
11311: @noindent
11312: Finally, create two objects and apply selectors:
11313: 
11314: @example
11315: button new Constant foo
11316: s" thin foo" foo init
11317: page
11318: foo draw
11319: bold-button new Constant bar
11320: s" fat bar" bar init
11321: 1 bar y !
11322: bar draw
11323: @end example
11324: 
11325: 
11326: @node Comparison with other object models,  , Mini-OOF, Object-oriented Forth
11327: @subsection Comparison with other object models
11328: @cindex comparison of object models
11329: @cindex object models, comparison
11330: 
11331: Many object-oriented Forth extensions have been proposed (@cite{A survey
11332: of object-oriented Forths} (SIGPLAN Notices, April 1996) by Bradford
11333: J. Rodriguez and W. F. S. Poehlman lists 17). This section discusses the
11334: relation of the object models described here to two well-known and two
11335: closely-related (by the use of method maps) models.  Andras Zsoter
11336: helped us with this section.
11337: 
11338: @cindex Neon model
11339: The most popular model currently seems to be the Neon model (see
11340: @cite{Object-oriented programming in ANS Forth} (Forth Dimensions, March
11341: 1997) by Andrew McKewan) but this model has a number of limitations
11342: @footnote{A longer version of this critique can be
11343: found in @cite{On Standardizing Object-Oriented Forth Extensions} (Forth
11344: Dimensions, May 1997) by Anton Ertl.}:
11345: 
11346: @itemize @bullet
11347: @item
11348: It uses a @code{@emph{selector object}} syntax, which makes it unnatural
11349: to pass objects on the stack.
11350: 
11351: @item
11352: It requires that the selector parses the input stream (at
11353: compile time); this leads to reduced extensibility and to bugs that are
11354: hard to find.
11355: 
11356: @item
11357: It allows using every selector on every object; this eliminates the
11358: need for interfaces, but makes it harder to create efficient
11359: implementations.
11360: @end itemize
11361: 
11362: @cindex Pountain's object-oriented model
11363: Another well-known publication is @cite{Object-Oriented Forth} (Academic
11364: Press, London, 1987) by Dick Pountain. However, it is not really about
11365: object-oriented programming, because it hardly deals with late
11366: binding. Instead, it focuses on features like information hiding and
11367: overloading that are characteristic of modular languages like Ada (83).
11368: 
11369: @cindex Zsoter's object-oriented model
11370: In @uref{http://www.forth.org/oopf.html, Does late binding have to be
11371: slow?} (Forth Dimensions 18(1) 1996, pages 31-35) Andras Zsoter
11372: describes a model that makes heavy use of an active object (like
11373: @code{this} in @file{objects.fs}): The active object is not only used
11374: for accessing all fields, but also specifies the receiving object of
11375: every selector invocation; you have to change the active object
11376: explicitly with @code{@{ ... @}}, whereas in @file{objects.fs} it
11377: changes more or less implicitly at @code{m: ... ;m}. Such a change at
11378: the method entry point is unnecessary with Zsoter's model, because the
11379: receiving object is the active object already. On the other hand, the
11380: explicit change is absolutely necessary in that model, because otherwise
11381: no one could ever change the active object. An ANS Forth implementation
11382: of this model is available through
11383: @uref{http://www.forth.org/oopf.html}.
11384: 
11385: @cindex @file{oof.fs}, differences to other models
11386: The @file{oof.fs} model combines information hiding and overloading
11387: resolution (by keeping names in various word lists) with object-oriented
11388: programming. It sets the active object implicitly on method entry, but
11389: also allows explicit changing (with @code{>o...o>} or with
11390: @code{with...endwith}). It uses parsing and state-smart objects and
11391: classes for resolving overloading and for early binding: the object or
11392: class parses the selector and determines the method from this. If the
11393: selector is not parsed by an object or class, it performs a call to the
11394: selector for the active object (late binding), like Zsoter's model.
11395: Fields are always accessed through the active object. The big
11396: disadvantage of this model is the parsing and the state-smartness, which
11397: reduces extensibility and increases the opportunities for subtle bugs;
11398: essentially, you are only safe if you never tick or @code{postpone} an
11399: object or class (Bernd disagrees, but I (Anton) am not convinced).
11400: 
11401: @cindex @file{mini-oof.fs}, differences to other models
11402: The @file{mini-oof.fs} model is quite similar to a very stripped-down
11403: version of the @file{objects.fs} model, but syntactically it is a
11404: mixture of the @file{objects.fs} and @file{oof.fs} models.
11405: 
11406: 
11407: @c -------------------------------------------------------------
11408: @node Programming Tools, C Interface, Object-oriented Forth, Words
11409: @section Programming Tools
11410: @cindex programming tools
11411: 
11412: @c !! move this and assembler down below OO stuff.
11413: 
11414: @menu
11415: * Examining::                   Data and Code.
11416: * Forgetting words::            Usually before reloading.
11417: * Debugging::                   Simple and quick.
11418: * Assertions::                  Making your programs self-checking.
11419: * Singlestep Debugger::         Executing your program word by word.
11420: @end menu
11421: 
11422: @node Examining, Forgetting words, Programming Tools, Programming Tools
11423: @subsection Examining data and code
11424: @cindex examining data and code
11425: @cindex data examination
11426: @cindex code examination
11427: 
11428: The following words inspect the stack non-destructively:
11429: 
11430: doc-.s
11431: doc-f.s
11432: doc-maxdepth-.s
11433: 
11434: There is a word @code{.r} but it does @i{not} display the return stack!
11435: It is used for formatted numeric output (@pxref{Simple numeric output}).
11436: 
11437: doc-depth
11438: doc-fdepth
11439: doc-clearstack
11440: doc-clearstacks
11441: 
11442: The following words inspect memory.
11443: 
11444: doc-?
11445: doc-dump
11446: 
11447: And finally, @code{see} allows to inspect code:
11448: 
11449: doc-see
11450: doc-xt-see
11451: doc-simple-see
11452: doc-simple-see-range
11453: 
11454: @node Forgetting words, Debugging, Examining, Programming Tools
11455: @subsection Forgetting words
11456: @cindex words, forgetting
11457: @cindex forgeting words
11458: 
11459: @c  anton: other, maybe better places for this subsection: Defining Words;
11460: @c  Dictionary allocation.  At least a reference should be there.
11461: 
11462: Forth allows you to forget words (and everything that was alloted in the
11463: dictonary after them) in a LIFO manner.
11464: 
11465: doc-marker
11466: 
11467: The most common use of this feature is during progam development: when
11468: you change a source file, forget all the words it defined and load it
11469: again (since you also forget everything defined after the source file
11470: was loaded, you have to reload that, too).  Note that effects like
11471: storing to variables and destroyed system words are not undone when you
11472: forget words.  With a system like Gforth, that is fast enough at
11473: starting up and compiling, I find it more convenient to exit and restart
11474: Gforth, as this gives me a clean slate.
11475: 
11476: Here's an example of using @code{marker} at the start of a source file
11477: that you are debugging; it ensures that you only ever have one copy of
11478: the file's definitions compiled at any time:
11479: 
11480: @example
11481: [IFDEF] my-code
11482:     my-code
11483: [ENDIF]
11484: 
11485: marker my-code
11486: init-included-files
11487: 
11488: \ .. definitions start here
11489: \ .
11490: \ .
11491: \ end
11492: @end example
11493: 
11494: 
11495: @node Debugging, Assertions, Forgetting words, Programming Tools
11496: @subsection Debugging
11497: @cindex debugging
11498: 
11499: Languages with a slow edit/compile/link/test development loop tend to
11500: require sophisticated tracing/stepping debuggers to facilate debugging.
11501: 
11502: A much better (faster) way in fast-compiling languages is to add
11503: printing code at well-selected places, let the program run, look at
11504: the output, see where things went wrong, add more printing code, etc.,
11505: until the bug is found.
11506: 
11507: The simple debugging aids provided in @file{debugs.fs}
11508: are meant to support this style of debugging.
11509: 
11510: The word @code{~~} prints debugging information (by default the source
11511: location and the stack contents). It is easy to insert. If you use Emacs
11512: it is also easy to remove (@kbd{C-x ~} in the Emacs Forth mode to
11513: query-replace them with nothing). The deferred words
11514: @code{printdebugdata} and @code{.debugline} control the output of
11515: @code{~~}. The default source location output format works well with
11516: Emacs' compilation mode, so you can step through the program at the
11517: source level using @kbd{C-x `} (the advantage over a stepping debugger
11518: is that you can step in any direction and you know where the crash has
11519: happened or where the strange data has occurred).
11520: 
11521: doc-~~
11522: doc-printdebugdata
11523: doc-.debugline
11524: 
11525: @cindex filenames in @code{~~} output
11526: @code{~~} (and assertions) will usually print the wrong file name if a
11527: marker is executed in the same file after their occurance.  They will
11528: print @samp{*somewhere*} as file name if a marker is executed in the
11529: same file before their occurance.
11530: 
11531: 
11532: @node Assertions, Singlestep Debugger, Debugging, Programming Tools
11533: @subsection Assertions
11534: @cindex assertions
11535: 
11536: It is a good idea to make your programs self-checking, especially if you
11537: make an assumption that may become invalid during maintenance (for
11538: example, that a certain field of a data structure is never zero). Gforth
11539: supports @dfn{assertions} for this purpose. They are used like this:
11540: 
11541: @example
11542: assert( @i{flag} )
11543: @end example
11544: 
11545: The code between @code{assert(} and @code{)} should compute a flag, that
11546: should be true if everything is alright and false otherwise. It should
11547: not change anything else on the stack. The overall stack effect of the
11548: assertion is @code{( -- )}. E.g.
11549: 
11550: @example
11551: assert( 1 1 + 2 = ) \ what we learn in school
11552: assert( dup 0<> ) \ assert that the top of stack is not zero
11553: assert( false ) \ this code should not be reached
11554: @end example
11555: 
11556: The need for assertions is different at different times. During
11557: debugging, we want more checking, in production we sometimes care more
11558: for speed. Therefore, assertions can be turned off, i.e., the assertion
11559: becomes a comment. Depending on the importance of an assertion and the
11560: time it takes to check it, you may want to turn off some assertions and
11561: keep others turned on. Gforth provides several levels of assertions for
11562: this purpose:
11563: 
11564: 
11565: doc-assert0(
11566: doc-assert1(
11567: doc-assert2(
11568: doc-assert3(
11569: doc-assert(
11570: doc-)
11571: 
11572: 
11573: The variable @code{assert-level} specifies the highest assertions that
11574: are turned on. I.e., at the default @code{assert-level} of one,
11575: @code{assert0(} and @code{assert1(} assertions perform checking, while
11576: @code{assert2(} and @code{assert3(} assertions are treated as comments.
11577: 
11578: The value of @code{assert-level} is evaluated at compile-time, not at
11579: run-time. Therefore you cannot turn assertions on or off at run-time;
11580: you have to set the @code{assert-level} appropriately before compiling a
11581: piece of code. You can compile different pieces of code at different
11582: @code{assert-level}s (e.g., a trusted library at level 1 and
11583: newly-written code at level 3).
11584: 
11585: 
11586: doc-assert-level
11587: 
11588: 
11589: If an assertion fails, a message compatible with Emacs' compilation mode
11590: is produced and the execution is aborted (currently with @code{ABORT"}.
11591: If there is interest, we will introduce a special throw code. But if you
11592: intend to @code{catch} a specific condition, using @code{throw} is
11593: probably more appropriate than an assertion).
11594: 
11595: @cindex filenames in assertion output
11596: Assertions (and @code{~~}) will usually print the wrong file name if a
11597: marker is executed in the same file after their occurance.  They will
11598: print @samp{*somewhere*} as file name if a marker is executed in the
11599: same file before their occurance.
11600: 
11601: Definitions in ANS Forth for these assertion words are provided
11602: in @file{compat/assert.fs}.
11603: 
11604: 
11605: @node Singlestep Debugger,  , Assertions, Programming Tools
11606: @subsection Singlestep Debugger
11607: @cindex singlestep Debugger
11608: @cindex debugging Singlestep
11609: 
11610: The singlestep debugger does not work in this release.
11611: 
11612: When you create a new word there's often the need to check whether it
11613: behaves correctly or not. You can do this by typing @code{dbg
11614: badword}. A debug session might look like this:
11615: 
11616: @example
11617: : badword 0 DO i . LOOP ;  ok
11618: 2 dbg badword 
11619: : badword  
11620: Scanning code...
11621: 
11622: Nesting debugger ready!
11623: 
11624: 400D4738  8049BC4 0              -> [ 2 ] 00002 00000 
11625: 400D4740  8049F68 DO             -> [ 0 ] 
11626: 400D4744  804A0C8 i              -> [ 1 ] 00000 
11627: 400D4748 400C5E60 .              -> 0 [ 0 ] 
11628: 400D474C  8049D0C LOOP           -> [ 0 ] 
11629: 400D4744  804A0C8 i              -> [ 1 ] 00001 
11630: 400D4748 400C5E60 .              -> 1 [ 0 ] 
11631: 400D474C  8049D0C LOOP           -> [ 0 ] 
11632: 400D4758  804B384 ;              ->  ok
11633: @end example
11634: 
11635: Each line displayed is one step. You always have to hit return to
11636: execute the next word that is displayed. If you don't want to execute
11637: the next word in a whole, you have to type @kbd{n} for @code{nest}. Here is
11638: an overview what keys are available:
11639: 
11640: @table @i
11641: 
11642: @item @key{RET}
11643: Next; Execute the next word.
11644: 
11645: @item n
11646: Nest; Single step through next word.
11647: 
11648: @item u
11649: Unnest; Stop debugging and execute rest of word. If we got to this word
11650: with nest, continue debugging with the calling word.
11651: 
11652: @item d
11653: Done; Stop debugging and execute rest.
11654: 
11655: @item s
11656: Stop; Abort immediately.
11657: 
11658: @end table
11659: 
11660: Debugging large application with this mechanism is very difficult, because
11661: you have to nest very deeply into the program before the interesting part
11662: begins. This takes a lot of time. 
11663: 
11664: To do it more directly put a @code{BREAK:} command into your source code.
11665: When program execution reaches @code{BREAK:} the single step debugger is
11666: invoked and you have all the features described above.
11667: 
11668: If you have more than one part to debug it is useful to know where the
11669: program has stopped at the moment. You can do this by the 
11670: @code{BREAK" string"} command. This behaves like @code{BREAK:} except that
11671: string is typed out when the ``breakpoint'' is reached.
11672: 
11673: 
11674: doc-dbg
11675: doc-break:
11676: doc-break"
11677: 
11678: @c ------------------------------------------------------------
11679: @node C Interface, Assembler and Code Words, Programming Tools, Words
11680: @section C Interface
11681: @cindex C interface
11682: @cindex foreign language interface
11683: @cindex interface to C functions
11684: 
11685: Note that the C interface is not yet complete; a better way of
11686: declaring C functions is planned, as well as a way of declaring
11687: structs, unions, and their fields.
11688: 
11689: @menu
11690: * Calling C Functions::         
11691: * Declaring C Functions::       
11692: * Callbacks::                   
11693: * Low-Level C Interface Words::  
11694: @end menu
11695: 
11696: @node Calling C Functions, Declaring C Functions, C Interface, C Interface
11697: @subsection Calling C functions
11698: @cindex C functions, calls to
11699: @cindex calling C functions
11700: 
11701: Once a C function is declared (see @pxref{Declaring C Functions}), you
11702: can call it as follows: You push the arguments on the stack(s), and
11703: then call the word for the C function.  The arguments have to be
11704: pushed in the same order as the arguments appear in the C
11705: documentation (i.e., the first argument is deepest on the stack).
11706: Integer and pointer arguments have to be pushed on the data stack,
11707: floating-point arguments on the FP stack; these arguments are consumed
11708: by the called C function.
11709: 
11710: On returning from the C function, the return value, if any, resides on
11711: the appropriate stack: an integer return value is pushed on the data
11712: stack, an FP return value on the FP stack, and a void return value
11713: results in not pushing anything.  Note that most C functions have a
11714: return value, even if that is often not used in C; in Forth, you have
11715: to @code{drop} this return value explicitly if you do not use it.
11716: 
11717: By default, an integer argument or return value corresponds to a
11718: single cell, and a floating-point argument or return value corresponds
11719: to a Forth float value; the C interface performs the appropriate
11720: conversions where necessary, on a best-effort basis (in some cases,
11721: there may be some loss).
11722: 
11723: As an example, consider the POSIX function @code{lseek()}:
11724: 
11725: @example
11726: off_t lseek(int fd, off_t offset, int whence);
11727: @end example
11728: 
11729: This function takes three integer arguments, and returns an integer
11730: argument, so a Forth call for setting the current file offset to the
11731: start of the file could look like this:
11732: 
11733: @example
11734: fd @@ 0 SEEK_SET lseek -1 = if
11735:   ... \ error handling
11736: then
11737: @end example
11738: 
11739: You might be worried that an @code{off_t} does not fit into a cell, so
11740: you could not pass larger offsets to lseek, and might get only a part
11741: of the return values.  In that case, in your declaration of the
11742: function (@pxref{Declaring C Functions}) you should declare it to use
11743: double-cells for the off_t argument and return value, and maybe give
11744: the resulting Forth word a different name, like @code{dlseek}; the
11745: result could be called like this:
11746: 
11747: @example
11748: fd @@ 0. SEEK_SET dlseek -1. d= if
11749:   ... \ error handling
11750: then
11751: @end example
11752: 
11753: Passing and returning structs or unions is currently not supported by
11754: our interface@footnote{If you know the calling convention of your C
11755: compiler, you usually can call such functions in some way, but that
11756: way is usually not portable between platforms, and sometimes not even
11757: between C compilers.}.
11758: 
11759: Calling functions with a variable number of arguments (e.g.,
11760: @code{printf()}) is currently only supported by having you declare one
11761: function-calling word for each argument pattern, and calling the
11762: appropriate word for the desired pattern.
11763: 
11764: 
11765: @node Declaring C Functions, Callbacks, Calling C Functions, C Interface
11766: @subsection Declaring C Functions
11767: @cindex C functions, declarations
11768: @cindex declaring C functions
11769: 
11770: Before you can call @code{lseek} or @code{dlseek}, you have to declare
11771: it.  You have to look up in your system what the concrete type for the
11772: abstract type @code{off_t} is; let's assume it is @code{long}.  Then
11773: the declarations for these words are:
11774: 
11775: @example
11776: library libc libc.so.6
11777: libc lseek  int  long int  (long) lseek ( fd noffset whence -- noffset2 )
11778: libc dlseek int dlong int (dlong) lseek ( fd doffset whence -- doffset2 ) 
11779: @end example
11780: 
11781: The first line defines a Forth word @code{libc} for accessing the C
11782: functions in the shared library @file{libc.so.6} (the name of the
11783: shared library depends on the library and the OS; this example is the
11784: standard C library (containing most of the standard C and Unix
11785: functions) for GNU/Linux systems since about 1998).
11786: 
11787: The next two lines define two Forth words for the same C function
11788: @code{lseek()}; the middle line defines @code{lseek ( n1 n2 n3 -- n
11789: )}, and the last line defines @code{dlseek ( n1 d2 n3 -- d )}.
11790: 
11791: As you can see, the declarations are relatively platform-dependent
11792: (e.g., on one platform @code{off_t} may be a @code{long}, whereas on
11793: another platform it may be a @code{long long}; actually, in this case
11794: you can have this difference even on the same platform), while the
11795: resulting function-calling words are platform-independent, and calls
11796: to them are portable.
11797: 
11798: At some point in the future this interface will be superseded by a
11799: more convenient one with fewer portability issues.  But the resulting
11800: words for calling the C function will still have the same interface,
11801: so you will not need to change the calls.
11802: 
11803: Anyway, here are the words for the current interface:
11804: 
11805: doc-library
11806: doc-int
11807: doc-dint
11808: doc-uint
11809: doc-udint
11810: doc-long
11811: doc-dlong
11812: doc-ulong
11813: doc-udlong
11814: doc-longlong
11815: doc-dlonglong
11816: doc-ulonglong
11817: doc-udlonglong
11818: doc-ptr
11819: doc-cfloat
11820: doc-cdouble
11821: doc-clongdouble
11822: doc-(int)
11823: doc-(dint)
11824: doc-(uint)
11825: doc-(udint)
11826: doc-(long)
11827: doc-(dlong)
11828: doc-(ulong)
11829: doc-(udlong)
11830: doc-(longlong)
11831: doc-(dlonglong)
11832: doc-(ulonglong)
11833: doc-(udlonglong)
11834: doc-(ptr)
11835: doc-(cfloat)
11836: doc-(cdouble)
11837: doc-(clongdouble)
11838: 
11839: 
11840: @node Callbacks, Low-Level C Interface Words, Declaring C Functions, C Interface
11841: @subsection Callbacks
11842: @cindex Callback functions written in Forth
11843: @cindex C function pointers to Forth words
11844: 
11845: In some cases you have to pass a function pointer to a C function,
11846: i.e., the library wants to call back to your application (and the
11847: pointed-to function is called a callback function).  You can pass the
11848: address of an existing C function (that you get with @code{lib-sym},
11849: @pxref{Low-Level C Interface Words}), but if there is no appropriate C
11850: function, you probably want to define the function as a Forth word.
11851: 
11852: !!!
11853: @c I don't understand the existing callback interface from the example - anton
11854: 
11855: doc-callback
11856: doc-callback;
11857: doc-fptr
11858: 
11859: @node Low-Level C Interface Words,  , Callbacks, C Interface
11860: @subsection Low-Level C Interface Words
11861: 
11862: doc-open-lib
11863: doc-lib-sym
11864: 
11865: @c -------------------------------------------------------------
11866: @node Assembler and Code Words, Threading Words, C Interface, Words
11867: @section Assembler and Code Words
11868: @cindex assembler
11869: @cindex code words
11870: 
11871: @menu
11872: * Code and ;code::              
11873: * Common Assembler::            Assembler Syntax
11874: * Common Disassembler::         
11875: * 386 Assembler::               Deviations and special cases
11876: * Alpha Assembler::             Deviations and special cases
11877: * MIPS assembler::              Deviations and special cases
11878: * Other assemblers::            How to write them
11879: @end menu
11880: 
11881: @node Code and ;code, Common Assembler, Assembler and Code Words, Assembler and Code Words
11882: @subsection @code{Code} and @code{;code}
11883: 
11884: Gforth provides some words for defining primitives (words written in
11885: machine code), and for defining the machine-code equivalent of
11886: @code{DOES>}-based defining words. However, the machine-independent
11887: nature of Gforth poses a few problems: First of all, Gforth runs on
11888: several architectures, so it can provide no standard assembler. What's
11889: worse is that the register allocation not only depends on the processor,
11890: but also on the @code{gcc} version and options used.
11891: 
11892: The words that Gforth offers encapsulate some system dependences (e.g.,
11893: the header structure), so a system-independent assembler may be used in
11894: Gforth. If you do not have an assembler, you can compile machine code
11895: directly with @code{,} and @code{c,}@footnote{This isn't portable,
11896: because these words emit stuff in @i{data} space; it works because
11897: Gforth has unified code/data spaces. Assembler isn't likely to be
11898: portable anyway.}.
11899: 
11900: 
11901: doc-assembler
11902: doc-init-asm
11903: doc-code
11904: doc-end-code
11905: doc-;code
11906: doc-flush-icache
11907: 
11908: 
11909: If @code{flush-icache} does not work correctly, @code{code} words
11910: etc. will not work (reliably), either.
11911: 
11912: The typical usage of these @code{code} words can be shown most easily by
11913: analogy to the equivalent high-level defining words:
11914: 
11915: @example
11916: : foo                              code foo
11917:    <high-level Forth words>              <assembler>
11918: ;                                  end-code
11919:                                 
11920: : bar                              : bar
11921:    <high-level Forth words>           <high-level Forth words>
11922:    CREATE                             CREATE
11923:       <high-level Forth words>           <high-level Forth words>
11924:    DOES>                              ;code
11925:       <high-level Forth words>           <assembler>
11926: ;                                  end-code
11927: @end example
11928: 
11929: @c anton: the following stuff is also in "Common Assembler", in less detail.
11930: 
11931: @cindex registers of the inner interpreter
11932: In the assembly code you will want to refer to the inner interpreter's
11933: registers (e.g., the data stack pointer) and you may want to use other
11934: registers for temporary storage. Unfortunately, the register allocation
11935: is installation-dependent.
11936: 
11937: In particular, @code{ip} (Forth instruction pointer) and @code{rp}
11938: (return stack pointer) may be in different places in @code{gforth} and
11939: @code{gforth-fast}, or different installations.  This means that you
11940: cannot write a @code{NEXT} routine that works reliably on both versions
11941: or different installations; so for doing @code{NEXT}, I recommend
11942: jumping to @code{' noop >code-address}, which contains nothing but a
11943: @code{NEXT}.
11944: 
11945: For general accesses to the inner interpreter's registers, the easiest
11946: solution is to use explicit register declarations (@pxref{Explicit Reg
11947: Vars, , Variables in Specified Registers, gcc.info, GNU C Manual}) for
11948: all of the inner interpreter's registers: You have to compile Gforth
11949: with @code{-DFORCE_REG} (configure option @code{--enable-force-reg}) and
11950: the appropriate declarations must be present in the @code{machine.h}
11951: file (see @code{mips.h} for an example; you can find a full list of all
11952: declarable register symbols with @code{grep register engine.c}). If you
11953: give explicit registers to all variables that are declared at the
11954: beginning of @code{engine()}, you should be able to use the other
11955: caller-saved registers for temporary storage. Alternatively, you can use
11956: the @code{gcc} option @code{-ffixed-REG} (@pxref{Code Gen Options, ,
11957: Options for Code Generation Conventions, gcc.info, GNU C Manual}) to
11958: reserve a register (however, this restriction on register allocation may
11959: slow Gforth significantly).
11960: 
11961: If this solution is not viable (e.g., because @code{gcc} does not allow
11962: you to explicitly declare all the registers you need), you have to find
11963: out by looking at the code where the inner interpreter's registers
11964: reside and which registers can be used for temporary storage. You can
11965: get an assembly listing of the engine's code with @code{make engine.s}.
11966: 
11967: In any case, it is good practice to abstract your assembly code from the
11968: actual register allocation. E.g., if the data stack pointer resides in
11969: register @code{$17}, create an alias for this register called @code{sp},
11970: and use that in your assembly code.
11971: 
11972: @cindex code words, portable
11973: Another option for implementing normal and defining words efficiently
11974: is to add the desired functionality to the source of Gforth. For normal
11975: words you just have to edit @file{primitives} (@pxref{Automatic
11976: Generation}). Defining words (equivalent to @code{;CODE} words, for fast
11977: defined words) may require changes in @file{engine.c}, @file{kernel.fs},
11978: @file{prims2x.fs}, and possibly @file{cross.fs}.
11979: 
11980: @node Common Assembler, Common Disassembler, Code and ;code, Assembler and Code Words
11981: @subsection Common Assembler
11982: 
11983: The assemblers in Gforth generally use a postfix syntax, i.e., the
11984: instruction name follows the operands.
11985: 
11986: The operands are passed in the usual order (the same that is used in the
11987: manual of the architecture).  Since they all are Forth words, they have
11988: to be separated by spaces; you can also use Forth words to compute the
11989: operands.
11990: 
11991: The instruction names usually end with a @code{,}.  This makes it easier
11992: to visually separate instructions if you put several of them on one
11993: line; it also avoids shadowing other Forth words (e.g., @code{and}).
11994: 
11995: Registers are usually specified by number; e.g., (decimal) @code{11}
11996: specifies registers R11 and F11 on the Alpha architecture (which one,
11997: depends on the instruction).  The usual names are also available, e.g.,
11998: @code{s2} for R11 on Alpha.
11999: 
12000: Control flow is specified similar to normal Forth code (@pxref{Arbitrary
12001: control structures}), with @code{if,}, @code{ahead,}, @code{then,},
12002: @code{begin,}, @code{until,}, @code{again,}, @code{cs-roll},
12003: @code{cs-pick}, @code{else,}, @code{while,}, and @code{repeat,}.  The
12004: conditions are specified in a way specific to each assembler.
12005: 
12006: Note that the register assignments of the Gforth engine can change
12007: between Gforth versions, or even between different compilations of the
12008: same Gforth version (e.g., if you use a different GCC version).  So if
12009: you want to refer to Gforth's registers (e.g., the stack pointer or
12010: TOS), I recommend defining your own words for refering to these
12011: registers, and using them later on; then you can easily adapt to a
12012: changed register assignment.  The stability of the register assignment
12013: is usually better if you build Gforth with @code{--enable-force-reg}.
12014: 
12015: The most common use of these registers is to dispatch to the next word
12016: (the @code{next} routine).  A portable way to do this is to jump to
12017: @code{' noop >code-address} (of course, this is less efficient than
12018: integrating the @code{next} code and scheduling it well).
12019: 
12020: Another difference between Gforth version is that the top of stack is
12021: kept in memory in @code{gforth} and, on most platforms, in a register in
12022: @code{gforth-fast}.
12023: 
12024: @node  Common Disassembler, 386 Assembler, Common Assembler, Assembler and Code Words
12025: @subsection Common Disassembler
12026: @cindex disassembler, general
12027: @cindex gdb disassembler
12028: 
12029: You can disassemble a @code{code} word with @code{see}
12030: (@pxref{Debugging}).  You can disassemble a section of memory with
12031: 
12032: doc-discode
12033: 
12034: There are two kinds of disassembler for Gforth: The Forth disassembler
12035: (available on some CPUs) and the gdb disassembler (available on
12036: platforms with @command{gdb} and @command{mktemp}).  If both are
12037: available, the Forth disassembler is used by default.  If you prefer
12038: the gdb disassembler, say
12039: 
12040: @example
12041: ' disasm-gdb is discode
12042: @end example
12043: 
12044: If neither is available, @code{discode} performs @code{dump}.
12045: 
12046: The Forth disassembler generally produces output that can be fed into the
12047: assembler (i.e., same syntax, etc.).  It also includes additional
12048: information in comments.  In particular, the address of the instruction
12049: is given in a comment before the instruction.
12050: 
12051: The gdb disassembler produces output in the same format as the gdb
12052: @code{disassemble} command (@pxref{Machine Code,,Source and machine
12053: code,gdb,Debugging with GDB}), in the default flavour (AT&T syntax for
12054: the 386 and AMD64 architectures).
12055: 
12056: @code{See} may display more or less than the actual code of the word,
12057: because the recognition of the end of the code is unreliable.  You can
12058: use @code{discode} if it did not display enough.  It may display more, if
12059: the code word is not immediately followed by a named word.  If you have
12060: something else there, you can follow the word with @code{align latest ,}
12061: to ensure that the end is recognized.
12062: 
12063: @node 386 Assembler, Alpha Assembler, Common Disassembler, Assembler and Code Words
12064: @subsection 386 Assembler
12065: 
12066: The 386 assembler included in Gforth was written by Bernd Paysan, it's
12067: available under GPL, and originally part of bigFORTH.
12068: 
12069: The 386 disassembler included in Gforth was written by Andrew McKewan
12070: and is in the public domain.
12071: 
12072: The disassembler displays code in an Intel-like prefix syntax.
12073: 
12074: The assembler uses a postfix syntax with reversed parameters.
12075: 
12076: The assembler includes all instruction of the Athlon, i.e. 486 core
12077: instructions, Pentium and PPro extensions, floating point, MMX, 3Dnow!,
12078: but not ISSE. It's an integrated 16- and 32-bit assembler. Default is 32
12079: bit, you can switch to 16 bit with .86 and back to 32 bit with .386.
12080: 
12081: There are several prefixes to switch between different operation sizes,
12082: @code{.b} for byte accesses, @code{.w} for word accesses, @code{.d} for
12083: double-word accesses. Addressing modes can be switched with @code{.wa}
12084: for 16 bit addresses, and @code{.da} for 32 bit addresses. You don't
12085: need a prefix for byte register names (@code{AL} et al).
12086: 
12087: For floating point operations, the prefixes are @code{.fs} (IEEE
12088: single), @code{.fl} (IEEE double), @code{.fx} (extended), @code{.fw}
12089: (word), @code{.fd} (double-word), and @code{.fq} (quad-word).
12090: 
12091: The MMX opcodes don't have size prefixes, they are spelled out like in
12092: the Intel assembler. Instead of move from and to memory, there are
12093: PLDQ/PLDD and PSTQ/PSTD.
12094: 
12095: The registers lack the 'e' prefix; even in 32 bit mode, eax is called
12096: ax.  Immediate values are indicated by postfixing them with @code{#},
12097: e.g., @code{3 #}.  Here are some examples of addressing modes in various
12098: syntaxes:
12099: 
12100: @example
12101: Gforth          Intel (NASM)   AT&T (gas)      Name
12102: .w ax           ax             %ax             register (16 bit)
12103: ax              eax            %eax            register (32 bit)
12104: 3 #             offset 3       $3              immediate
12105: 1000 #)         byte ptr 1000  1000            displacement
12106: bx )            [ebx]          (%ebx)          base
12107: 100 di d)       100[edi]       100(%edi)       base+displacement
12108: 20 ax *4 i#)    20[eax*4]      20(,%eax,4)     (index*scale)+displacement
12109: di ax *4 i)     [edi][eax*4]   (%edi,%eax,4)   base+(index*scale)
12110: 4 bx cx di)     4[ebx][ecx]    4(%ebx,%ecx)    base+index+displacement
12111: 12 sp ax *2 di) 12[esp][eax*2] 12(%esp,%eax,2) base+(index*scale)+displacement
12112: @end example
12113: 
12114: You can use @code{L)} and @code{LI)} instead of @code{D)} and
12115: @code{DI)} to enforce 32-bit displacement fields (useful for
12116: later patching).
12117: 
12118: Some example of instructions are:
12119: 
12120: @example
12121: ax bx mov             \ move ebx,eax
12122: 3 # ax mov            \ mov eax,3
12123: 100 di d) ax mov      \ mov eax,100[edi]
12124: 4 bx cx di) ax mov    \ mov eax,4[ebx][ecx]
12125: .w ax bx mov          \ mov bx,ax
12126: @end example
12127: 
12128: The following forms are supported for binary instructions:
12129: 
12130: @example
12131: <reg> <reg> <inst>
12132: <n> # <reg> <inst>
12133: <mem> <reg> <inst>
12134: <reg> <mem> <inst>
12135: <n> # <mem> <inst>
12136: @end example
12137: 
12138: The shift/rotate syntax is:
12139: 
12140: @example
12141: <reg/mem> 1 # shl \ shortens to shift without immediate
12142: <reg/mem> 4 # shl
12143: <reg/mem> cl shl
12144: @end example
12145: 
12146: Precede string instructions (@code{movs} etc.) with @code{.b} to get
12147: the byte version.
12148: 
12149: The control structure words @code{IF} @code{UNTIL} etc. must be preceded
12150: by one of these conditions: @code{vs vc u< u>= 0= 0<> u<= u> 0< 0>= ps
12151: pc < >= <= >}. (Note that most of these words shadow some Forth words
12152: when @code{assembler} is in front of @code{forth} in the search path,
12153: e.g., in @code{code} words).  Currently the control structure words use
12154: one stack item, so you have to use @code{roll} instead of @code{cs-roll}
12155: to shuffle them (you can also use @code{swap} etc.).
12156: 
12157: Here is an example of a @code{code} word (assumes that the stack pointer
12158: is in esi and the TOS is in ebx):
12159: 
12160: @example
12161: code my+ ( n1 n2 -- n )
12162:     4 si D) bx add
12163:     4 # si add
12164:     Next
12165: end-code
12166: @end example
12167: 
12168: @node Alpha Assembler, MIPS assembler, 386 Assembler, Assembler and Code Words
12169: @subsection Alpha Assembler
12170: 
12171: The Alpha assembler and disassembler were originally written by Bernd
12172: Thallner.
12173: 
12174: The register names @code{a0}--@code{a5} are not available to avoid
12175: shadowing hex numbers.
12176: 
12177: Immediate forms of arithmetic instructions are distinguished by a
12178: @code{#} just before the @code{,}, e.g., @code{and#,} (note: @code{lda,}
12179: does not count as arithmetic instruction).
12180: 
12181: You have to specify all operands to an instruction, even those that
12182: other assemblers consider optional, e.g., the destination register for
12183: @code{br,}, or the destination register and hint for @code{jmp,}.
12184: 
12185: You can specify conditions for @code{if,} by removing the first @code{b}
12186: and the trailing @code{,} from a branch with a corresponding name; e.g.,
12187: 
12188: @example
12189: 11 fgt if, \ if F11>0e
12190:   ...
12191: endif,
12192: @end example
12193: 
12194: @code{fbgt,} gives @code{fgt}.  
12195: 
12196: @node MIPS assembler, Other assemblers, Alpha Assembler, Assembler and Code Words
12197: @subsection MIPS assembler
12198: 
12199: The MIPS assembler was originally written by Christian Pirker.
12200: 
12201: Currently the assembler and disassembler only cover the MIPS-I
12202: architecture (R3000), and don't support FP instructions.
12203: 
12204: The register names @code{$a0}--@code{$a3} are not available to avoid
12205: shadowing hex numbers.
12206: 
12207: Because there is no way to distinguish registers from immediate values,
12208: you have to explicitly use the immediate forms of instructions, i.e.,
12209: @code{addiu,}, not just @code{addu,} (@command{as} does this
12210: implicitly).
12211: 
12212: If the architecture manual specifies several formats for the instruction
12213: (e.g., for @code{jalr,}), you usually have to use the one with more
12214: arguments (i.e., two for @code{jalr,}).  When in doubt, see
12215: @code{arch/mips/testasm.fs} for an example of correct use.
12216: 
12217: Branches and jumps in the MIPS architecture have a delay slot.  You have
12218: to fill it yourself (the simplest way is to use @code{nop,}), the
12219: assembler does not do it for you (unlike @command{as}).  Even
12220: @code{if,}, @code{ahead,}, @code{until,}, @code{again,}, @code{while,},
12221: @code{else,} and @code{repeat,} need a delay slot.  Since @code{begin,}
12222: and @code{then,} just specify branch targets, they are not affected.
12223: 
12224: Note that you must not put branches, jumps, or @code{li,} into the delay
12225: slot: @code{li,} may expand to several instructions, and control flow
12226: instructions may not be put into the branch delay slot in any case.
12227: 
12228: For branches the argument specifying the target is a relative address;
12229: You have to add the address of the delay slot to get the absolute
12230: address.
12231: 
12232: The MIPS architecture also has load delay slots and restrictions on
12233: using @code{mfhi,} and @code{mflo,}; you have to order the instructions
12234: yourself to satisfy these restrictions, the assembler does not do it for
12235: you.
12236: 
12237: You can specify the conditions for @code{if,} etc. by taking a
12238: conditional branch and leaving away the @code{b} at the start and the
12239: @code{,} at the end.  E.g.,
12240: 
12241: @example
12242: 4 5 eq if,
12243:   ... \ do something if $4 equals $5
12244: then,
12245: @end example
12246: 
12247: @node Other assemblers,  , MIPS assembler, Assembler and Code Words
12248: @subsection Other assemblers
12249: 
12250: If you want to contribute another assembler/disassembler, please contact
12251: us (@email{anton@@mips.complang.tuwien.ac.at}) to check if we have such
12252: an assembler already.  If you are writing them from scratch, please use
12253: a similar syntax style as the one we use (i.e., postfix, commas at the
12254: end of the instruction names, @pxref{Common Assembler}); make the output
12255: of the disassembler be valid input for the assembler, and keep the style
12256: similar to the style we used.
12257: 
12258: Hints on implementation: The most important part is to have a good test
12259: suite that contains all instructions.  Once you have that, the rest is
12260: easy.  For actual coding you can take a look at
12261: @file{arch/mips/disasm.fs} to get some ideas on how to use data for both
12262: the assembler and disassembler, avoiding redundancy and some potential
12263: bugs.  You can also look at that file (and @pxref{Advanced does> usage
12264: example}) to get ideas how to factor a disassembler.
12265: 
12266: Start with the disassembler, because it's easier to reuse data from the
12267: disassembler for the assembler than the other way round.
12268: 
12269: For the assembler, take a look at @file{arch/alpha/asm.fs}, which shows
12270: how simple it can be.
12271: 
12272: @c -------------------------------------------------------------
12273: @node Threading Words, Passing Commands to the OS, Assembler and Code Words, Words
12274: @section Threading Words
12275: @cindex threading words
12276: 
12277: @cindex code address
12278: These words provide access to code addresses and other threading stuff
12279: in Gforth (and, possibly, other interpretive Forths). It more or less
12280: abstracts away the differences between direct and indirect threading
12281: (and, for direct threading, the machine dependences). However, at
12282: present this wordset is still incomplete. It is also pretty low-level;
12283: some day it will hopefully be made unnecessary by an internals wordset
12284: that abstracts implementation details away completely.
12285: 
12286: The terminology used here stems from indirect threaded Forth systems; in
12287: such a system, the XT of a word is represented by the CFA (code field
12288: address) of a word; the CFA points to a cell that contains the code
12289: address.  The code address is the address of some machine code that
12290: performs the run-time action of invoking the word (e.g., the
12291: @code{dovar:} routine pushes the address of the body of the word (a
12292: variable) on the stack
12293: ).
12294: 
12295: @cindex code address
12296: @cindex code field address
12297: In an indirect threaded Forth, you can get the code address of @i{name}
12298: with @code{' @i{name} @@}; in Gforth you can get it with @code{' @i{name}
12299: >code-address}, independent of the threading method.
12300: 
12301: doc-threading-method
12302: doc->code-address
12303: doc-code-address!
12304: 
12305: @cindex @code{does>}-handler
12306: @cindex @code{does>}-code
12307: For a word defined with @code{DOES>}, the code address usually points to
12308: a jump instruction (the @dfn{does-handler}) that jumps to the dodoes
12309: routine (in Gforth on some platforms, it can also point to the dodoes
12310: routine itself).  What you are typically interested in, though, is
12311: whether a word is a @code{DOES>}-defined word, and what Forth code it
12312: executes; @code{>does-code} tells you that.
12313: 
12314: doc->does-code
12315: 
12316: To create a @code{DOES>}-defined word with the following basic words,
12317: you have to set up a @code{DOES>}-handler with @code{does-handler!};
12318: @code{/does-handler} aus behind you have to place your executable Forth
12319: code.  Finally you have to create a word and modify its behaviour with
12320: @code{does-handler!}.
12321: 
12322: doc-does-code!
12323: doc-does-handler!
12324: doc-/does-handler
12325: 
12326: The code addresses produced by various defining words are produced by
12327: the following words:
12328: 
12329: doc-docol:
12330: doc-docon:
12331: doc-dovar:
12332: doc-douser:
12333: doc-dodefer:
12334: doc-dofield:
12335: 
12336: @cindex definer
12337: The following two words generalize @code{>code-address},
12338: @code{>does-code}, @code{code-address!}, and @code{does-code!}:
12339: 
12340: doc->definer
12341: doc-definer!
12342: 
12343: @c -------------------------------------------------------------
12344: @node Passing Commands to the OS, Keeping track of Time, Threading Words, Words
12345: @section Passing Commands to the Operating System
12346: @cindex operating system - passing commands
12347: @cindex shell commands
12348: 
12349: Gforth allows you to pass an arbitrary string to the host operating
12350: system shell (if such a thing exists) for execution.
12351: 
12352: doc-sh
12353: doc-system
12354: doc-$?
12355: doc-getenv
12356: 
12357: @c -------------------------------------------------------------
12358: @node Keeping track of Time, Miscellaneous Words, Passing Commands to the OS, Words
12359: @section Keeping track of Time
12360: @cindex time-related words
12361: 
12362: doc-ms
12363: doc-time&date
12364: doc-utime
12365: doc-cputime
12366: 
12367: 
12368: @c -------------------------------------------------------------
12369: @node Miscellaneous Words,  , Keeping track of Time, Words
12370: @section Miscellaneous Words
12371: @cindex miscellaneous words
12372: 
12373: @comment TODO find homes for these
12374: 
12375: These section lists the ANS Forth words that are not documented
12376: elsewhere in this manual. Ultimately, they all need proper homes.
12377: 
12378: doc-quit
12379: 
12380: The following ANS Forth words are not currently supported by Gforth 
12381: (@pxref{ANS conformance}):
12382: 
12383: @code{EDITOR} 
12384: @code{EMIT?} 
12385: @code{FORGET} 
12386: 
12387: @c ******************************************************************
12388: @node Error messages, Tools, Words, Top
12389: @chapter Error messages
12390: @cindex error messages
12391: @cindex backtrace
12392: 
12393: A typical Gforth error message looks like this:
12394: 
12395: @example
12396: in file included from \evaluated string/:-1
12397: in file included from ./yyy.fs:1
12398: ./xxx.fs:4: Invalid memory address
12399: >>>bar<<<
12400: Backtrace:
12401: $400E664C @@
12402: $400E6664 foo
12403: @end example
12404: 
12405: The message identifying the error is @code{Invalid memory address}.  The
12406: error happened when text-interpreting line 4 of the file
12407: @file{./xxx.fs}. This line is given (it contains @code{bar}), and the
12408: word on the line where the error happened, is pointed out (with
12409: @code{>>>} and @code{<<<}).
12410: 
12411: The file containing the error was included in line 1 of @file{./yyy.fs},
12412: and @file{yyy.fs} was included from a non-file (in this case, by giving
12413: @file{yyy.fs} as command-line parameter to Gforth).
12414: 
12415: At the end of the error message you find a return stack dump that can be
12416: interpreted as a backtrace (possibly empty). On top you find the top of
12417: the return stack when the @code{throw} happened, and at the bottom you
12418: find the return stack entry just above the return stack of the topmost
12419: text interpreter.
12420: 
12421: To the right of most return stack entries you see a guess for the word
12422: that pushed that return stack entry as its return address. This gives a
12423: backtrace. In our case we see that @code{bar} called @code{foo}, and
12424: @code{foo} called @code{@@} (and @code{@@} had an @emph{Invalid memory
12425: address} exception).
12426: 
12427: Note that the backtrace is not perfect: We don't know which return stack
12428: entries are return addresses (so we may get false positives); and in
12429: some cases (e.g., for @code{abort"}) we cannot determine from the return
12430: address the word that pushed the return address, so for some return
12431: addresses you see no names in the return stack dump.
12432: 
12433: @cindex @code{catch} and backtraces
12434: The return stack dump represents the return stack at the time when a
12435: specific @code{throw} was executed.  In programs that make use of
12436: @code{catch}, it is not necessarily clear which @code{throw} should be
12437: used for the return stack dump (e.g., consider one @code{throw} that
12438: indicates an error, which is caught, and during recovery another error
12439: happens; which @code{throw} should be used for the stack dump?).  Gforth
12440: presents the return stack dump for the first @code{throw} after the last
12441: executed (not returned-to) @code{catch}; this works well in the usual
12442: case.
12443: 
12444: @cindex @code{gforth-fast} and backtraces
12445: @cindex @code{gforth-fast}, difference from @code{gforth}
12446: @cindex backtraces with @code{gforth-fast}
12447: @cindex return stack dump with @code{gforth-fast}
12448: @code{Gforth} is able to do a return stack dump for throws generated
12449: from primitives (e.g., invalid memory address, stack empty etc.);
12450: @code{gforth-fast} is only able to do a return stack dump from a
12451: directly called @code{throw} (including @code{abort} etc.).  Given an
12452: exception caused by a primitive in @code{gforth-fast}, you will
12453: typically see no return stack dump at all; however, if the exception is
12454: caught by @code{catch} (e.g., for restoring some state), and then
12455: @code{throw}n again, the return stack dump will be for the first such
12456: @code{throw}.
12457: 
12458: @c ******************************************************************
12459: @node Tools, ANS conformance, Error messages, Top
12460: @chapter Tools
12461: 
12462: @menu
12463: * ANS Report::                  Report the words used, sorted by wordset.
12464: * Stack depth changes::         Where does this stack item come from?
12465: @end menu
12466: 
12467: See also @ref{Emacs and Gforth}.
12468: 
12469: @node ANS Report, Stack depth changes, Tools, Tools
12470: @section @file{ans-report.fs}: Report the words used, sorted by wordset
12471: @cindex @file{ans-report.fs}
12472: @cindex report the words used in your program
12473: @cindex words used in your program
12474: 
12475: If you want to label a Forth program as ANS Forth Program, you must
12476: document which wordsets the program uses; for extension wordsets, it is
12477: helpful to list the words the program requires from these wordsets
12478: (because Forth systems are allowed to provide only some words of them).
12479: 
12480: The @file{ans-report.fs} tool makes it easy for you to determine which
12481: words from which wordset and which non-ANS words your application
12482: uses. You simply have to include @file{ans-report.fs} before loading the
12483: program you want to check. After loading your program, you can get the
12484: report with @code{print-ans-report}. A typical use is to run this as
12485: batch job like this:
12486: @example
12487: gforth ans-report.fs myprog.fs -e "print-ans-report bye"
12488: @end example
12489: 
12490: The output looks like this (for @file{compat/control.fs}):
12491: @example
12492: The program uses the following words
12493: from CORE :
12494: : POSTPONE THEN ; immediate ?dup IF 0= 
12495: from BLOCK-EXT :
12496: \ 
12497: from FILE :
12498: ( 
12499: @end example
12500: 
12501: @subsection Caveats
12502: 
12503: Note that @file{ans-report.fs} just checks which words are used, not whether
12504: they are used in an ANS Forth conforming way!
12505: 
12506: Some words are defined in several wordsets in the
12507: standard. @file{ans-report.fs} reports them for only one of the
12508: wordsets, and not necessarily the one you expect. It depends on usage
12509: which wordset is the right one to specify. E.g., if you only use the
12510: compilation semantics of @code{S"}, it is a Core word; if you also use
12511: its interpretation semantics, it is a File word.
12512: 
12513: 
12514: @node Stack depth changes,  , ANS Report, Tools
12515: @section Stack depth changes during interpretation
12516: @cindex @file{depth-changes.fs}
12517: @cindex depth changes during interpretation
12518: @cindex stack depth changes during interpretation
12519: @cindex items on the stack after interpretation
12520: 
12521: Sometimes you notice that, after loading a file, there are items left
12522: on the stack.  The tool @file{depth-changes.fs} helps you find out
12523: quickly where in the file these stack items are coming from.
12524: 
12525: The simplest way of using @file{depth-changes.fs} is to include it
12526: before the file(s) you want to check, e.g.:
12527: 
12528: @example
12529: gforth depth-changes.fs my-file.fs
12530: @end example
12531: 
12532: This will compare the stack depths of the data and FP stack at every
12533: empty line (in interpretation state) against these depths at the last
12534: empty line (in interpretation state).  If the depths are not equal,
12535: the position in the file and the stack contents are printed with
12536: @code{~~} (@pxref{Debugging}).  This indicates that a stack depth
12537: change has occured in the paragraph of non-empty lines before the
12538: indicated line.  It is a good idea to leave an empty line at the end
12539: of the file, so the last paragraph is checked, too.
12540: 
12541: Checking only at empty lines usually works well, but sometimes you
12542: have big blocks of non-empty lines (e.g., when building a big table),
12543: and you want to know where in this block the stack depth changed.  You
12544: can check all interpreted lines with
12545: 
12546: @example
12547: gforth depth-changes.fs -e "' all-lines is depth-changes-filter" my-file.fs
12548: @end example
12549: 
12550: This checks the stack depth at every end-of-line.  So the depth change
12551: occured in the line reported by the @code{~~} (not in the line
12552: before).
12553: 
12554: Note that, while this offers better accuracy in indicating where the
12555: stack depth changes, it will often report many intentional stack depth
12556: changes (e.g., when an interpreted computation stretches across
12557: several lines).  You can suppress the checking of some lines by
12558: putting backslashes at the end of these lines (not followed by white
12559: space), and using
12560: 
12561: @example
12562: gforth depth-changes.fs -e "' most-lines is depth-changes-filter" my-file.fs
12563: @end example
12564: 
12565: @c ******************************************************************
12566: @node ANS conformance, Standard vs Extensions, Tools, Top
12567: @chapter ANS conformance
12568: @cindex ANS conformance of Gforth
12569: 
12570: To the best of our knowledge, Gforth is an
12571: 
12572: ANS Forth System
12573: @itemize @bullet
12574: @item providing the Core Extensions word set
12575: @item providing the Block word set
12576: @item providing the Block Extensions word set
12577: @item providing the Double-Number word set
12578: @item providing the Double-Number Extensions word set
12579: @item providing the Exception word set
12580: @item providing the Exception Extensions word set
12581: @item providing the Facility word set
12582: @item providing @code{EKEY}, @code{EKEY>CHAR}, @code{EKEY?}, @code{MS} and @code{TIME&DATE} from the Facility Extensions word set
12583: @item providing the File Access word set
12584: @item providing the File Access Extensions word set
12585: @item providing the Floating-Point word set
12586: @item providing the Floating-Point Extensions word set
12587: @item providing the Locals word set
12588: @item providing the Locals Extensions word set
12589: @item providing the Memory-Allocation word set
12590: @item providing the Memory-Allocation Extensions word set (that one's easy)
12591: @item providing the Programming-Tools word set
12592: @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
12593: @item providing the Search-Order word set
12594: @item providing the Search-Order Extensions word set
12595: @item providing the String word set
12596: @item providing the String Extensions word set (another easy one)
12597: @end itemize
12598: 
12599: Gforth has the following environmental restrictions:
12600: 
12601: @cindex environmental restrictions
12602: @itemize @bullet
12603: @item
12604: While processing the OS command line, if an exception is not caught,
12605: Gforth exits with a non-zero exit code instyead of performing QUIT.
12606: 
12607: @item
12608: When an @code{throw} is performed after a @code{query}, Gforth does not
12609: allways restore the input source specification in effect at the
12610: corresponding catch.
12611: 
12612: @end itemize
12613: 
12614: 
12615: @cindex system documentation
12616: In addition, ANS Forth systems are required to document certain
12617: implementation choices. This chapter tries to meet these
12618: requirements. In many cases it gives a way to ask the system for the
12619: information instead of providing the information directly, in
12620: particular, if the information depends on the processor, the operating
12621: system or the installation options chosen, or if they are likely to
12622: change during the maintenance of Gforth.
12623: 
12624: @comment The framework for the rest has been taken from pfe.
12625: 
12626: @menu
12627: * The Core Words::              
12628: * The optional Block word set::  
12629: * The optional Double Number word set::  
12630: * The optional Exception word set::  
12631: * The optional Facility word set::  
12632: * The optional File-Access word set::  
12633: * The optional Floating-Point word set::  
12634: * The optional Locals word set::  
12635: * The optional Memory-Allocation word set::  
12636: * The optional Programming-Tools word set::  
12637: * The optional Search-Order word set::  
12638: @end menu
12639: 
12640: 
12641: @c =====================================================================
12642: @node The Core Words, The optional Block word set, ANS conformance, ANS conformance
12643: @comment  node-name,  next,  previous,  up
12644: @section The Core Words
12645: @c =====================================================================
12646: @cindex core words, system documentation
12647: @cindex system documentation, core words
12648: 
12649: @menu
12650: * core-idef::                   Implementation Defined Options                   
12651: * core-ambcond::                Ambiguous Conditions                
12652: * core-other::                  Other System Documentation                  
12653: @end menu
12654: 
12655: @c ---------------------------------------------------------------------
12656: @node core-idef, core-ambcond, The Core Words, The Core Words
12657: @subsection Implementation Defined Options
12658: @c ---------------------------------------------------------------------
12659: @cindex core words, implementation-defined options
12660: @cindex implementation-defined options, core words
12661: 
12662: 
12663: @table @i
12664: @item (Cell) aligned addresses:
12665: @cindex cell-aligned addresses
12666: @cindex aligned addresses
12667: processor-dependent. Gforth's alignment words perform natural alignment
12668: (e.g., an address aligned for a datum of size 8 is divisible by
12669: 8). Unaligned accesses usually result in a @code{-23 THROW}.
12670: 
12671: @item @code{EMIT} and non-graphic characters:
12672: @cindex @code{EMIT} and non-graphic characters
12673: @cindex non-graphic characters and @code{EMIT}
12674: The character is output using the C library function (actually, macro)
12675: @code{putc}.
12676: 
12677: @item character editing of @code{ACCEPT} and @code{EXPECT}:
12678: @cindex character editing of @code{ACCEPT} and @code{EXPECT}
12679: @cindex editing in @code{ACCEPT} and @code{EXPECT}
12680: @cindex @code{ACCEPT}, editing
12681: @cindex @code{EXPECT}, editing
12682: This is modeled on the GNU readline library (@pxref{Readline
12683: Interaction, , Command Line Editing, readline, The GNU Readline
12684: Library}) with Emacs-like key bindings. @kbd{Tab} deviates a little by
12685: producing a full word completion every time you type it (instead of
12686: producing the common prefix of all completions). @xref{Command-line editing}.
12687: 
12688: @item character set:
12689: @cindex character set
12690: The character set of your computer and display device. Gforth is
12691: 8-bit-clean (but some other component in your system may make trouble).
12692: 
12693: @item Character-aligned address requirements:
12694: @cindex character-aligned address requirements
12695: installation-dependent. Currently a character is represented by a C
12696: @code{unsigned char}; in the future we might switch to @code{wchar_t}
12697: (Comments on that requested).
12698: 
12699: @item character-set extensions and matching of names:
12700: @cindex character-set extensions and matching of names
12701: @cindex case-sensitivity for name lookup
12702: @cindex name lookup, case-sensitivity
12703: @cindex locale and case-sensitivity
12704: Any character except the ASCII NUL character can be used in a
12705: name. Matching is case-insensitive (except in @code{TABLE}s). The
12706: matching is performed using the C library function @code{strncasecmp}, whose
12707: function is probably influenced by the locale. E.g., the @code{C} locale
12708: does not know about accents and umlauts, so they are matched
12709: case-sensitively in that locale. For portability reasons it is best to
12710: write programs such that they work in the @code{C} locale. Then one can
12711: use libraries written by a Polish programmer (who might use words
12712: containing ISO Latin-2 encoded characters) and by a French programmer
12713: (ISO Latin-1) in the same program (of course, @code{WORDS} will produce
12714: funny results for some of the words (which ones, depends on the font you
12715: are using)). Also, the locale you prefer may not be available in other
12716: operating systems. Hopefully, Unicode will solve these problems one day.
12717: 
12718: @item conditions under which control characters match a space delimiter:
12719: @cindex space delimiters
12720: @cindex control characters as delimiters
12721: If @code{word} is called with the space character as a delimiter, all
12722: white-space characters (as identified by the C macro @code{isspace()})
12723: are delimiters. @code{Parse}, on the other hand, treats space like other
12724: delimiters.  @code{Parse-name}, which is used by the outer
12725: interpreter (aka text interpreter) by default, treats all white-space
12726: characters as delimiters.
12727: 
12728: @item format of the control-flow stack:
12729: @cindex control-flow stack, format
12730: The data stack is used as control-flow stack. The size of a control-flow
12731: stack item in cells is given by the constant @code{cs-item-size}. At the
12732: time of this writing, an item consists of a (pointer to a) locals list
12733: (third), an address in the code (second), and a tag for identifying the
12734: item (TOS). The following tags are used: @code{defstart},
12735: @code{live-orig}, @code{dead-orig}, @code{dest}, @code{do-dest},
12736: @code{scopestart}.
12737: 
12738: @item conversion of digits > 35
12739: @cindex digits > 35
12740: The characters @code{[\]^_'} are the digits with the decimal value
12741: 36@minus{}41. There is no way to input many of the larger digits.
12742: 
12743: @item display after input terminates in @code{ACCEPT} and @code{EXPECT}:
12744: @cindex @code{EXPECT}, display after end of input
12745: @cindex @code{ACCEPT}, display after end of input
12746: The cursor is moved to the end of the entered string. If the input is
12747: terminated using the @kbd{Return} key, a space is typed.
12748: 
12749: @item exception abort sequence of @code{ABORT"}:
12750: @cindex exception abort sequence of @code{ABORT"}
12751: @cindex @code{ABORT"}, exception abort sequence
12752: The error string is stored into the variable @code{"error} and a
12753: @code{-2 throw} is performed.
12754: 
12755: @item input line terminator:
12756: @cindex input line terminator
12757: @cindex line terminator on input
12758: @cindex newline character on input
12759: For interactive input, @kbd{C-m} (CR) and @kbd{C-j} (LF) terminate
12760: lines. One of these characters is typically produced when you type the
12761: @kbd{Enter} or @kbd{Return} key.
12762: 
12763: @item maximum size of a counted string:
12764: @cindex maximum size of a counted string
12765: @cindex counted string, maximum size
12766: @code{s" /counted-string" environment? drop .}. Currently 255 characters
12767: on all platforms, but this may change.
12768: 
12769: @item maximum size of a parsed string:
12770: @cindex maximum size of a parsed string
12771: @cindex parsed string, maximum size
12772: Given by the constant @code{/line}. Currently 255 characters.
12773: 
12774: @item maximum size of a definition name, in characters:
12775: @cindex maximum size of a definition name, in characters
12776: @cindex name, maximum length
12777: MAXU/8
12778: 
12779: @item maximum string length for @code{ENVIRONMENT?}, in characters:
12780: @cindex maximum string length for @code{ENVIRONMENT?}, in characters
12781: @cindex @code{ENVIRONMENT?} string length, maximum
12782: MAXU/8
12783: 
12784: @item method of selecting the user input device:
12785: @cindex user input device, method of selecting
12786: The user input device is the standard input. There is currently no way to
12787: change it from within Gforth. However, the input can typically be
12788: redirected in the command line that starts Gforth.
12789: 
12790: @item method of selecting the user output device:
12791: @cindex user output device, method of selecting
12792: @code{EMIT} and @code{TYPE} output to the file-id stored in the value
12793: @code{outfile-id} (@code{stdout} by default). Gforth uses unbuffered
12794: output when the user output device is a terminal, otherwise the output
12795: is buffered.
12796: 
12797: @item methods of dictionary compilation:
12798: What are we expected to document here?
12799: 
12800: @item number of bits in one address unit:
12801: @cindex number of bits in one address unit
12802: @cindex address unit, size in bits
12803: @code{s" address-units-bits" environment? drop .}. 8 in all current
12804: platforms.
12805: 
12806: @item number representation and arithmetic:
12807: @cindex number representation and arithmetic
12808: Processor-dependent. Binary two's complement on all current platforms.
12809: 
12810: @item ranges for integer types:
12811: @cindex ranges for integer types
12812: @cindex integer types, ranges
12813: Installation-dependent. Make environmental queries for @code{MAX-N},
12814: @code{MAX-U}, @code{MAX-D} and @code{MAX-UD}. The lower bounds for
12815: unsigned (and positive) types is 0. The lower bound for signed types on
12816: two's complement and one's complement machines machines can be computed
12817: by adding 1 to the upper bound.
12818: 
12819: @item read-only data space regions:
12820: @cindex read-only data space regions
12821: @cindex data-space, read-only regions
12822: The whole Forth data space is writable.
12823: 
12824: @item size of buffer at @code{WORD}:
12825: @cindex size of buffer at @code{WORD}
12826: @cindex @code{WORD} buffer size
12827: @code{PAD HERE - .}. 104 characters on 32-bit machines. The buffer is
12828: shared with the pictured numeric output string. If overwriting
12829: @code{PAD} is acceptable, it is as large as the remaining dictionary
12830: space, although only as much can be sensibly used as fits in a counted
12831: string.
12832: 
12833: @item size of one cell in address units:
12834: @cindex cell size
12835: @code{1 cells .}.
12836: 
12837: @item size of one character in address units:
12838: @cindex char size
12839: @code{1 chars .}. 1 on all current platforms.
12840: 
12841: @item size of the keyboard terminal buffer:
12842: @cindex size of the keyboard terminal buffer
12843: @cindex terminal buffer, size
12844: Varies. You can determine the size at a specific time using @code{lp@@
12845: tib - .}. It is shared with the locals stack and TIBs of files that
12846: include the current file. You can change the amount of space for TIBs
12847: and locals stack at Gforth startup with the command line option
12848: @code{-l}.
12849: 
12850: @item size of the pictured numeric output buffer:
12851: @cindex size of the pictured numeric output buffer
12852: @cindex pictured numeric output buffer, size
12853: @code{PAD HERE - .}. 104 characters on 32-bit machines. The buffer is
12854: shared with @code{WORD}.
12855: 
12856: @item size of the scratch area returned by @code{PAD}:
12857: @cindex size of the scratch area returned by @code{PAD}
12858: @cindex @code{PAD} size
12859: The remainder of dictionary space. @code{unused pad here - - .}.
12860: 
12861: @item system case-sensitivity characteristics:
12862: @cindex case-sensitivity characteristics
12863: Dictionary searches are case-insensitive (except in
12864: @code{TABLE}s). However, as explained above under @i{character-set
12865: extensions}, the matching for non-ASCII characters is determined by the
12866: locale you are using. In the default @code{C} locale all non-ASCII
12867: characters are matched case-sensitively.
12868: 
12869: @item system prompt:
12870: @cindex system prompt
12871: @cindex prompt
12872: @code{ ok} in interpret state, @code{ compiled} in compile state.
12873: 
12874: @item division rounding:
12875: @cindex division rounding
12876: installation dependent. @code{s" floored" environment? drop .}. We leave
12877: the choice to @code{gcc} (what to use for @code{/}) and to you (whether
12878: to use @code{fm/mod}, @code{sm/rem} or simply @code{/}).
12879: 
12880: @item values of @code{STATE} when true:
12881: @cindex @code{STATE} values
12882: -1.
12883: 
12884: @item values returned after arithmetic overflow:
12885: On two's complement machines, arithmetic is performed modulo
12886: 2**bits-per-cell for single arithmetic and 4**bits-per-cell for double
12887: arithmetic (with appropriate mapping for signed types). Division by zero
12888: typically results in a @code{-55 throw} (Floating-point unidentified
12889: fault) or @code{-10 throw} (divide by zero).
12890: 
12891: @item whether the current definition can be found after @t{DOES>}:
12892: @cindex @t{DOES>}, visibility of current definition
12893: No.
12894: 
12895: @end table
12896: 
12897: @c ---------------------------------------------------------------------
12898: @node core-ambcond, core-other, core-idef, The Core Words
12899: @subsection Ambiguous conditions
12900: @c ---------------------------------------------------------------------
12901: @cindex core words, ambiguous conditions
12902: @cindex ambiguous conditions, core words
12903: 
12904: @table @i
12905: 
12906: @item a name is neither a word nor a number:
12907: @cindex name not found
12908: @cindex undefined word
12909: @code{-13 throw} (Undefined word).
12910: 
12911: @item a definition name exceeds the maximum length allowed:
12912: @cindex word name too long
12913: @code{-19 throw} (Word name too long)
12914: 
12915: @item addressing a region not inside the various data spaces of the forth system:
12916: @cindex Invalid memory address
12917: The stacks, code space and header space are accessible. Machine code space is
12918: typically readable. Accessing other addresses gives results dependent on
12919: the operating system. On decent systems: @code{-9 throw} (Invalid memory
12920: address).
12921: 
12922: @item argument type incompatible with parameter:
12923: @cindex argument type mismatch
12924: This is usually not caught. Some words perform checks, e.g., the control
12925: flow words, and issue a @code{ABORT"} or @code{-12 THROW} (Argument type
12926: mismatch).
12927: 
12928: @item attempting to obtain the execution token of a word with undefined execution semantics:
12929: @cindex Interpreting a compile-only word, for @code{'} etc.
12930: @cindex execution token of words with undefined execution semantics
12931: @code{-14 throw} (Interpreting a compile-only word). In some cases, you
12932: get an execution token for @code{compile-only-error} (which performs a
12933: @code{-14 throw} when executed).
12934: 
12935: @item dividing by zero:
12936: @cindex dividing by zero
12937: @cindex floating point unidentified fault, integer division
12938: On some platforms, this produces a @code{-10 throw} (Division by
12939: zero); on other systems, this typically results in a @code{-55 throw}
12940: (Floating-point unidentified fault).
12941: 
12942: @item insufficient data stack or return stack space:
12943: @cindex insufficient data stack or return stack space
12944: @cindex stack overflow
12945: @cindex address alignment exception, stack overflow
12946: @cindex Invalid memory address, stack overflow
12947: Depending on the operating system, the installation, and the invocation
12948: of Gforth, this is either checked by the memory management hardware, or
12949: it is not checked. If it is checked, you typically get a @code{-3 throw}
12950: (Stack overflow), @code{-5 throw} (Return stack overflow), or @code{-9
12951: throw} (Invalid memory address) (depending on the platform and how you
12952: achieved the overflow) as soon as the overflow happens. If it is not
12953: checked, overflows typically result in mysterious illegal memory
12954: accesses, producing @code{-9 throw} (Invalid memory address) or
12955: @code{-23 throw} (Address alignment exception); they might also destroy
12956: the internal data structure of @code{ALLOCATE} and friends, resulting in
12957: various errors in these words.
12958: 
12959: @item insufficient space for loop control parameters:
12960: @cindex insufficient space for loop control parameters
12961: Like other return stack overflows.
12962: 
12963: @item insufficient space in the dictionary:
12964: @cindex insufficient space in the dictionary
12965: @cindex dictionary overflow
12966: If you try to allot (either directly with @code{allot}, or indirectly
12967: with @code{,}, @code{create} etc.) more memory than available in the
12968: dictionary, you get a @code{-8 throw} (Dictionary overflow). If you try
12969: to access memory beyond the end of the dictionary, the results are
12970: similar to stack overflows.
12971: 
12972: @item interpreting a word with undefined interpretation semantics:
12973: @cindex interpreting a word with undefined interpretation semantics
12974: @cindex Interpreting a compile-only word
12975: For some words, we have defined interpretation semantics. For the
12976: others: @code{-14 throw} (Interpreting a compile-only word).
12977: 
12978: @item modifying the contents of the input buffer or a string literal:
12979: @cindex modifying the contents of the input buffer or a string literal
12980: These are located in writable memory and can be modified.
12981: 
12982: @item overflow of the pictured numeric output string:
12983: @cindex overflow of the pictured numeric output string
12984: @cindex pictured numeric output string, overflow
12985: @code{-17 throw} (Pictured numeric ouput string overflow).
12986: 
12987: @item parsed string overflow:
12988: @cindex parsed string overflow
12989: @code{PARSE} cannot overflow. @code{WORD} does not check for overflow.
12990: 
12991: @item producing a result out of range:
12992: @cindex result out of range
12993: On two's complement machines, arithmetic is performed modulo
12994: 2**bits-per-cell for single arithmetic and 4**bits-per-cell for double
12995: arithmetic (with appropriate mapping for signed types). Division by zero
12996: typically results in a @code{-10 throw} (divide by zero) or @code{-55
12997: throw} (floating point unidentified fault). @code{convert} and
12998: @code{>number} currently overflow silently.
12999: 
13000: @item reading from an empty data or return stack:
13001: @cindex stack empty
13002: @cindex stack underflow
13003: @cindex return stack underflow
13004: The data stack is checked by the outer (aka text) interpreter after
13005: every word executed. If it has underflowed, a @code{-4 throw} (Stack
13006: underflow) is performed. Apart from that, stacks may be checked or not,
13007: depending on operating system, installation, and invocation. If they are
13008: caught by a check, they typically result in @code{-4 throw} (Stack
13009: underflow), @code{-6 throw} (Return stack underflow) or @code{-9 throw}
13010: (Invalid memory address), depending on the platform and which stack
13011: underflows and by how much. Note that even if the system uses checking
13012: (through the MMU), your program may have to underflow by a significant
13013: number of stack items to trigger the reaction (the reason for this is
13014: that the MMU, and therefore the checking, works with a page-size
13015: granularity).  If there is no checking, the symptoms resulting from an
13016: underflow are similar to those from an overflow.  Unbalanced return
13017: stack errors can result in a variety of symptoms, including @code{-9 throw}
13018: (Invalid memory address) and Illegal Instruction (typically @code{-260
13019: throw}).
13020: 
13021: @item unexpected end of the input buffer, resulting in an attempt to use a zero-length string as a name:
13022: @cindex unexpected end of the input buffer
13023: @cindex zero-length string as a name
13024: @cindex Attempt to use zero-length string as a name
13025: @code{Create} and its descendants perform a @code{-16 throw} (Attempt to
13026: use zero-length string as a name). Words like @code{'} probably will not
13027: find what they search. Note that it is possible to create zero-length
13028: names with @code{nextname} (should it not?).
13029: 
13030: @item @code{>IN} greater than input buffer:
13031: @cindex @code{>IN} greater than input buffer
13032: The next invocation of a parsing word returns a string with length 0.
13033: 
13034: @item @code{RECURSE} appears after @code{DOES>}:
13035: @cindex @code{RECURSE} appears after @code{DOES>}
13036: Compiles a recursive call to the defining word, not to the defined word.
13037: 
13038: @item argument input source different than current input source for @code{RESTORE-INPUT}:
13039: @cindex argument input source different than current input source for @code{RESTORE-INPUT}
13040: @cindex argument type mismatch, @code{RESTORE-INPUT}
13041: @cindex @code{RESTORE-INPUT}, Argument type mismatch
13042: @code{-12 THROW}. Note that, once an input file is closed (e.g., because
13043: the end of the file was reached), its source-id may be
13044: reused. Therefore, restoring an input source specification referencing a
13045: closed file may lead to unpredictable results instead of a @code{-12
13046: THROW}.
13047: 
13048: In the future, Gforth may be able to restore input source specifications
13049: from other than the current input source.
13050: 
13051: @item data space containing definitions gets de-allocated:
13052: @cindex data space containing definitions gets de-allocated
13053: Deallocation with @code{allot} is not checked. This typically results in
13054: memory access faults or execution of illegal instructions.
13055: 
13056: @item data space read/write with incorrect alignment:
13057: @cindex data space read/write with incorrect alignment
13058: @cindex alignment faults
13059: @cindex address alignment exception
13060: Processor-dependent. Typically results in a @code{-23 throw} (Address
13061: alignment exception). Under Linux-Intel on a 486 or later processor with
13062: alignment turned on, incorrect alignment results in a @code{-9 throw}
13063: (Invalid memory address). There are reportedly some processors with
13064: alignment restrictions that do not report violations.
13065: 
13066: @item data space pointer not properly aligned, @code{,}, @code{C,}:
13067: @cindex data space pointer not properly aligned, @code{,}, @code{C,}
13068: Like other alignment errors.
13069: 
13070: @item less than u+2 stack items (@code{PICK} and @code{ROLL}):
13071: Like other stack underflows.
13072: 
13073: @item loop control parameters not available:
13074: @cindex loop control parameters not available
13075: Not checked. The counted loop words simply assume that the top of return
13076: stack items are loop control parameters and behave accordingly.
13077: 
13078: @item most recent definition does not have a name (@code{IMMEDIATE}):
13079: @cindex most recent definition does not have a name (@code{IMMEDIATE})
13080: @cindex last word was headerless
13081: @code{abort" last word was headerless"}.
13082: 
13083: @item name not defined by @code{VALUE} used by @code{TO}:
13084: @cindex name not defined by @code{VALUE} used by @code{TO}
13085: @cindex @code{TO} on non-@code{VALUE}s
13086: @cindex Invalid name argument, @code{TO}
13087: @code{-32 throw} (Invalid name argument) (unless name is a local or was
13088: defined by @code{CONSTANT}; in the latter case it just changes the constant).
13089: 
13090: @item name not found (@code{'}, @code{POSTPONE}, @code{[']}, @code{[COMPILE]}):
13091: @cindex name not found (@code{'}, @code{POSTPONE}, @code{[']}, @code{[COMPILE]})
13092: @cindex undefined word, @code{'}, @code{POSTPONE}, @code{[']}, @code{[COMPILE]}
13093: @code{-13 throw} (Undefined word)
13094: 
13095: @item parameters are not of the same type (@code{DO}, @code{?DO}, @code{WITHIN}):
13096: @cindex parameters are not of the same type (@code{DO}, @code{?DO}, @code{WITHIN})
13097: Gforth behaves as if they were of the same type. I.e., you can predict
13098: the behaviour by interpreting all parameters as, e.g., signed.
13099: 
13100: @item @code{POSTPONE} or @code{[COMPILE]} applied to @code{TO}:
13101: @cindex @code{POSTPONE} or @code{[COMPILE]} applied to @code{TO}
13102: Assume @code{: X POSTPONE TO ; IMMEDIATE}. @code{X} performs the
13103: compilation semantics of @code{TO}.
13104: 
13105: @item String longer than a counted string returned by @code{WORD}:
13106: @cindex string longer than a counted string returned by @code{WORD}
13107: @cindex @code{WORD}, string overflow
13108: Not checked. The string will be ok, but the count will, of course,
13109: contain only the least significant bits of the length.
13110: 
13111: @item u greater than or equal to the number of bits in a cell (@code{LSHIFT}, @code{RSHIFT}):
13112: @cindex @code{LSHIFT}, large shift counts
13113: @cindex @code{RSHIFT}, large shift counts
13114: Processor-dependent. Typical behaviours are returning 0 and using only
13115: the low bits of the shift count.
13116: 
13117: @item word not defined via @code{CREATE}:
13118: @cindex @code{>BODY} of non-@code{CREATE}d words
13119: @code{>BODY} produces the PFA of the word no matter how it was defined.
13120: 
13121: @cindex @code{DOES>} of non-@code{CREATE}d words
13122: @code{DOES>} changes the execution semantics of the last defined word no
13123: matter how it was defined. E.g., @code{CONSTANT DOES>} is equivalent to
13124: @code{CREATE , DOES>}.
13125: 
13126: @item words improperly used outside @code{<#} and @code{#>}:
13127: Not checked. As usual, you can expect memory faults.
13128: 
13129: @end table
13130: 
13131: 
13132: @c ---------------------------------------------------------------------
13133: @node core-other,  , core-ambcond, The Core Words
13134: @subsection Other system documentation
13135: @c ---------------------------------------------------------------------
13136: @cindex other system documentation, core words
13137: @cindex core words, other system documentation
13138: 
13139: @table @i
13140: @item nonstandard words using @code{PAD}:
13141: @cindex @code{PAD} use by nonstandard words
13142: None.
13143: 
13144: @item operator's terminal facilities available:
13145: @cindex operator's terminal facilities available
13146: After processing the OS's command line, Gforth goes into interactive mode,
13147: and you can give commands to Gforth interactively. The actual facilities
13148: available depend on how you invoke Gforth.
13149: 
13150: @item program data space available:
13151: @cindex program data space available
13152: @cindex data space available
13153: @code{UNUSED .} gives the remaining dictionary space. The total
13154: dictionary space can be specified with the @code{-m} switch
13155: (@pxref{Invoking Gforth}) when Gforth starts up.
13156: 
13157: @item return stack space available:
13158: @cindex return stack space available
13159: You can compute the total return stack space in cells with
13160: @code{s" RETURN-STACK-CELLS" environment? drop .}. You can specify it at
13161: startup time with the @code{-r} switch (@pxref{Invoking Gforth}).
13162: 
13163: @item stack space available:
13164: @cindex stack space available
13165: You can compute the total data stack space in cells with
13166: @code{s" STACK-CELLS" environment? drop .}. You can specify it at
13167: startup time with the @code{-d} switch (@pxref{Invoking Gforth}).
13168: 
13169: @item system dictionary space required, in address units:
13170: @cindex system dictionary space required, in address units
13171: Type @code{here forthstart - .} after startup. At the time of this
13172: writing, this gives 80080 (bytes) on a 32-bit system.
13173: @end table
13174: 
13175: 
13176: @c =====================================================================
13177: @node The optional Block word set, The optional Double Number word set, The Core Words, ANS conformance
13178: @section The optional Block word set
13179: @c =====================================================================
13180: @cindex system documentation, block words
13181: @cindex block words, system documentation
13182: 
13183: @menu
13184: * block-idef::                  Implementation Defined Options
13185: * block-ambcond::               Ambiguous Conditions               
13186: * block-other::                 Other System Documentation                 
13187: @end menu
13188: 
13189: 
13190: @c ---------------------------------------------------------------------
13191: @node block-idef, block-ambcond, The optional Block word set, The optional Block word set
13192: @subsection Implementation Defined Options
13193: @c ---------------------------------------------------------------------
13194: @cindex implementation-defined options, block words
13195: @cindex block words, implementation-defined options
13196: 
13197: @table @i
13198: @item the format for display by @code{LIST}:
13199: @cindex @code{LIST} display format
13200: First the screen number is displayed, then 16 lines of 64 characters,
13201: each line preceded by the line number.
13202: 
13203: @item the length of a line affected by @code{\}:
13204: @cindex length of a line affected by @code{\}
13205: @cindex @code{\}, line length in blocks
13206: 64 characters.
13207: @end table
13208: 
13209: 
13210: @c ---------------------------------------------------------------------
13211: @node block-ambcond, block-other, block-idef, The optional Block word set
13212: @subsection Ambiguous conditions
13213: @c ---------------------------------------------------------------------
13214: @cindex block words, ambiguous conditions
13215: @cindex ambiguous conditions, block words
13216: 
13217: @table @i
13218: @item correct block read was not possible:
13219: @cindex block read not possible
13220: Typically results in a @code{throw} of some OS-derived value (between
13221: -512 and -2048). If the blocks file was just not long enough, blanks are
13222: supplied for the missing portion.
13223: 
13224: @item I/O exception in block transfer:
13225: @cindex I/O exception in block transfer
13226: @cindex block transfer, I/O exception
13227: Typically results in a @code{throw} of some OS-derived value (between
13228: -512 and -2048).
13229: 
13230: @item invalid block number:
13231: @cindex invalid block number
13232: @cindex block number invalid
13233: @code{-35 throw} (Invalid block number)
13234: 
13235: @item a program directly alters the contents of @code{BLK}:
13236: @cindex @code{BLK}, altering @code{BLK}
13237: The input stream is switched to that other block, at the same
13238: position. If the storing to @code{BLK} happens when interpreting
13239: non-block input, the system will get quite confused when the block ends.
13240: 
13241: @item no current block buffer for @code{UPDATE}:
13242: @cindex @code{UPDATE}, no current block buffer
13243: @code{UPDATE} has no effect.
13244: 
13245: @end table
13246: 
13247: @c ---------------------------------------------------------------------
13248: @node block-other,  , block-ambcond, The optional Block word set
13249: @subsection Other system documentation
13250: @c ---------------------------------------------------------------------
13251: @cindex other system documentation, block words
13252: @cindex block words, other system documentation
13253: 
13254: @table @i
13255: @item any restrictions a multiprogramming system places on the use of buffer addresses:
13256: No restrictions (yet).
13257: 
13258: @item the number of blocks available for source and data:
13259: depends on your disk space.
13260: 
13261: @end table
13262: 
13263: 
13264: @c =====================================================================
13265: @node The optional Double Number word set, The optional Exception word set, The optional Block word set, ANS conformance
13266: @section The optional Double Number word set
13267: @c =====================================================================
13268: @cindex system documentation, double words
13269: @cindex double words, system documentation
13270: 
13271: @menu
13272: * double-ambcond::              Ambiguous Conditions              
13273: @end menu
13274: 
13275: 
13276: @c ---------------------------------------------------------------------
13277: @node double-ambcond,  , The optional Double Number word set, The optional Double Number word set
13278: @subsection Ambiguous conditions
13279: @c ---------------------------------------------------------------------
13280: @cindex double words, ambiguous conditions
13281: @cindex ambiguous conditions, double words
13282: 
13283: @table @i
13284: @item @i{d} outside of range of @i{n} in @code{D>S}:
13285: @cindex @code{D>S}, @i{d} out of range of @i{n} 
13286: The least significant cell of @i{d} is produced.
13287: 
13288: @end table
13289: 
13290: 
13291: @c =====================================================================
13292: @node The optional Exception word set, The optional Facility word set, The optional Double Number word set, ANS conformance
13293: @section The optional Exception word set
13294: @c =====================================================================
13295: @cindex system documentation, exception words
13296: @cindex exception words, system documentation
13297: 
13298: @menu
13299: * exception-idef::              Implementation Defined Options              
13300: @end menu
13301: 
13302: 
13303: @c ---------------------------------------------------------------------
13304: @node exception-idef,  , The optional Exception word set, The optional Exception word set
13305: @subsection Implementation Defined Options
13306: @c ---------------------------------------------------------------------
13307: @cindex implementation-defined options, exception words
13308: @cindex exception words, implementation-defined options
13309: 
13310: @table @i
13311: @item @code{THROW}-codes used in the system:
13312: @cindex @code{THROW}-codes used in the system
13313: The codes -256@minus{}-511 are used for reporting signals. The mapping
13314: from OS signal numbers to throw codes is -256@minus{}@i{signal}. The
13315: codes -512@minus{}-2047 are used for OS errors (for file and memory
13316: allocation operations). The mapping from OS error numbers to throw codes
13317: is -512@minus{}@code{errno}. One side effect of this mapping is that
13318: undefined OS errors produce a message with a strange number; e.g.,
13319: @code{-1000 THROW} results in @code{Unknown error 488} on my system.
13320: @end table
13321: 
13322: @c =====================================================================
13323: @node The optional Facility word set, The optional File-Access word set, The optional Exception word set, ANS conformance
13324: @section The optional Facility word set
13325: @c =====================================================================
13326: @cindex system documentation, facility words
13327: @cindex facility words, system documentation
13328: 
13329: @menu
13330: * facility-idef::               Implementation Defined Options               
13331: * facility-ambcond::            Ambiguous Conditions            
13332: @end menu
13333: 
13334: 
13335: @c ---------------------------------------------------------------------
13336: @node facility-idef, facility-ambcond, The optional Facility word set, The optional Facility word set
13337: @subsection Implementation Defined Options
13338: @c ---------------------------------------------------------------------
13339: @cindex implementation-defined options, facility words
13340: @cindex facility words, implementation-defined options
13341: 
13342: @table @i
13343: @item encoding of keyboard events (@code{EKEY}):
13344: @cindex keyboard events, encoding in @code{EKEY}
13345: @cindex @code{EKEY}, encoding of keyboard events
13346: Keys corresponding to ASCII characters are encoded as ASCII characters.
13347: Other keys are encoded with the constants @code{k-left}, @code{k-right},
13348: @code{k-up}, @code{k-down}, @code{k-home}, @code{k-end}, @code{k1},
13349: @code{k2}, @code{k3}, @code{k4}, @code{k5}, @code{k6}, @code{k7},
13350: @code{k8}, @code{k9}, @code{k10}, @code{k11}, @code{k12}.
13351: 
13352: 
13353: @item duration of a system clock tick:
13354: @cindex duration of a system clock tick
13355: @cindex clock tick duration
13356: System dependent. With respect to @code{MS}, the time is specified in
13357: microseconds. How well the OS and the hardware implement this, is
13358: another question.
13359: 
13360: @item repeatability to be expected from the execution of @code{MS}:
13361: @cindex repeatability to be expected from the execution of @code{MS}
13362: @cindex @code{MS}, repeatability to be expected
13363: System dependent. On Unix, a lot depends on load. If the system is
13364: lightly loaded, and the delay is short enough that Gforth does not get
13365: swapped out, the performance should be acceptable. Under MS-DOS and
13366: other single-tasking systems, it should be good.
13367: 
13368: @end table
13369: 
13370: 
13371: @c ---------------------------------------------------------------------
13372: @node facility-ambcond,  , facility-idef, The optional Facility word set
13373: @subsection Ambiguous conditions
13374: @c ---------------------------------------------------------------------
13375: @cindex facility words, ambiguous conditions
13376: @cindex ambiguous conditions, facility words
13377: 
13378: @table @i
13379: @item @code{AT-XY} can't be performed on user output device:
13380: @cindex @code{AT-XY} can't be performed on user output device
13381: Largely terminal dependent. No range checks are done on the arguments.
13382: No errors are reported. You may see some garbage appearing, you may see
13383: simply nothing happen.
13384: 
13385: @end table
13386: 
13387: 
13388: @c =====================================================================
13389: @node The optional File-Access word set, The optional Floating-Point word set, The optional Facility word set, ANS conformance
13390: @section The optional File-Access word set
13391: @c =====================================================================
13392: @cindex system documentation, file words
13393: @cindex file words, system documentation
13394: 
13395: @menu
13396: * file-idef::                   Implementation Defined Options
13397: * file-ambcond::                Ambiguous Conditions                
13398: @end menu
13399: 
13400: @c ---------------------------------------------------------------------
13401: @node file-idef, file-ambcond, The optional File-Access word set, The optional File-Access word set
13402: @subsection Implementation Defined Options
13403: @c ---------------------------------------------------------------------
13404: @cindex implementation-defined options, file words
13405: @cindex file words, implementation-defined options
13406: 
13407: @table @i
13408: @item file access methods used:
13409: @cindex file access methods used
13410: @code{R/O}, @code{R/W} and @code{BIN} work as you would
13411: expect. @code{W/O} translates into the C file opening mode @code{w} (or
13412: @code{wb}): The file is cleared, if it exists, and created, if it does
13413: not (with both @code{open-file} and @code{create-file}).  Under Unix
13414: @code{create-file} creates a file with 666 permissions modified by your
13415: umask.
13416: 
13417: @item file exceptions:
13418: @cindex file exceptions
13419: The file words do not raise exceptions (except, perhaps, memory access
13420: faults when you pass illegal addresses or file-ids).
13421: 
13422: @item file line terminator:
13423: @cindex file line terminator
13424: System-dependent. Gforth uses C's newline character as line
13425: terminator. What the actual character code(s) of this are is
13426: system-dependent.
13427: 
13428: @item file name format:
13429: @cindex file name format
13430: System dependent. Gforth just uses the file name format of your OS.
13431: 
13432: @item information returned by @code{FILE-STATUS}:
13433: @cindex @code{FILE-STATUS}, returned information
13434: @code{FILE-STATUS} returns the most powerful file access mode allowed
13435: for the file: Either @code{R/O}, @code{W/O} or @code{R/W}. If the file
13436: cannot be accessed, @code{R/O BIN} is returned. @code{BIN} is applicable
13437: along with the returned mode.
13438: 
13439: @item input file state after an exception when including source:
13440: @cindex exception when including source
13441: All files that are left via the exception are closed.
13442: 
13443: @item @i{ior} values and meaning:
13444: @cindex @i{ior} values and meaning
13445: @cindex @i{wior} values and meaning
13446: The @i{ior}s returned by the file and memory allocation words are
13447: intended as throw codes. They typically are in the range
13448: -512@minus{}-2047 of OS errors.  The mapping from OS error numbers to
13449: @i{ior}s is -512@minus{}@i{errno}.
13450: 
13451: @item maximum depth of file input nesting:
13452: @cindex maximum depth of file input nesting
13453: @cindex file input nesting, maximum depth
13454: limited by the amount of return stack, locals/TIB stack, and the number
13455: of open files available. This should not give you troubles.
13456: 
13457: @item maximum size of input line:
13458: @cindex maximum size of input line
13459: @cindex input line size, maximum
13460: @code{/line}. Currently 255.
13461: 
13462: @item methods of mapping block ranges to files:
13463: @cindex mapping block ranges to files
13464: @cindex files containing blocks
13465: @cindex blocks in files
13466: By default, blocks are accessed in the file @file{blocks.fb} in the
13467: current working directory. The file can be switched with @code{USE}.
13468: 
13469: @item number of string buffers provided by @code{S"}:
13470: @cindex @code{S"}, number of string buffers
13471: 1
13472: 
13473: @item size of string buffer used by @code{S"}:
13474: @cindex @code{S"}, size of string buffer
13475: @code{/line}. currently 255.
13476: 
13477: @end table
13478: 
13479: @c ---------------------------------------------------------------------
13480: @node file-ambcond,  , file-idef, The optional File-Access word set
13481: @subsection Ambiguous conditions
13482: @c ---------------------------------------------------------------------
13483: @cindex file words, ambiguous conditions
13484: @cindex ambiguous conditions, file words
13485: 
13486: @table @i
13487: @item attempting to position a file outside its boundaries:
13488: @cindex @code{REPOSITION-FILE}, outside the file's boundaries
13489: @code{REPOSITION-FILE} is performed as usual: Afterwards,
13490: @code{FILE-POSITION} returns the value given to @code{REPOSITION-FILE}.
13491: 
13492: @item attempting to read from file positions not yet written:
13493: @cindex reading from file positions not yet written
13494: End-of-file, i.e., zero characters are read and no error is reported.
13495: 
13496: @item @i{file-id} is invalid (@code{INCLUDE-FILE}):
13497: @cindex @code{INCLUDE-FILE}, @i{file-id} is invalid 
13498: An appropriate exception may be thrown, but a memory fault or other
13499: problem is more probable.
13500: 
13501: @item I/O exception reading or closing @i{file-id} (@code{INCLUDE-FILE}, @code{INCLUDED}):
13502: @cindex @code{INCLUDE-FILE}, I/O exception reading or closing @i{file-id}
13503: @cindex @code{INCLUDED}, I/O exception reading or closing @i{file-id}
13504: The @i{ior} produced by the operation, that discovered the problem, is
13505: thrown.
13506: 
13507: @item named file cannot be opened (@code{INCLUDED}):
13508: @cindex @code{INCLUDED}, named file cannot be opened
13509: The @i{ior} produced by @code{open-file} is thrown.
13510: 
13511: @item requesting an unmapped block number:
13512: @cindex unmapped block numbers
13513: There are no unmapped legal block numbers. On some operating systems,
13514: writing a block with a large number may overflow the file system and
13515: have an error message as consequence.
13516: 
13517: @item using @code{source-id} when @code{blk} is non-zero:
13518: @cindex @code{SOURCE-ID}, behaviour when @code{BLK} is non-zero
13519: @code{source-id} performs its function. Typically it will give the id of
13520: the source which loaded the block. (Better ideas?)
13521: 
13522: @end table
13523: 
13524: 
13525: @c =====================================================================
13526: @node  The optional Floating-Point word set, The optional Locals word set, The optional File-Access word set, ANS conformance
13527: @section The optional Floating-Point word set
13528: @c =====================================================================
13529: @cindex system documentation, floating-point words
13530: @cindex floating-point words, system documentation
13531: 
13532: @menu
13533: * floating-idef::               Implementation Defined Options
13534: * floating-ambcond::            Ambiguous Conditions            
13535: @end menu
13536: 
13537: 
13538: @c ---------------------------------------------------------------------
13539: @node floating-idef, floating-ambcond, The optional Floating-Point word set, The optional Floating-Point word set
13540: @subsection Implementation Defined Options
13541: @c ---------------------------------------------------------------------
13542: @cindex implementation-defined options, floating-point words
13543: @cindex floating-point words, implementation-defined options
13544: 
13545: @table @i
13546: @item format and range of floating point numbers:
13547: @cindex format and range of floating point numbers
13548: @cindex floating point numbers, format and range
13549: System-dependent; the @code{double} type of C.
13550: 
13551: @item results of @code{REPRESENT} when @i{float} is out of range:
13552: @cindex  @code{REPRESENT}, results when @i{float} is out of range
13553: System dependent; @code{REPRESENT} is implemented using the C library
13554: function @code{ecvt()} and inherits its behaviour in this respect.
13555: 
13556: @item rounding or truncation of floating-point numbers:
13557: @cindex rounding of floating-point numbers
13558: @cindex truncation of floating-point numbers
13559: @cindex floating-point numbers, rounding or truncation
13560: System dependent; the rounding behaviour is inherited from the hosting C
13561: compiler. IEEE-FP-based (i.e., most) systems by default round to
13562: nearest, and break ties by rounding to even (i.e., such that the last
13563: bit of the mantissa is 0).
13564: 
13565: @item size of floating-point stack:
13566: @cindex floating-point stack size
13567: @code{s" FLOATING-STACK" environment? drop .} gives the total size of
13568: the floating-point stack (in floats). You can specify this on startup
13569: with the command-line option @code{-f} (@pxref{Invoking Gforth}).
13570: 
13571: @item width of floating-point stack:
13572: @cindex floating-point stack width 
13573: @code{1 floats}.
13574: 
13575: @end table
13576: 
13577: 
13578: @c ---------------------------------------------------------------------
13579: @node floating-ambcond,  , floating-idef, The optional Floating-Point word set
13580: @subsection Ambiguous conditions
13581: @c ---------------------------------------------------------------------
13582: @cindex floating-point words, ambiguous conditions
13583: @cindex ambiguous conditions, floating-point words
13584: 
13585: @table @i
13586: @item @code{df@@} or @code{df!} used with an address that is not double-float  aligned:
13587: @cindex @code{df@@} or @code{df!} used with an address that is not double-float  aligned
13588: System-dependent. Typically results in a @code{-23 THROW} like other
13589: alignment violations.
13590: 
13591: @item @code{f@@} or @code{f!} used with an address that is not float  aligned:
13592: @cindex @code{f@@} used with an address that is not float aligned
13593: @cindex @code{f!} used with an address that is not float aligned
13594: System-dependent. Typically results in a @code{-23 THROW} like other
13595: alignment violations.
13596: 
13597: @item floating-point result out of range:
13598: @cindex floating-point result out of range
13599: System-dependent. Can result in a @code{-43 throw} (floating point
13600: overflow), @code{-54 throw} (floating point underflow), @code{-41 throw}
13601: (floating point inexact result), @code{-55 THROW} (Floating-point
13602: unidentified fault), or can produce a special value representing, e.g.,
13603: Infinity.
13604: 
13605: @item @code{sf@@} or @code{sf!} used with an address that is not single-float  aligned:
13606: @cindex @code{sf@@} or @code{sf!} used with an address that is not single-float  aligned
13607: System-dependent. Typically results in an alignment fault like other
13608: alignment violations.
13609: 
13610: @item @code{base} is not decimal (@code{REPRESENT}, @code{F.}, @code{FE.}, @code{FS.}):
13611: @cindex @code{base} is not decimal (@code{REPRESENT}, @code{F.}, @code{FE.}, @code{FS.})
13612: The floating-point number is converted into decimal nonetheless.
13613: 
13614: @item Both arguments are equal to zero (@code{FATAN2}):
13615: @cindex @code{FATAN2}, both arguments are equal to zero
13616: System-dependent. @code{FATAN2} is implemented using the C library
13617: function @code{atan2()}.
13618: 
13619: @item Using @code{FTAN} on an argument @i{r1} where cos(@i{r1}) is zero:
13620: @cindex @code{FTAN} on an argument @i{r1} where cos(@i{r1}) is zero
13621: System-dependent. Anyway, typically the cos of @i{r1} will not be zero
13622: because of small errors and the tan will be a very large (or very small)
13623: but finite number.
13624: 
13625: @item @i{d} cannot be presented precisely as a float in @code{D>F}:
13626: @cindex @code{D>F}, @i{d} cannot be presented precisely as a float
13627: The result is rounded to the nearest float.
13628: 
13629: @item dividing by zero:
13630: @cindex dividing by zero, floating-point
13631: @cindex floating-point dividing by zero
13632: @cindex floating-point unidentified fault, FP divide-by-zero
13633: Platform-dependent; can produce an Infinity, NaN, @code{-42 throw}
13634: (floating point divide by zero) or @code{-55 throw} (Floating-point
13635: unidentified fault).
13636: 
13637: @item exponent too big for conversion (@code{DF!}, @code{DF@@}, @code{SF!}, @code{SF@@}):
13638: @cindex exponent too big for conversion (@code{DF!}, @code{DF@@}, @code{SF!}, @code{SF@@})
13639: System dependent. On IEEE-FP based systems the number is converted into
13640: an infinity.
13641: 
13642: @item @i{float}<1 (@code{FACOSH}):
13643: @cindex @code{FACOSH}, @i{float}<1
13644: @cindex floating-point unidentified fault, @code{FACOSH}
13645: Platform-dependent; on IEEE-FP systems typically produces a NaN.
13646: 
13647: @item @i{float}=<-1 (@code{FLNP1}):
13648: @cindex @code{FLNP1}, @i{float}=<-1
13649: @cindex floating-point unidentified fault, @code{FLNP1}
13650: Platform-dependent; on IEEE-FP systems typically produces a NaN (or a
13651: negative infinity for @i{float}=-1).
13652: 
13653: @item @i{float}=<0 (@code{FLN}, @code{FLOG}):
13654: @cindex @code{FLN}, @i{float}=<0
13655: @cindex @code{FLOG}, @i{float}=<0
13656: @cindex floating-point unidentified fault, @code{FLN} or @code{FLOG}
13657: Platform-dependent; on IEEE-FP systems typically produces a NaN (or a
13658: negative infinity for @i{float}=0).
13659: 
13660: @item @i{float}<0 (@code{FASINH}, @code{FSQRT}):
13661: @cindex @code{FASINH}, @i{float}<0
13662: @cindex @code{FSQRT}, @i{float}<0
13663: @cindex floating-point unidentified fault, @code{FASINH} or @code{FSQRT}
13664: Platform-dependent; for @code{fsqrt} this typically gives a NaN, for
13665: @code{fasinh} some platforms produce a NaN, others a number (bug in the
13666: C library?).
13667: 
13668: @item |@i{float}|>1 (@code{FACOS}, @code{FASIN}, @code{FATANH}):
13669: @cindex @code{FACOS}, |@i{float}|>1
13670: @cindex @code{FASIN}, |@i{float}|>1
13671: @cindex @code{FATANH}, |@i{float}|>1
13672: @cindex floating-point unidentified fault, @code{FACOS}, @code{FASIN} or @code{FATANH}
13673: Platform-dependent; IEEE-FP systems typically produce a NaN.
13674: 
13675: @item integer part of float cannot be represented by @i{d} in @code{F>D}:
13676: @cindex @code{F>D}, integer part of float cannot be represented by @i{d}
13677: @cindex floating-point unidentified fault, @code{F>D}
13678: Platform-dependent; typically, some double number is produced and no
13679: error is reported.
13680: 
13681: @item string larger than pictured numeric output area (@code{f.}, @code{fe.}, @code{fs.}):
13682: @cindex string larger than pictured numeric output area (@code{f.}, @code{fe.}, @code{fs.})
13683: @code{Precision} characters of the numeric output area are used.  If
13684: @code{precision} is too high, these words will smash the data or code
13685: close to @code{here}.
13686: @end table
13687: 
13688: @c =====================================================================
13689: @node  The optional Locals word set, The optional Memory-Allocation word set, The optional Floating-Point word set, ANS conformance
13690: @section The optional Locals word set
13691: @c =====================================================================
13692: @cindex system documentation, locals words
13693: @cindex locals words, system documentation
13694: 
13695: @menu
13696: * locals-idef::                 Implementation Defined Options                 
13697: * locals-ambcond::              Ambiguous Conditions              
13698: @end menu
13699: 
13700: 
13701: @c ---------------------------------------------------------------------
13702: @node locals-idef, locals-ambcond, The optional Locals word set, The optional Locals word set
13703: @subsection Implementation Defined Options
13704: @c ---------------------------------------------------------------------
13705: @cindex implementation-defined options, locals words
13706: @cindex locals words, implementation-defined options
13707: 
13708: @table @i
13709: @item maximum number of locals in a definition:
13710: @cindex maximum number of locals in a definition
13711: @cindex locals, maximum number in a definition
13712: @code{s" #locals" environment? drop .}. Currently 15. This is a lower
13713: bound, e.g., on a 32-bit machine there can be 41 locals of up to 8
13714: characters. The number of locals in a definition is bounded by the size
13715: of locals-buffer, which contains the names of the locals.
13716: 
13717: @end table
13718: 
13719: 
13720: @c ---------------------------------------------------------------------
13721: @node locals-ambcond,  , locals-idef, The optional Locals word set
13722: @subsection Ambiguous conditions
13723: @c ---------------------------------------------------------------------
13724: @cindex locals words, ambiguous conditions
13725: @cindex ambiguous conditions, locals words
13726: 
13727: @table @i
13728: @item executing a named local in interpretation state:
13729: @cindex local in interpretation state
13730: @cindex Interpreting a compile-only word, for a local
13731: Locals have no interpretation semantics. If you try to perform the
13732: interpretation semantics, you will get a @code{-14 throw} somewhere
13733: (Interpreting a compile-only word). If you perform the compilation
13734: semantics, the locals access will be compiled (irrespective of state).
13735: 
13736: @item @i{name} not defined by @code{VALUE} or @code{(LOCAL)} (@code{TO}):
13737: @cindex name not defined by @code{VALUE} or @code{(LOCAL)} used by @code{TO}
13738: @cindex @code{TO} on non-@code{VALUE}s and non-locals
13739: @cindex Invalid name argument, @code{TO}
13740: @code{-32 throw} (Invalid name argument)
13741: 
13742: @end table
13743: 
13744: 
13745: @c =====================================================================
13746: @node  The optional Memory-Allocation word set, The optional Programming-Tools word set, The optional Locals word set, ANS conformance
13747: @section The optional Memory-Allocation word set
13748: @c =====================================================================
13749: @cindex system documentation, memory-allocation words
13750: @cindex memory-allocation words, system documentation
13751: 
13752: @menu
13753: * memory-idef::                 Implementation Defined Options                 
13754: @end menu
13755: 
13756: 
13757: @c ---------------------------------------------------------------------
13758: @node memory-idef,  , The optional Memory-Allocation word set, The optional Memory-Allocation word set
13759: @subsection Implementation Defined Options
13760: @c ---------------------------------------------------------------------
13761: @cindex implementation-defined options, memory-allocation words
13762: @cindex memory-allocation words, implementation-defined options
13763: 
13764: @table @i
13765: @item values and meaning of @i{ior}:
13766: @cindex  @i{ior} values and meaning
13767: The @i{ior}s returned by the file and memory allocation words are
13768: intended as throw codes. They typically are in the range
13769: -512@minus{}-2047 of OS errors.  The mapping from OS error numbers to
13770: @i{ior}s is -512@minus{}@i{errno}.
13771: 
13772: @end table
13773: 
13774: @c =====================================================================
13775: @node  The optional Programming-Tools word set, The optional Search-Order word set, The optional Memory-Allocation word set, ANS conformance
13776: @section The optional Programming-Tools word set
13777: @c =====================================================================
13778: @cindex system documentation, programming-tools words
13779: @cindex programming-tools words, system documentation
13780: 
13781: @menu
13782: * programming-idef::            Implementation Defined Options            
13783: * programming-ambcond::         Ambiguous Conditions         
13784: @end menu
13785: 
13786: 
13787: @c ---------------------------------------------------------------------
13788: @node programming-idef, programming-ambcond, The optional Programming-Tools word set, The optional Programming-Tools word set
13789: @subsection Implementation Defined Options
13790: @c ---------------------------------------------------------------------
13791: @cindex implementation-defined options, programming-tools words
13792: @cindex programming-tools words, implementation-defined options
13793: 
13794: @table @i
13795: @item ending sequence for input following @code{;CODE} and @code{CODE}:
13796: @cindex @code{;CODE} ending sequence
13797: @cindex @code{CODE} ending sequence
13798: @code{END-CODE}
13799: 
13800: @item manner of processing input following @code{;CODE} and @code{CODE}:
13801: @cindex @code{;CODE}, processing input
13802: @cindex @code{CODE}, processing input
13803: The @code{ASSEMBLER} vocabulary is pushed on the search order stack, and
13804: the input is processed by the text interpreter, (starting) in interpret
13805: state.
13806: 
13807: @item search order capability for @code{EDITOR} and @code{ASSEMBLER}:
13808: @cindex @code{ASSEMBLER}, search order capability
13809: The ANS Forth search order word set.
13810: 
13811: @item source and format of display by @code{SEE}:
13812: @cindex @code{SEE}, source and format of output
13813: The source for @code{see} is the executable code used by the inner
13814: interpreter.  The current @code{see} tries to output Forth source code
13815: (and on some platforms, assembly code for primitives) as well as
13816: possible.
13817: 
13818: @end table
13819: 
13820: @c ---------------------------------------------------------------------
13821: @node programming-ambcond,  , programming-idef, The optional Programming-Tools word set
13822: @subsection Ambiguous conditions
13823: @c ---------------------------------------------------------------------
13824: @cindex programming-tools words, ambiguous conditions
13825: @cindex ambiguous conditions, programming-tools words
13826: 
13827: @table @i
13828: 
13829: @item deleting the compilation word list (@code{FORGET}):
13830: @cindex @code{FORGET}, deleting the compilation word list
13831: Not implemented (yet).
13832: 
13833: @item fewer than @i{u}+1 items on the control-flow stack (@code{CS-PICK}, @code{CS-ROLL}):
13834: @cindex @code{CS-PICK}, fewer than @i{u}+1 items on the control flow-stack
13835: @cindex @code{CS-ROLL}, fewer than @i{u}+1 items on the control flow-stack
13836: @cindex control-flow stack underflow
13837: This typically results in an @code{abort"} with a descriptive error
13838: message (may change into a @code{-22 throw} (Control structure mismatch)
13839: in the future). You may also get a memory access error. If you are
13840: unlucky, this ambiguous condition is not caught.
13841: 
13842: @item @i{name} can't be found (@code{FORGET}):
13843: @cindex @code{FORGET}, @i{name} can't be found
13844: Not implemented (yet).
13845: 
13846: @item @i{name} not defined via @code{CREATE}:
13847: @cindex @code{;CODE}, @i{name} not defined via @code{CREATE}
13848: @code{;CODE} behaves like @code{DOES>} in this respect, i.e., it changes
13849: the execution semantics of the last defined word no matter how it was
13850: defined.
13851: 
13852: @item @code{POSTPONE} applied to @code{[IF]}:
13853: @cindex @code{POSTPONE} applied to @code{[IF]}
13854: @cindex @code{[IF]} and @code{POSTPONE}
13855: After defining @code{: X POSTPONE [IF] ; IMMEDIATE}. @code{X} is
13856: equivalent to @code{[IF]}.
13857: 
13858: @item reaching the end of the input source before matching @code{[ELSE]} or @code{[THEN]}:
13859: @cindex @code{[IF]}, end of the input source before matching @code{[ELSE]} or @code{[THEN]}
13860: Continue in the same state of conditional compilation in the next outer
13861: input source. Currently there is no warning to the user about this.
13862: 
13863: @item removing a needed definition (@code{FORGET}):
13864: @cindex @code{FORGET}, removing a needed definition
13865: Not implemented (yet).
13866: 
13867: @end table
13868: 
13869: 
13870: @c =====================================================================
13871: @node  The optional Search-Order word set,  , The optional Programming-Tools word set, ANS conformance
13872: @section The optional Search-Order word set
13873: @c =====================================================================
13874: @cindex system documentation, search-order words
13875: @cindex search-order words, system documentation
13876: 
13877: @menu
13878: * search-idef::                 Implementation Defined Options                 
13879: * search-ambcond::              Ambiguous Conditions              
13880: @end menu
13881: 
13882: 
13883: @c ---------------------------------------------------------------------
13884: @node search-idef, search-ambcond, The optional Search-Order word set, The optional Search-Order word set
13885: @subsection Implementation Defined Options
13886: @c ---------------------------------------------------------------------
13887: @cindex implementation-defined options, search-order words
13888: @cindex search-order words, implementation-defined options
13889: 
13890: @table @i
13891: @item maximum number of word lists in search order:
13892: @cindex maximum number of word lists in search order
13893: @cindex search order, maximum depth
13894: @code{s" wordlists" environment? drop .}. Currently 16.
13895: 
13896: @item minimum search order:
13897: @cindex minimum search order
13898: @cindex search order, minimum
13899: @code{root root}.
13900: 
13901: @end table
13902: 
13903: @c ---------------------------------------------------------------------
13904: @node search-ambcond,  , search-idef, The optional Search-Order word set
13905: @subsection Ambiguous conditions
13906: @c ---------------------------------------------------------------------
13907: @cindex search-order words, ambiguous conditions
13908: @cindex ambiguous conditions, search-order words
13909: 
13910: @table @i
13911: @item changing the compilation word list (during compilation):
13912: @cindex changing the compilation word list (during compilation)
13913: @cindex compilation word list, change before definition ends
13914: The word is entered into the word list that was the compilation word list
13915: at the start of the definition. Any changes to the name field (e.g.,
13916: @code{immediate}) or the code field (e.g., when executing @code{DOES>})
13917: are applied to the latest defined word (as reported by @code{latest} or
13918: @code{latestxt}), if possible, irrespective of the compilation word list.
13919: 
13920: @item search order empty (@code{previous}):
13921: @cindex @code{previous}, search order empty
13922: @cindex vocstack empty, @code{previous}
13923: @code{abort" Vocstack empty"}.
13924: 
13925: @item too many word lists in search order (@code{also}):
13926: @cindex @code{also}, too many word lists in search order
13927: @cindex vocstack full, @code{also}
13928: @code{abort" Vocstack full"}.
13929: 
13930: @end table
13931: 
13932: @c ***************************************************************
13933: @node Standard vs Extensions, Model, ANS conformance, Top
13934: @chapter Should I use Gforth extensions?
13935: @cindex Gforth extensions
13936: 
13937: As you read through the rest of this manual, you will see documentation
13938: for @i{Standard} words, and documentation for some appealing Gforth
13939: @i{extensions}. You might ask yourself the question: @i{``Should I
13940: restrict myself to the standard, or should I use the extensions?''}
13941: 
13942: The answer depends on the goals you have for the program you are working
13943: on:
13944: 
13945: @itemize @bullet
13946: 
13947: @item Is it just for yourself or do you want to share it with others?
13948: 
13949: @item
13950: If you want to share it, do the others all use Gforth?
13951: 
13952: @item
13953: If it is just for yourself, do you want to restrict yourself to Gforth?
13954: 
13955: @end itemize
13956: 
13957: If restricting the program to Gforth is ok, then there is no reason not
13958: to use extensions.  It is still a good idea to keep to the standard
13959: where it is easy, in case you want to reuse these parts in another
13960: program that you want to be portable.
13961: 
13962: If you want to be able to port the program to other Forth systems, there
13963: are the following points to consider:
13964: 
13965: @itemize @bullet
13966: 
13967: @item
13968: Most Forth systems that are being maintained support the ANS Forth
13969: standard.  So if your program complies with the standard, it will be
13970: portable among many systems.
13971: 
13972: @item
13973: A number of the Gforth extensions can be implemented in ANS Forth using
13974: public-domain files provided in the @file{compat/} directory. These are
13975: mentioned in the text in passing.  There is no reason not to use these
13976: extensions, your program will still be ANS Forth compliant; just include
13977: the appropriate compat files with your program.
13978: 
13979: @item
13980: The tool @file{ans-report.fs} (@pxref{ANS Report}) makes it easy to
13981: analyse your program and determine what non-Standard words it relies
13982: upon.  However, it does not check whether you use standard words in a
13983: non-standard way.
13984: 
13985: @item
13986: Some techniques are not standardized by ANS Forth, and are hard or
13987: impossible to implement in a standard way, but can be implemented in
13988: most Forth systems easily, and usually in similar ways (e.g., accessing
13989: word headers).  Forth has a rich historical precedent for programmers
13990: taking advantage of implementation-dependent features of their tools
13991: (for example, relying on a knowledge of the dictionary
13992: structure). Sometimes these techniques are necessary to extract every
13993: last bit of performance from the hardware, sometimes they are just a
13994: programming shorthand.
13995: 
13996: @item
13997: Does using a Gforth extension save more work than the porting this part
13998: to other Forth systems (if any) will cost?
13999: 
14000: @item
14001: Is the additional functionality worth the reduction in portability and
14002: the additional porting problems?
14003: 
14004: @end itemize
14005: 
14006: In order to perform these consideratios, you need to know what's
14007: standard and what's not.  This manual generally states if something is
14008: non-standard, but the authoritative source is the
14009: @uref{http://www.taygeta.com/forth/dpans.html,standard document}.
14010: Appendix A of the Standard (@var{Rationale}) provides a valuable insight
14011: into the thought processes of the technical committee.
14012: 
14013: Note also that portability between Forth systems is not the only
14014: portability issue; there is also the issue of portability between
14015: different platforms (processor/OS combinations).
14016: 
14017: @c ***************************************************************
14018: @node Model, Integrating Gforth, Standard vs Extensions, Top
14019: @chapter Model
14020: 
14021: This chapter has yet to be written. It will contain information, on
14022: which internal structures you can rely.
14023: 
14024: @c ***************************************************************
14025: @node Integrating Gforth, Emacs and Gforth, Model, Top
14026: @chapter Integrating Gforth into C programs
14027: 
14028: This is not yet implemented.
14029: 
14030: Several people like to use Forth as scripting language for applications
14031: that are otherwise written in C, C++, or some other language.
14032: 
14033: The Forth system ATLAST provides facilities for embedding it into
14034: applications; unfortunately it has several disadvantages: most
14035: importantly, it is not based on ANS Forth, and it is apparently dead
14036: (i.e., not developed further and not supported). The facilities
14037: provided by Gforth in this area are inspired by ATLAST's facilities, so
14038: making the switch should not be hard.
14039: 
14040: We also tried to design the interface such that it can easily be
14041: implemented by other Forth systems, so that we may one day arrive at a
14042: standardized interface. Such a standard interface would allow you to
14043: replace the Forth system without having to rewrite C code.
14044: 
14045: You embed the Gforth interpreter by linking with the library
14046: @code{libgforth.a} (give the compiler the option @code{-lgforth}).  All
14047: global symbols in this library that belong to the interface, have the
14048: prefix @code{forth_}. (Global symbols that are used internally have the
14049: prefix @code{gforth_}).
14050: 
14051: You can include the declarations of Forth types and the functions and
14052: variables of the interface with @code{#include <forth.h>}.
14053: 
14054: Types.
14055: 
14056: Variables.
14057: 
14058: Data and FP Stack pointer. Area sizes.
14059: 
14060: functions.
14061: 
14062: forth_init(imagefile)
14063: forth_evaluate(string) exceptions?
14064: forth_goto(address) (or forth_execute(xt)?)
14065: forth_continue() (a corountining mechanism)
14066: 
14067: Adding primitives.
14068: 
14069: No checking.
14070: 
14071: Signals?
14072: 
14073: Accessing the Stacks
14074: 
14075: @c ******************************************************************
14076: @node Emacs and Gforth, Image Files, Integrating Gforth, Top
14077: @chapter Emacs and Gforth
14078: @cindex Emacs and Gforth
14079: 
14080: @cindex @file{gforth.el}
14081: @cindex @file{forth.el}
14082: @cindex Rydqvist, Goran
14083: @cindex Kuehling, David
14084: @cindex comment editing commands
14085: @cindex @code{\}, editing with Emacs
14086: @cindex debug tracer editing commands
14087: @cindex @code{~~}, removal with Emacs
14088: @cindex Forth mode in Emacs
14089: 
14090: Gforth comes with @file{gforth.el}, an improved version of
14091: @file{forth.el} by Goran Rydqvist (included in the TILE package). The
14092: improvements are:
14093: 
14094: @itemize @bullet
14095: @item
14096: A better handling of indentation.
14097: @item
14098: A custom hilighting engine for Forth-code.
14099: @item
14100: Comment paragraph filling (@kbd{M-q})
14101: @item
14102: Commenting (@kbd{C-x \}) and uncommenting (@kbd{C-u C-x \}) of regions
14103: @item
14104: Removal of debugging tracers (@kbd{C-x ~}, @pxref{Debugging}).
14105: @item
14106: Support of the @code{info-lookup} feature for looking up the
14107: documentation of a word.
14108: @item
14109: Support for reading and writing blocks files.
14110: @end itemize
14111: 
14112: To get a basic description of these features, enter Forth mode and
14113: type @kbd{C-h m}.
14114: 
14115: @cindex source location of error or debugging output in Emacs
14116: @cindex error output, finding the source location in Emacs
14117: @cindex debugging output, finding the source location in Emacs
14118: In addition, Gforth supports Emacs quite well: The source code locations
14119: given in error messages, debugging output (from @code{~~}) and failed
14120: assertion messages are in the right format for Emacs' compilation mode
14121: (@pxref{Compilation, , Running Compilations under Emacs, emacs, Emacs
14122: Manual}) so the source location corresponding to an error or other
14123: message is only a few keystrokes away (@kbd{C-x `} for the next error,
14124: @kbd{C-c C-c} for the error under the cursor).
14125: 
14126: @cindex viewing the documentation of a word in Emacs
14127: @cindex context-sensitive help
14128: Moreover, for words documented in this manual, you can look up the
14129: glossary entry quickly by using @kbd{C-h TAB}
14130: (@code{info-lookup-symbol}, @pxref{Documentation, ,Documentation
14131: Commands, emacs, Emacs Manual}).  This feature requires Emacs 20.3 or
14132: later and does not work for words containing @code{:}.
14133: 
14134: @menu
14135: * Installing gforth.el::        Making Emacs aware of Forth.
14136: * Emacs Tags::                  Viewing the source of a word in Emacs.
14137: * Hilighting::                  Making Forth code look prettier.
14138: * Auto-Indentation::            Customizing auto-indentation.
14139: * Blocks Files::                Reading and writing blocks files.
14140: @end menu
14141: 
14142: @c ----------------------------------
14143: @node Installing gforth.el, Emacs Tags, Emacs and Gforth, Emacs and Gforth
14144: @section Installing gforth.el
14145: @cindex @file{.emacs}
14146: @cindex @file{gforth.el}, installation
14147: To make the features from @file{gforth.el} available in Emacs, add
14148: the following lines to your @file{.emacs} file:
14149: 
14150: @example
14151: (autoload 'forth-mode "gforth.el")
14152: (setq auto-mode-alist (cons '("\\.fs\\'" . forth-mode) 
14153: 			    auto-mode-alist))
14154: (autoload 'forth-block-mode "gforth.el")
14155: (setq auto-mode-alist (cons '("\\.fb\\'" . forth-block-mode) 
14156: 			    auto-mode-alist))
14157: (add-hook 'forth-mode-hook (function (lambda ()
14158:    ;; customize variables here:
14159:    (setq forth-indent-level 4)
14160:    (setq forth-minor-indent-level 2)
14161:    (setq forth-hilight-level 3)
14162:    ;;; ...
14163: )))
14164: @end example
14165: 
14166: @c ----------------------------------
14167: @node Emacs Tags, Hilighting, Installing gforth.el, Emacs and Gforth
14168: @section Emacs Tags
14169: @cindex @file{TAGS} file
14170: @cindex @file{etags.fs}
14171: @cindex viewing the source of a word in Emacs
14172: @cindex @code{require}, placement in files
14173: @cindex @code{include}, placement in files
14174: If you @code{require} @file{etags.fs}, a new @file{TAGS} file will be
14175: produced (@pxref{Tags, , Tags Tables, emacs, Emacs Manual}) that
14176: contains the definitions of all words defined afterwards. You can then
14177: find the source for a word using @kbd{M-.}. Note that Emacs can use
14178: several tags files at the same time (e.g., one for the Gforth sources
14179: and one for your program, @pxref{Select Tags Table,,Selecting a Tags
14180: Table,emacs, Emacs Manual}). The TAGS file for the preloaded words is
14181: @file{$(datadir)/gforth/$(VERSION)/TAGS} (e.g.,
14182: @file{/usr/local/share/gforth/0.2.0/TAGS}).  To get the best behaviour
14183: with @file{etags.fs}, you should avoid putting definitions both before
14184: and after @code{require} etc., otherwise you will see the same file
14185: visited several times by commands like @code{tags-search}.
14186: 
14187: @c ----------------------------------
14188: @node Hilighting, Auto-Indentation, Emacs Tags, Emacs and Gforth
14189: @section Hilighting
14190: @cindex hilighting Forth code in Emacs
14191: @cindex highlighting Forth code in Emacs
14192: @file{gforth.el} comes with a custom source hilighting engine.  When
14193: you open a file in @code{forth-mode}, it will be completely parsed,
14194: assigning faces to keywords, comments, strings etc.  While you edit
14195: the file, modified regions get parsed and updated on-the-fly. 
14196: 
14197: Use the variable `forth-hilight-level' to change the level of
14198: decoration from 0 (no hilighting at all) to 3 (the default).  Even if
14199: you set the hilighting level to 0, the parser will still work in the
14200: background, collecting information about whether regions of text are
14201: ``compiled'' or ``interpreted''.  Those information are required for
14202: auto-indentation to work properly.  Set `forth-disable-parser' to
14203: non-nil if your computer is too slow to handle parsing.  This will
14204: have an impact on the smartness of the auto-indentation engine,
14205: though.
14206: 
14207: Sometimes Forth sources define new features that should be hilighted,
14208: new control structures, defining-words etc.  You can use the variable
14209: `forth-custom-words' to make @code{forth-mode} hilight additional
14210: words and constructs.  See the docstring of `forth-words' for details
14211: (in Emacs, type @kbd{C-h v forth-words}).
14212: 
14213: `forth-custom-words' is meant to be customized in your
14214: @file{.emacs} file.  To customize hilighing in a file-specific manner,
14215: set `forth-local-words' in a local-variables section at the end of
14216: your source file (@pxref{Local Variables in Files,, Variables, emacs, Emacs Manual}).
14217: 
14218: Example:
14219: @example
14220: 0 [IF]
14221:    Local Variables:
14222:    forth-local-words:
14223:       ((("t:") definition-starter (font-lock-keyword-face . 1)
14224:         "[ \t\n]" t name (font-lock-function-name-face . 3))
14225:        ((";t") definition-ender (font-lock-keyword-face . 1)))
14226:    End:
14227: [THEN]
14228: @end example
14229: 
14230: @c ----------------------------------
14231: @node Auto-Indentation, Blocks Files, Hilighting, Emacs and Gforth
14232: @section Auto-Indentation
14233: @cindex auto-indentation of Forth code in Emacs
14234: @cindex indentation of Forth code in Emacs
14235: @code{forth-mode} automatically tries to indent lines in a smart way,
14236: whenever you type @key{TAB} or break a line with @kbd{C-m}.
14237: 
14238: Simple customization can be achieved by setting
14239: `forth-indent-level' and `forth-minor-indent-level' in your
14240: @file{.emacs} file. For historical reasons @file{gforth.el} indents
14241: per default by multiples of 4 columns.  To use the more traditional
14242: 3-column indentation, add the following lines to your @file{.emacs}:
14243: 
14244: @example
14245: (add-hook 'forth-mode-hook (function (lambda ()
14246:    ;; customize variables here:
14247:    (setq forth-indent-level 3)
14248:    (setq forth-minor-indent-level 1)
14249: )))
14250: @end example
14251: 
14252: If you want indentation to recognize non-default words, customize it
14253: by setting `forth-custom-indent-words' in your @file{.emacs}.  See the
14254: docstring of `forth-indent-words' for details (in Emacs, type @kbd{C-h
14255: v forth-indent-words}).
14256: 
14257: To customize indentation in a file-specific manner, set
14258: `forth-local-indent-words' in a local-variables section at the end of
14259: your source file (@pxref{Local Variables in Files, Variables,,emacs,
14260: Emacs Manual}).
14261: 
14262: Example:
14263: @example
14264: 0 [IF]
14265:    Local Variables:
14266:    forth-local-indent-words:
14267:       ((("t:") (0 . 2) (0 . 2))
14268:        ((";t") (-2 . 0) (0 . -2)))
14269:    End:
14270: [THEN]
14271: @end example
14272: 
14273: @c ----------------------------------
14274: @node Blocks Files,  , Auto-Indentation, Emacs and Gforth
14275: @section Blocks Files
14276: @cindex blocks files, use with Emacs
14277: @code{forth-mode} Autodetects blocks files by checking whether the
14278: length of the first line exceeds 1023 characters.  It then tries to
14279: convert the file into normal text format.  When you save the file, it
14280: will be written to disk as normal stream-source file.
14281: 
14282: If you want to write blocks files, use @code{forth-blocks-mode}.  It
14283: inherits all the features from @code{forth-mode}, plus some additions:
14284: 
14285: @itemize @bullet
14286: @item
14287: Files are written to disk in blocks file format.
14288: @item
14289: Screen numbers are displayed in the mode line (enumerated beginning
14290: with the value of `forth-block-base')
14291: @item
14292: Warnings are displayed when lines exceed 64 characters.
14293: @item
14294: The beginning of the currently edited block is marked with an
14295: overlay-arrow. 
14296: @end itemize
14297: 
14298: There are some restrictions you should be aware of.  When you open a
14299: blocks file that contains tabulator or newline characters, these
14300: characters will be translated into spaces when the file is written
14301: back to disk.  If tabs or newlines are encountered during blocks file
14302: reading, an error is output to the echo area. So have a look at the
14303: `*Messages*' buffer, when Emacs' bell rings during reading.
14304: 
14305: Please consult the docstring of @code{forth-blocks-mode} for more
14306: information by typing @kbd{C-h v forth-blocks-mode}).
14307: 
14308: @c ******************************************************************
14309: @node Image Files, Engine, Emacs and Gforth, Top
14310: @chapter Image Files
14311: @cindex image file
14312: @cindex @file{.fi} files
14313: @cindex precompiled Forth code
14314: @cindex dictionary in persistent form
14315: @cindex persistent form of dictionary
14316: 
14317: An image file is a file containing an image of the Forth dictionary,
14318: i.e., compiled Forth code and data residing in the dictionary.  By
14319: convention, we use the extension @code{.fi} for image files.
14320: 
14321: @menu
14322: * Image Licensing Issues::      Distribution terms for images.
14323: * Image File Background::       Why have image files?
14324: * Non-Relocatable Image Files::  don't always work.
14325: * Data-Relocatable Image Files::  are better.
14326: * Fully Relocatable Image Files::  better yet.
14327: * Stack and Dictionary Sizes::  Setting the default sizes for an image.
14328: * Running Image Files::         @code{gforth -i @i{file}} or @i{file}.
14329: * Modifying the Startup Sequence::  and turnkey applications.
14330: @end menu
14331: 
14332: @node Image Licensing Issues, Image File Background, Image Files, Image Files
14333: @section Image Licensing Issues
14334: @cindex license for images
14335: @cindex image license
14336: 
14337: An image created with @code{gforthmi} (@pxref{gforthmi}) or
14338: @code{savesystem} (@pxref{Non-Relocatable Image Files}) includes the
14339: original image; i.e., according to copyright law it is a derived work of
14340: the original image.
14341: 
14342: Since Gforth is distributed under the GNU GPL, the newly created image
14343: falls under the GNU GPL, too. In particular, this means that if you
14344: distribute the image, you have to make all of the sources for the image
14345: available, including those you wrote.  For details see @ref{Copying, ,
14346: GNU General Public License (Section 3)}.
14347: 
14348: If you create an image with @code{cross} (@pxref{cross.fs}), the image
14349: contains only code compiled from the sources you gave it; if none of
14350: these sources is under the GPL, the terms discussed above do not apply
14351: to the image. However, if your image needs an engine (a gforth binary)
14352: that is under the GPL, you should make sure that you distribute both in
14353: a way that is at most a @emph{mere aggregation}, if you don't want the
14354: terms of the GPL to apply to the image.
14355: 
14356: @node Image File Background, Non-Relocatable Image Files, Image Licensing Issues, Image Files
14357: @section Image File Background
14358: @cindex image file background
14359: 
14360: Gforth consists not only of primitives (in the engine), but also of
14361: definitions written in Forth. Since the Forth compiler itself belongs to
14362: those definitions, it is not possible to start the system with the
14363: engine and the Forth source alone. Therefore we provide the Forth
14364: code as an image file in nearly executable form. When Gforth starts up,
14365: a C routine loads the image file into memory, optionally relocates the
14366: addresses, then sets up the memory (stacks etc.) according to
14367: information in the image file, and (finally) starts executing Forth
14368: code.
14369: 
14370: The image file variants represent different compromises between the
14371: goals of making it easy to generate image files and making them
14372: portable.
14373: 
14374: @cindex relocation at run-time
14375: Win32Forth 3.4 and Mitch Bradley's @code{cforth} use relocation at
14376: run-time. This avoids many of the complications discussed below (image
14377: files are data relocatable without further ado), but costs performance
14378: (one addition per memory access).
14379: 
14380: @cindex relocation at load-time
14381: By contrast, the Gforth loader performs relocation at image load time. The
14382: loader also has to replace tokens that represent primitive calls with the
14383: appropriate code-field addresses (or code addresses in the case of
14384: direct threading).
14385: 
14386: There are three kinds of image files, with different degrees of
14387: relocatability: non-relocatable, data-relocatable, and fully relocatable
14388: image files.
14389: 
14390: @cindex image file loader
14391: @cindex relocating loader
14392: @cindex loader for image files
14393: These image file variants have several restrictions in common; they are
14394: caused by the design of the image file loader:
14395: 
14396: @itemize @bullet
14397: @item
14398: There is only one segment; in particular, this means, that an image file
14399: cannot represent @code{ALLOCATE}d memory chunks (and pointers to
14400: them). The contents of the stacks are not represented, either.
14401: 
14402: @item
14403: The only kinds of relocation supported are: adding the same offset to
14404: all cells that represent data addresses; and replacing special tokens
14405: with code addresses or with pieces of machine code.
14406: 
14407: If any complex computations involving addresses are performed, the
14408: results cannot be represented in the image file. Several applications that
14409: use such computations come to mind:
14410: @itemize @minus
14411: @item
14412: Hashing addresses (or data structures which contain addresses) for table
14413: lookup. If you use Gforth's @code{table}s or @code{wordlist}s for this
14414: purpose, you will have no problem, because the hash tables are
14415: recomputed automatically when the system is started. If you use your own
14416: hash tables, you will have to do something similar.
14417: 
14418: @item
14419: There's a cute implementation of doubly-linked lists that uses
14420: @code{XOR}ed addresses. You could represent such lists as singly-linked
14421: in the image file, and restore the doubly-linked representation on
14422: startup.@footnote{In my opinion, though, you should think thrice before
14423: using a doubly-linked list (whatever implementation).}
14424: 
14425: @item
14426: The code addresses of run-time routines like @code{docol:} cannot be
14427: represented in the image file (because their tokens would be replaced by
14428: machine code in direct threaded implementations). As a workaround,
14429: compute these addresses at run-time with @code{>code-address} from the
14430: executions tokens of appropriate words (see the definitions of
14431: @code{docol:} and friends in @file{kernel/getdoers.fs}).
14432: 
14433: @item
14434: On many architectures addresses are represented in machine code in some
14435: shifted or mangled form. You cannot put @code{CODE} words that contain
14436: absolute addresses in this form in a relocatable image file. Workarounds
14437: are representing the address in some relative form (e.g., relative to
14438: the CFA, which is present in some register), or loading the address from
14439: a place where it is stored in a non-mangled form.
14440: @end itemize
14441: @end itemize
14442: 
14443: @node  Non-Relocatable Image Files, Data-Relocatable Image Files, Image File Background, Image Files
14444: @section Non-Relocatable Image Files
14445: @cindex non-relocatable image files
14446: @cindex image file, non-relocatable
14447: 
14448: These files are simple memory dumps of the dictionary. They are specific
14449: to the executable (i.e., @file{gforth} file) they were created
14450: with. What's worse, they are specific to the place on which the
14451: dictionary resided when the image was created. Now, there is no
14452: guarantee that the dictionary will reside at the same place the next
14453: time you start Gforth, so there's no guarantee that a non-relocatable
14454: image will work the next time (Gforth will complain instead of crashing,
14455: though).
14456: 
14457: You can create a non-relocatable image file with
14458: 
14459: 
14460: doc-savesystem
14461: 
14462: 
14463: @node Data-Relocatable Image Files, Fully Relocatable Image Files, Non-Relocatable Image Files, Image Files
14464: @section Data-Relocatable Image Files
14465: @cindex data-relocatable image files
14466: @cindex image file, data-relocatable
14467: 
14468: These files contain relocatable data addresses, but fixed code addresses
14469: (instead of tokens). They are specific to the executable (i.e.,
14470: @file{gforth} file) they were created with. For direct threading on some
14471: architectures (e.g., the i386), data-relocatable images do not work. You
14472: get a data-relocatable image, if you use @file{gforthmi} with a
14473: Gforth binary that is not doubly indirect threaded (@pxref{Fully
14474: Relocatable Image Files}).
14475: 
14476: @node Fully Relocatable Image Files, Stack and Dictionary Sizes, Data-Relocatable Image Files, Image Files
14477: @section Fully Relocatable Image Files
14478: @cindex fully relocatable image files
14479: @cindex image file, fully relocatable
14480: 
14481: @cindex @file{kern*.fi}, relocatability
14482: @cindex @file{gforth.fi}, relocatability
14483: These image files have relocatable data addresses, and tokens for code
14484: addresses. They can be used with different binaries (e.g., with and
14485: without debugging) on the same machine, and even across machines with
14486: the same data formats (byte order, cell size, floating point
14487: format). However, they are usually specific to the version of Gforth
14488: they were created with. The files @file{gforth.fi} and @file{kernl*.fi}
14489: are fully relocatable.
14490: 
14491: There are two ways to create a fully relocatable image file:
14492: 
14493: @menu
14494: * gforthmi::                    The normal way
14495: * cross.fs::                    The hard way
14496: @end menu
14497: 
14498: @node gforthmi, cross.fs, Fully Relocatable Image Files, Fully Relocatable Image Files
14499: @subsection @file{gforthmi}
14500: @cindex @file{comp-i.fs}
14501: @cindex @file{gforthmi}
14502: 
14503: You will usually use @file{gforthmi}. If you want to create an
14504: image @i{file} that contains everything you would load by invoking
14505: Gforth with @code{gforth @i{options}}, you simply say:
14506: @example
14507: gforthmi @i{file} @i{options}
14508: @end example
14509: 
14510: E.g., if you want to create an image @file{asm.fi} that has the file
14511: @file{asm.fs} loaded in addition to the usual stuff, you could do it
14512: like this:
14513: 
14514: @example
14515: gforthmi asm.fi asm.fs
14516: @end example
14517: 
14518: @file{gforthmi} is implemented as a sh script and works like this: It
14519: produces two non-relocatable images for different addresses and then
14520: compares them. Its output reflects this: first you see the output (if
14521: any) of the two Gforth invocations that produce the non-relocatable image
14522: files, then you see the output of the comparing program: It displays the
14523: offset used for data addresses and the offset used for code addresses;
14524: moreover, for each cell that cannot be represented correctly in the
14525: image files, it displays a line like this:
14526: 
14527: @example
14528:      78DC         BFFFFA50         BFFFFA40
14529: @end example
14530: 
14531: This means that at offset $78dc from @code{forthstart}, one input image
14532: contains $bffffa50, and the other contains $bffffa40. Since these cells
14533: cannot be represented correctly in the output image, you should examine
14534: these places in the dictionary and verify that these cells are dead
14535: (i.e., not read before they are written).
14536: 
14537: @cindex --application, @code{gforthmi} option
14538: If you insert the option @code{--application} in front of the image file
14539: name, you will get an image that uses the @code{--appl-image} option
14540: instead of the @code{--image-file} option (@pxref{Invoking
14541: Gforth}). When you execute such an image on Unix (by typing the image
14542: name as command), the Gforth engine will pass all options to the image
14543: instead of trying to interpret them as engine options.
14544: 
14545: If you type @file{gforthmi} with no arguments, it prints some usage
14546: instructions.
14547: 
14548: @cindex @code{savesystem} during @file{gforthmi}
14549: @cindex @code{bye} during @file{gforthmi}
14550: @cindex doubly indirect threaded code
14551: @cindex environment variables
14552: @cindex @code{GFORTHD} -- environment variable
14553: @cindex @code{GFORTH} -- environment variable
14554: @cindex @code{gforth-ditc}
14555: There are a few wrinkles: After processing the passed @i{options}, the
14556: words @code{savesystem} and @code{bye} must be visible. A special doubly
14557: indirect threaded version of the @file{gforth} executable is used for
14558: creating the non-relocatable images; you can pass the exact filename of
14559: this executable through the environment variable @code{GFORTHD}
14560: (default: @file{gforth-ditc}); if you pass a version that is not doubly
14561: indirect threaded, you will not get a fully relocatable image, but a
14562: data-relocatable image (because there is no code address offset). The
14563: normal @file{gforth} executable is used for creating the relocatable
14564: image; you can pass the exact filename of this executable through the
14565: environment variable @code{GFORTH}.
14566: 
14567: @node cross.fs,  , gforthmi, Fully Relocatable Image Files
14568: @subsection @file{cross.fs}
14569: @cindex @file{cross.fs}
14570: @cindex cross-compiler
14571: @cindex metacompiler
14572: @cindex target compiler
14573: 
14574: You can also use @code{cross}, a batch compiler that accepts a Forth-like
14575: programming language (@pxref{Cross Compiler}).
14576: 
14577: @code{cross} allows you to create image files for machines with
14578: different data sizes and data formats than the one used for generating
14579: the image file. You can also use it to create an application image that
14580: does not contain a Forth compiler. These features are bought with
14581: restrictions and inconveniences in programming. E.g., addresses have to
14582: be stored in memory with special words (@code{A!}, @code{A,}, etc.) in
14583: order to make the code relocatable.
14584: 
14585: 
14586: @node Stack and Dictionary Sizes, Running Image Files, Fully Relocatable Image Files, Image Files
14587: @section Stack and Dictionary Sizes
14588: @cindex image file, stack and dictionary sizes
14589: @cindex dictionary size default
14590: @cindex stack size default
14591: 
14592: If you invoke Gforth with a command line flag for the size
14593: (@pxref{Invoking Gforth}), the size you specify is stored in the
14594: dictionary. If you save the dictionary with @code{savesystem} or create
14595: an image with @file{gforthmi}, this size will become the default
14596: for the resulting image file. E.g., the following will create a
14597: fully relocatable version of @file{gforth.fi} with a 1MB dictionary:
14598: 
14599: @example
14600: gforthmi gforth.fi -m 1M
14601: @end example
14602: 
14603: In other words, if you want to set the default size for the dictionary
14604: and the stacks of an image, just invoke @file{gforthmi} with the
14605: appropriate options when creating the image.
14606: 
14607: @cindex stack size, cache-friendly
14608: Note: For cache-friendly behaviour (i.e., good performance), you should
14609: make the sizes of the stacks modulo, say, 2K, somewhat different. E.g.,
14610: the default stack sizes are: data: 16k (mod 2k=0); fp: 15.5k (mod
14611: 2k=1.5k); return: 15k(mod 2k=1k); locals: 14.5k (mod 2k=0.5k).
14612: 
14613: @node Running Image Files, Modifying the Startup Sequence, Stack and Dictionary Sizes, Image Files
14614: @section Running Image Files
14615: @cindex running image files
14616: @cindex invoking image files
14617: @cindex image file invocation
14618: 
14619: @cindex -i, invoke image file
14620: @cindex --image file, invoke image file
14621: You can invoke Gforth with an image file @i{image} instead of the
14622: default @file{gforth.fi} with the @code{-i} flag (@pxref{Invoking Gforth}):
14623: @example
14624: gforth -i @i{image}
14625: @end example
14626: 
14627: @cindex executable image file
14628: @cindex image file, executable
14629: If your operating system supports starting scripts with a line of the
14630: form @code{#! ...}, you just have to type the image file name to start
14631: Gforth with this image file (note that the file extension @code{.fi} is
14632: just a convention). I.e., to run Gforth with the image file @i{image},
14633: you can just type @i{image} instead of @code{gforth -i @i{image}}.
14634: This works because every @code{.fi} file starts with a line of this
14635: format:
14636: 
14637: @example
14638: #! /usr/local/bin/gforth-0.4.0 -i
14639: @end example
14640: 
14641: The file and pathname for the Gforth engine specified on this line is
14642: the specific Gforth executable that it was built against; i.e. the value
14643: of the environment variable @code{GFORTH} at the time that
14644: @file{gforthmi} was executed.
14645: 
14646: You can make use of the same shell capability to make a Forth source
14647: file into an executable. For example, if you place this text in a file:
14648: 
14649: @example
14650: #! /usr/local/bin/gforth
14651: 
14652: ." Hello, world" CR
14653: bye
14654: @end example
14655: 
14656: @noindent
14657: and then make the file executable (chmod +x in Unix), you can run it
14658: directly from the command line. The sequence @code{#!} is used in two
14659: ways; firstly, it is recognised as a ``magic sequence'' by the operating
14660: system@footnote{The Unix kernel actually recognises two types of files:
14661: executable files and files of data, where the data is processed by an
14662: interpreter that is specified on the ``interpreter line'' -- the first
14663: line of the file, starting with the sequence #!. There may be a small
14664: limit (e.g., 32) on the number of characters that may be specified on
14665: the interpreter line.} secondly it is treated as a comment character by
14666: Gforth. Because of the second usage, a space is required between
14667: @code{#!} and the path to the executable (moreover, some Unixes
14668: require the sequence @code{#! /}).
14669: 
14670: The disadvantage of this latter technique, compared with using
14671: @file{gforthmi}, is that it is slightly slower; the Forth source code is
14672: compiled on-the-fly, each time the program is invoked.
14673: 
14674: doc-#!
14675: 
14676: 
14677: @node Modifying the Startup Sequence,  , Running Image Files, Image Files
14678: @section Modifying the Startup Sequence
14679: @cindex startup sequence for image file
14680: @cindex image file initialization sequence
14681: @cindex initialization sequence of image file
14682: 
14683: You can add your own initialization to the startup sequence of an image
14684: through the deferred word @code{'cold}. @code{'cold} is invoked just
14685: before the image-specific command line processing (i.e., loading files
14686: and evaluating (@code{-e}) strings) starts.
14687: 
14688: A sequence for adding your initialization usually looks like this:
14689: 
14690: @example
14691: :noname
14692:     Defers 'cold \ do other initialization stuff (e.g., rehashing wordlists)
14693:     ... \ your stuff
14694: ; IS 'cold
14695: @end example
14696: 
14697: After @code{'cold}, Gforth processes the image options
14698: (@pxref{Invoking Gforth}), and then it performs @code{bootmessage},
14699: another deferred word.  This normally prints Gforth's startup message
14700: and does nothing else.
14701: 
14702: @cindex turnkey image files
14703: @cindex image file, turnkey applications
14704: So, if you want to make a turnkey image (i.e., an image for an
14705: application instead of an extended Forth system), you can do this in
14706: two ways:
14707: 
14708: @itemize @bullet
14709: 
14710: @item
14711: If you want to do your interpretation of the OS command-line
14712: arguments, hook into @code{'cold}.  In that case you probably also
14713: want to build the image with @code{gforthmi --application}
14714: (@pxref{gforthmi}) to keep the engine from processing OS command line
14715: options.  You can then do your own command-line processing with
14716: @code{next-arg} 
14717: 
14718: @item
14719: If you want to have the normal Gforth processing of OS command-line
14720: arguments, hook into @code{bootmessage}.
14721: 
14722: @end itemize
14723: 
14724: In either case, you probably do not want the word that you execute in
14725: these hooks to exit normally, but use @code{bye} or @code{throw}.
14726: Otherwise the Gforth startup process would continue and eventually
14727: present the Forth command line to the user.
14728: 
14729: doc-'cold
14730: doc-bootmessage
14731: 
14732: @c ******************************************************************
14733: @node Engine, Cross Compiler, Image Files, Top
14734: @chapter Engine
14735: @cindex engine
14736: @cindex virtual machine
14737: 
14738: Reading this chapter is not necessary for programming with Gforth. It
14739: may be helpful for finding your way in the Gforth sources.
14740: 
14741: The ideas in this section have also been published in the following
14742: papers: Bernd Paysan, @cite{ANS fig/GNU/??? Forth} (in German),
14743: Forth-Tagung '93; M. Anton Ertl,
14744: @cite{@uref{http://www.complang.tuwien.ac.at/papers/ertl93.ps.Z, A
14745: Portable Forth Engine}}, EuroForth '93; M. Anton Ertl,
14746: @cite{@uref{http://www.complang.tuwien.ac.at/papers/ertl02.ps.gz,
14747: Threaded code variations and optimizations (extended version)}},
14748: Forth-Tagung '02.
14749: 
14750: @menu
14751: * Portability::                 
14752: * Threading::                   
14753: * Primitives::                  
14754: * Performance::                 
14755: @end menu
14756: 
14757: @node Portability, Threading, Engine, Engine
14758: @section Portability
14759: @cindex engine portability
14760: 
14761: An important goal of the Gforth Project is availability across a wide
14762: range of personal machines. fig-Forth, and, to a lesser extent, F83,
14763: achieved this goal by manually coding the engine in assembly language
14764: for several then-popular processors. This approach is very
14765: labor-intensive and the results are short-lived due to progress in
14766: computer architecture.
14767: 
14768: @cindex C, using C for the engine
14769: Others have avoided this problem by coding in C, e.g., Mitch Bradley
14770: (cforth), Mikael Patel (TILE) and Dirk Zoller (pfe). This approach is
14771: particularly popular for UNIX-based Forths due to the large variety of
14772: architectures of UNIX machines. Unfortunately an implementation in C
14773: does not mix well with the goals of efficiency and with using
14774: traditional techniques: Indirect or direct threading cannot be expressed
14775: in C, and switch threading, the fastest technique available in C, is
14776: significantly slower. Another problem with C is that it is very
14777: cumbersome to express double integer arithmetic.
14778: 
14779: @cindex GNU C for the engine
14780: @cindex long long
14781: Fortunately, there is a portable language that does not have these
14782: limitations: GNU C, the version of C processed by the GNU C compiler
14783: (@pxref{C Extensions, , Extensions to the C Language Family, gcc.info,
14784: GNU C Manual}). Its labels as values feature (@pxref{Labels as Values, ,
14785: Labels as Values, gcc.info, GNU C Manual}) makes direct and indirect
14786: threading possible, its @code{long long} type (@pxref{Long Long, ,
14787: Double-Word Integers, gcc.info, GNU C Manual}) corresponds to Forth's
14788: double numbers on many systems.  GNU C is freely available on all
14789: important (and many unimportant) UNIX machines, VMS, 80386s running
14790: MS-DOS, the Amiga, and the Atari ST, so a Forth written in GNU C can run
14791: on all these machines.
14792: 
14793: Writing in a portable language has the reputation of producing code that
14794: is slower than assembly. For our Forth engine we repeatedly looked at
14795: the code produced by the compiler and eliminated most compiler-induced
14796: inefficiencies by appropriate changes in the source code.
14797: 
14798: @cindex explicit register declarations
14799: @cindex --enable-force-reg, configuration flag
14800: @cindex -DFORCE_REG
14801: However, register allocation cannot be portably influenced by the
14802: programmer, leading to some inefficiencies on register-starved
14803: machines. We use explicit register declarations (@pxref{Explicit Reg
14804: Vars, , Variables in Specified Registers, gcc.info, GNU C Manual}) to
14805: improve the speed on some machines. They are turned on by using the
14806: configuration flag @code{--enable-force-reg} (@code{gcc} switch
14807: @code{-DFORCE_REG}). Unfortunately, this feature not only depends on the
14808: machine, but also on the compiler version: On some machines some
14809: compiler versions produce incorrect code when certain explicit register
14810: declarations are used. So by default @code{-DFORCE_REG} is not used.
14811: 
14812: @node Threading, Primitives, Portability, Engine
14813: @section Threading
14814: @cindex inner interpreter implementation
14815: @cindex threaded code implementation
14816: 
14817: @cindex labels as values
14818: GNU C's labels as values extension (available since @code{gcc-2.0},
14819: @pxref{Labels as Values, , Labels as Values, gcc.info, GNU C Manual})
14820: makes it possible to take the address of @i{label} by writing
14821: @code{&&@i{label}}.  This address can then be used in a statement like
14822: @code{goto *@i{address}}. I.e., @code{goto *&&x} is the same as
14823: @code{goto x}.
14824: 
14825: @cindex @code{NEXT}, indirect threaded
14826: @cindex indirect threaded inner interpreter
14827: @cindex inner interpreter, indirect threaded
14828: With this feature an indirect threaded @code{NEXT} looks like:
14829: @example
14830: cfa = *ip++;
14831: ca = *cfa;
14832: goto *ca;
14833: @end example
14834: @cindex instruction pointer
14835: For those unfamiliar with the names: @code{ip} is the Forth instruction
14836: pointer; the @code{cfa} (code-field address) corresponds to ANS Forths
14837: execution token and points to the code field of the next word to be
14838: executed; The @code{ca} (code address) fetched from there points to some
14839: executable code, e.g., a primitive or the colon definition handler
14840: @code{docol}.
14841: 
14842: @cindex @code{NEXT}, direct threaded
14843: @cindex direct threaded inner interpreter
14844: @cindex inner interpreter, direct threaded
14845: Direct threading is even simpler:
14846: @example
14847: ca = *ip++;
14848: goto *ca;
14849: @end example
14850: 
14851: Of course we have packaged the whole thing neatly in macros called
14852: @code{NEXT} and @code{NEXT1} (the part of @code{NEXT} after fetching the cfa).
14853: 
14854: @menu
14855: * Scheduling::                  
14856: * Direct or Indirect Threaded?::  
14857: * Dynamic Superinstructions::   
14858: * DOES>::                       
14859: @end menu
14860: 
14861: @node Scheduling, Direct or Indirect Threaded?, Threading, Threading
14862: @subsection Scheduling
14863: @cindex inner interpreter optimization
14864: 
14865: There is a little complication: Pipelined and superscalar processors,
14866: i.e., RISC and some modern CISC machines can process independent
14867: instructions while waiting for the results of an instruction. The
14868: compiler usually reorders (schedules) the instructions in a way that
14869: achieves good usage of these delay slots. However, on our first tries
14870: the compiler did not do well on scheduling primitives. E.g., for
14871: @code{+} implemented as
14872: @example
14873: n=sp[0]+sp[1];
14874: sp++;
14875: sp[0]=n;
14876: NEXT;
14877: @end example
14878: the @code{NEXT} comes strictly after the other code, i.e., there is
14879: nearly no scheduling. After a little thought the problem becomes clear:
14880: The compiler cannot know that @code{sp} and @code{ip} point to different
14881: addresses (and the version of @code{gcc} we used would not know it even
14882: if it was possible), so it could not move the load of the cfa above the
14883: store to the TOS. Indeed the pointers could be the same, if code on or
14884: very near the top of stack were executed. In the interest of speed we
14885: chose to forbid this probably unused ``feature'' and helped the compiler
14886: in scheduling: @code{NEXT} is divided into several parts:
14887: @code{NEXT_P0}, @code{NEXT_P1} and @code{NEXT_P2}). @code{+} now looks
14888: like:
14889: @example
14890: NEXT_P0;
14891: n=sp[0]+sp[1];
14892: sp++;
14893: NEXT_P1;
14894: sp[0]=n;
14895: NEXT_P2;
14896: @end example
14897: 
14898: There are various schemes that distribute the different operations of
14899: NEXT between these parts in several ways; in general, different schemes
14900: perform best on different processors.  We use a scheme for most
14901: architectures that performs well for most processors of this
14902: architecture; in the future we may switch to benchmarking and chosing
14903: the scheme on installation time.
14904: 
14905: 
14906: @node Direct or Indirect Threaded?, Dynamic Superinstructions, Scheduling, Threading
14907: @subsection Direct or Indirect Threaded?
14908: @cindex threading, direct or indirect?
14909: 
14910: Threaded forth code consists of references to primitives (simple machine
14911: code routines like @code{+}) and to non-primitives (e.g., colon
14912: definitions, variables, constants); for a specific class of
14913: non-primitives (e.g., variables) there is one code routine (e.g.,
14914: @code{dovar}), but each variable needs a separate reference to its data.
14915: 
14916: Traditionally Forth has been implemented as indirect threaded code,
14917: because this allows to use only one cell to reference a non-primitive
14918: (basically you point to the data, and find the code address there).
14919: 
14920: @cindex primitive-centric threaded code
14921: However, threaded code in Gforth (since 0.6.0) uses two cells for
14922: non-primitives, one for the code address, and one for the data address;
14923: the data pointer is an immediate argument for the virtual machine
14924: instruction represented by the code address.  We call this
14925: @emph{primitive-centric} threaded code, because all code addresses point
14926: to simple primitives.  E.g., for a variable, the code address is for
14927: @code{lit} (also used for integer literals like @code{99}).
14928: 
14929: Primitive-centric threaded code allows us to use (faster) direct
14930: threading as dispatch method, completely portably (direct threaded code
14931: in Gforth before 0.6.0 required architecture-specific code).  It also
14932: eliminates the performance problems related to I-cache consistency that
14933: 386 implementations have with direct threaded code, and allows
14934: additional optimizations.
14935: 
14936: @cindex hybrid direct/indirect threaded code
14937: There is a catch, however: the @var{xt} parameter of @code{execute} can
14938: occupy only one cell, so how do we pass non-primitives with their code
14939: @emph{and} data addresses to them?  Our answer is to use indirect
14940: threaded dispatch for @code{execute} and other words that use a
14941: single-cell xt.  So, normal threaded code in colon definitions uses
14942: direct threading, and @code{execute} and similar words, which dispatch
14943: to xts on the data stack, use indirect threaded code.  We call this
14944: @emph{hybrid direct/indirect} threaded code.
14945: 
14946: @cindex engines, gforth vs. gforth-fast vs. gforth-itc
14947: @cindex gforth engine
14948: @cindex gforth-fast engine
14949: The engines @command{gforth} and @command{gforth-fast} use hybrid
14950: direct/indirect threaded code.  This means that with these engines you
14951: cannot use @code{,} to compile an xt.  Instead, you have to use
14952: @code{compile,}.
14953: 
14954: @cindex gforth-itc engine
14955: If you want to compile xts with @code{,}, use @command{gforth-itc}.
14956: This engine uses plain old indirect threaded code.  It still compiles in
14957: a primitive-centric style, so you cannot use @code{compile,} instead of
14958: @code{,} (e.g., for producing tables of xts with @code{] word1 word2
14959: ... [}).  If you want to do that, you have to use @command{gforth-itc}
14960: and execute @code{' , is compile,}.  Your program can check if it is
14961: running on a hybrid direct/indirect threaded engine or a pure indirect
14962: threaded engine with @code{threading-method} (@pxref{Threading Words}).
14963: 
14964: 
14965: @node Dynamic Superinstructions, DOES>, Direct or Indirect Threaded?, Threading
14966: @subsection Dynamic Superinstructions
14967: @cindex Dynamic superinstructions with replication
14968: @cindex Superinstructions
14969: @cindex Replication
14970: 
14971: The engines @command{gforth} and @command{gforth-fast} use another
14972: optimization: Dynamic superinstructions with replication.  As an
14973: example, consider the following colon definition:
14974: 
14975: @example
14976: : squared ( n1 -- n2 )
14977:   dup * ;
14978: @end example
14979: 
14980: Gforth compiles this into the threaded code sequence
14981: 
14982: @example
14983: dup
14984: *
14985: ;s
14986: @end example
14987: 
14988: In normal direct threaded code there is a code address occupying one
14989: cell for each of these primitives.  Each code address points to a
14990: machine code routine, and the interpreter jumps to this machine code in
14991: order to execute the primitive.  The routines for these three
14992: primitives are (in @command{gforth-fast} on the 386):
14993: 
14994: @example
14995: Code dup  
14996: ( $804B950 )  add     esi , # -4  \ $83 $C6 $FC 
14997: ( $804B953 )  add     ebx , # 4  \ $83 $C3 $4 
14998: ( $804B956 )  mov     dword ptr 4 [esi] , ecx  \ $89 $4E $4 
14999: ( $804B959 )  jmp     dword ptr FC [ebx]  \ $FF $63 $FC 
15000: end-code
15001: Code *  
15002: ( $804ACC4 )  mov     eax , dword ptr 4 [esi]  \ $8B $46 $4 
15003: ( $804ACC7 )  add     esi , # 4  \ $83 $C6 $4 
15004: ( $804ACCA )  add     ebx , # 4  \ $83 $C3 $4 
15005: ( $804ACCD )  imul    ecx , eax  \ $F $AF $C8 
15006: ( $804ACD0 )  jmp     dword ptr FC [ebx]  \ $FF $63 $FC 
15007: end-code
15008: Code ;s  
15009: ( $804A693 )  mov     eax , dword ptr [edi]  \ $8B $7 
15010: ( $804A695 )  add     edi , # 4  \ $83 $C7 $4 
15011: ( $804A698 )  lea     ebx , dword ptr 4 [eax]  \ $8D $58 $4 
15012: ( $804A69B )  jmp     dword ptr FC [ebx]  \ $FF $63 $FC 
15013: end-code
15014: @end example
15015: 
15016: With dynamic superinstructions and replication the compiler does not
15017: just lay down the threaded code, but also copies the machine code
15018: fragments, usually without the jump at the end.
15019: 
15020: @example
15021: ( $4057D27D )  add     esi , # -4  \ $83 $C6 $FC 
15022: ( $4057D280 )  add     ebx , # 4  \ $83 $C3 $4 
15023: ( $4057D283 )  mov     dword ptr 4 [esi] , ecx  \ $89 $4E $4 
15024: ( $4057D286 )  mov     eax , dword ptr 4 [esi]  \ $8B $46 $4 
15025: ( $4057D289 )  add     esi , # 4  \ $83 $C6 $4 
15026: ( $4057D28C )  add     ebx , # 4  \ $83 $C3 $4 
15027: ( $4057D28F )  imul    ecx , eax  \ $F $AF $C8 
15028: ( $4057D292 )  mov     eax , dword ptr [edi]  \ $8B $7 
15029: ( $4057D294 )  add     edi , # 4  \ $83 $C7 $4 
15030: ( $4057D297 )  lea     ebx , dword ptr 4 [eax]  \ $8D $58 $4 
15031: ( $4057D29A )  jmp     dword ptr FC [ebx]  \ $FF $63 $FC 
15032: @end example
15033: 
15034: Only when a threaded-code control-flow change happens (e.g., in
15035: @code{;s}), the jump is appended.  This optimization eliminates many of
15036: these jumps and makes the rest much more predictable.  The speedup
15037: depends on the processor and the application; on the Athlon and Pentium
15038: III this optimization typically produces a speedup by a factor of 2.
15039: 
15040: The code addresses in the direct-threaded code are set to point to the
15041: appropriate points in the copied machine code, in this example like
15042: this:
15043: 
15044: @example
15045: primitive  code address
15046:    dup       $4057D27D
15047:    *         $4057D286
15048:    ;s        $4057D292
15049: @end example
15050: 
15051: Thus there can be threaded-code jumps to any place in this piece of
15052: code.  This also simplifies decompilation quite a bit.
15053: 
15054: @cindex --no-dynamic command-line option
15055: @cindex --no-super command-line option
15056: You can disable this optimization with @option{--no-dynamic}.  You can
15057: use the copying without eliminating the jumps (i.e., dynamic
15058: replication, but without superinstructions) with @option{--no-super};
15059: this gives the branch prediction benefit alone; the effect on
15060: performance depends on the CPU; on the Athlon and Pentium III the
15061: speedup is a little less than for dynamic superinstructions with
15062: replication.
15063: 
15064: @cindex patching threaded code
15065: One use of these options is if you want to patch the threaded code.
15066: With superinstructions, many of the dispatch jumps are eliminated, so
15067: patching often has no effect.  These options preserve all the dispatch
15068: jumps.
15069: 
15070: @cindex --dynamic command-line option
15071: On some machines dynamic superinstructions are disabled by default,
15072: because it is unsafe on these machines.  However, if you feel
15073: adventurous, you can enable it with @option{--dynamic}.
15074: 
15075: @node DOES>,  , Dynamic Superinstructions, Threading
15076: @subsection DOES>
15077: @cindex @code{DOES>} implementation
15078: 
15079: @cindex @code{dodoes} routine
15080: @cindex @code{DOES>}-code
15081: One of the most complex parts of a Forth engine is @code{dodoes}, i.e.,
15082: the chunk of code executed by every word defined by a
15083: @code{CREATE}...@code{DOES>} pair; actually with primitive-centric code,
15084: this is only needed if the xt of the word is @code{execute}d. The main
15085: problem here is: How to find the Forth code to be executed, i.e. the
15086: code after the @code{DOES>} (the @code{DOES>}-code)? There are two
15087: solutions:
15088: 
15089: In fig-Forth the code field points directly to the @code{dodoes} and the
15090: @code{DOES>}-code address is stored in the cell after the code address
15091: (i.e. at @code{@i{CFA} cell+}). It may seem that this solution is
15092: illegal in the Forth-79 and all later standards, because in fig-Forth
15093: this address lies in the body (which is illegal in these
15094: standards). However, by making the code field larger for all words this
15095: solution becomes legal again.  We use this approach.  Leaving a cell
15096: unused in most words is a bit wasteful, but on the machines we are
15097: targeting this is hardly a problem.
15098: 
15099: 
15100: @node Primitives, Performance, Threading, Engine
15101: @section Primitives
15102: @cindex primitives, implementation
15103: @cindex virtual machine instructions, implementation
15104: 
15105: @menu
15106: * Automatic Generation::        
15107: * TOS Optimization::            
15108: * Produced code::               
15109: @end menu
15110: 
15111: @node Automatic Generation, TOS Optimization, Primitives, Primitives
15112: @subsection Automatic Generation
15113: @cindex primitives, automatic generation
15114: 
15115: @cindex @file{prims2x.fs}
15116: 
15117: Since the primitives are implemented in a portable language, there is no
15118: longer any need to minimize the number of primitives. On the contrary,
15119: having many primitives has an advantage: speed. In order to reduce the
15120: number of errors in primitives and to make programming them easier, we
15121: provide a tool, the primitive generator (@file{prims2x.fs} aka Vmgen,
15122: @pxref{Top, Vmgen, Introduction, vmgen, Vmgen}), that automatically
15123: generates most (and sometimes all) of the C code for a primitive from
15124: the stack effect notation.  The source for a primitive has the following
15125: form:
15126: 
15127: @cindex primitive source format
15128: @format
15129: @i{Forth-name}  ( @i{stack-effect} )        @i{category}    [@i{pronounc.}]
15130: [@code{""}@i{glossary entry}@code{""}]
15131: @i{C code}
15132: [@code{:}
15133: @i{Forth code}]
15134: @end format
15135: 
15136: The items in brackets are optional. The category and glossary fields
15137: are there for generating the documentation, the Forth code is there
15138: for manual implementations on machines without GNU C. E.g., the source
15139: for the primitive @code{+} is:
15140: @example
15141: +    ( n1 n2 -- n )   core    plus
15142: n = n1+n2;
15143: @end example
15144: 
15145: This looks like a specification, but in fact @code{n = n1+n2} is C
15146: code. Our primitive generation tool extracts a lot of information from
15147: the stack effect notations@footnote{We use a one-stack notation, even
15148: though we have separate data and floating-point stacks; The separate
15149: notation can be generated easily from the unified notation.}: The number
15150: of items popped from and pushed on the stack, their type, and by what
15151: name they are referred to in the C code. It then generates a C code
15152: prelude and postlude for each primitive. The final C code for @code{+}
15153: looks like this:
15154: 
15155: @example
15156: I_plus: /* + ( n1 n2 -- n ) */  /* label, stack effect */
15157: /*  */                          /* documentation */
15158: NAME("+")                       /* debugging output (with -DDEBUG) */
15159: @{
15160: DEF_CA                          /* definition of variable ca (indirect threading) */
15161: Cell n1;                        /* definitions of variables */
15162: Cell n2;
15163: Cell n;
15164: NEXT_P0;                        /* NEXT part 0 */
15165: n1 = (Cell) sp[1];              /* input */
15166: n2 = (Cell) TOS;
15167: sp += 1;                        /* stack adjustment */
15168: @{
15169: n = n1+n2;                      /* C code taken from the source */
15170: @}
15171: NEXT_P1;                        /* NEXT part 1 */
15172: TOS = (Cell)n;                  /* output */
15173: NEXT_P2;                        /* NEXT part 2 */
15174: @}
15175: @end example
15176: 
15177: This looks long and inefficient, but the GNU C compiler optimizes quite
15178: well and produces optimal code for @code{+} on, e.g., the R3000 and the
15179: HP RISC machines: Defining the @code{n}s does not produce any code, and
15180: using them as intermediate storage also adds no cost.
15181: 
15182: There are also other optimizations that are not illustrated by this
15183: example: assignments between simple variables are usually for free (copy
15184: propagation). If one of the stack items is not used by the primitive
15185: (e.g.  in @code{drop}), the compiler eliminates the load from the stack
15186: (dead code elimination). On the other hand, there are some things that
15187: the compiler does not do, therefore they are performed by
15188: @file{prims2x.fs}: The compiler does not optimize code away that stores
15189: a stack item to the place where it just came from (e.g., @code{over}).
15190: 
15191: While programming a primitive is usually easy, there are a few cases
15192: where the programmer has to take the actions of the generator into
15193: account, most notably @code{?dup}, but also words that do not (always)
15194: fall through to @code{NEXT}.
15195: 
15196: For more information
15197: 
15198: @node TOS Optimization, Produced code, Automatic Generation, Primitives
15199: @subsection TOS Optimization
15200: @cindex TOS optimization for primitives
15201: @cindex primitives, keeping the TOS in a register
15202: 
15203: An important optimization for stack machine emulators, e.g., Forth
15204: engines, is keeping  one or more of the top stack items in
15205: registers.  If a word has the stack effect @i{in1}...@i{inx} @code{--}
15206: @i{out1}...@i{outy}, keeping the top @i{n} items in registers
15207: @itemize @bullet
15208: @item
15209: is better than keeping @i{n-1} items, if @i{x>=n} and @i{y>=n},
15210: due to fewer loads from and stores to the stack.
15211: @item is slower than keeping @i{n-1} items, if @i{x<>y} and @i{x<n} and
15212: @i{y<n}, due to additional moves between registers.
15213: @end itemize
15214: 
15215: @cindex -DUSE_TOS
15216: @cindex -DUSE_NO_TOS
15217: In particular, keeping one item in a register is never a disadvantage,
15218: if there are enough registers. Keeping two items in registers is a
15219: disadvantage for frequent words like @code{?branch}, constants,
15220: variables, literals and @code{i}. Therefore our generator only produces
15221: code that keeps zero or one items in registers. The generated C code
15222: covers both cases; the selection between these alternatives is made at
15223: C-compile time using the switch @code{-DUSE_TOS}. @code{TOS} in the C
15224: code for @code{+} is just a simple variable name in the one-item case,
15225: otherwise it is a macro that expands into @code{sp[0]}. Note that the
15226: GNU C compiler tries to keep simple variables like @code{TOS} in
15227: registers, and it usually succeeds, if there are enough registers.
15228: 
15229: @cindex -DUSE_FTOS
15230: @cindex -DUSE_NO_FTOS
15231: The primitive generator performs the TOS optimization for the
15232: floating-point stack, too (@code{-DUSE_FTOS}). For floating-point
15233: operations the benefit of this optimization is even larger:
15234: floating-point operations take quite long on most processors, but can be
15235: performed in parallel with other operations as long as their results are
15236: not used. If the FP-TOS is kept in a register, this works. If
15237: it is kept on the stack, i.e., in memory, the store into memory has to
15238: wait for the result of the floating-point operation, lengthening the
15239: execution time of the primitive considerably.
15240: 
15241: The TOS optimization makes the automatic generation of primitives a
15242: bit more complicated. Just replacing all occurrences of @code{sp[0]} by
15243: @code{TOS} is not sufficient. There are some special cases to
15244: consider:
15245: @itemize @bullet
15246: @item In the case of @code{dup ( w -- w w )} the generator must not
15247: eliminate the store to the original location of the item on the stack,
15248: if the TOS optimization is turned on.
15249: @item Primitives with stack effects of the form @code{--}
15250: @i{out1}...@i{outy} must store the TOS to the stack at the start.
15251: Likewise, primitives with the stack effect @i{in1}...@i{inx} @code{--}
15252: must load the TOS from the stack at the end. But for the null stack
15253: effect @code{--} no stores or loads should be generated.
15254: @end itemize
15255: 
15256: @node Produced code,  , TOS Optimization, Primitives
15257: @subsection Produced code
15258: @cindex primitives, assembly code listing
15259: 
15260: @cindex @file{engine.s}
15261: To see what assembly code is produced for the primitives on your machine
15262: with your compiler and your flag settings, type @code{make engine.s} and
15263: look at the resulting file @file{engine.s}.  Alternatively, you can also
15264: disassemble the code of primitives with @code{see} on some architectures.
15265: 
15266: @node  Performance,  , Primitives, Engine
15267: @section Performance
15268: @cindex performance of some Forth interpreters
15269: @cindex engine performance
15270: @cindex benchmarking Forth systems
15271: @cindex Gforth performance
15272: 
15273: On RISCs the Gforth engine is very close to optimal; i.e., it is usually
15274: impossible to write a significantly faster threaded-code engine.
15275: 
15276: On register-starved machines like the 386 architecture processors
15277: improvements are possible, because @code{gcc} does not utilize the
15278: registers as well as a human, even with explicit register declarations;
15279: e.g., Bernd Beuster wrote a Forth system fragment in assembly language
15280: and hand-tuned it for the 486; this system is 1.19 times faster on the
15281: Sieve benchmark on a 486DX2/66 than Gforth compiled with
15282: @code{gcc-2.6.3} with @code{-DFORCE_REG}.  The situation has improved
15283: with gcc-2.95 and gforth-0.4.9; now the most important virtual machine
15284: registers fit in real registers (and we can even afford to use the TOS
15285: optimization), resulting in a speedup of 1.14 on the sieve over the
15286: earlier results.  And dynamic superinstructions provide another speedup
15287: (but only around a factor 1.2 on the 486).
15288: 
15289: @cindex Win32Forth performance
15290: @cindex NT Forth performance
15291: @cindex eforth performance
15292: @cindex ThisForth performance
15293: @cindex PFE performance
15294: @cindex TILE performance
15295: The potential advantage of assembly language implementations is not
15296: necessarily realized in complete Forth systems: We compared Gforth-0.5.9
15297: (direct threaded, compiled with @code{gcc-2.95.1} and
15298: @code{-DFORCE_REG}) with Win32Forth 1.2093 (newer versions are
15299: reportedly much faster), LMI's NT Forth (Beta, May 1994) and Eforth
15300: (with and without peephole (aka pinhole) optimization of the threaded
15301: code); all these systems were written in assembly language. We also
15302: compared Gforth with three systems written in C: PFE-0.9.14 (compiled
15303: with @code{gcc-2.6.3} with the default configuration for Linux:
15304: @code{-O2 -fomit-frame-pointer -DUSE_REGS -DUNROLL_NEXT}), ThisForth
15305: Beta (compiled with @code{gcc-2.6.3 -O3 -fomit-frame-pointer}; ThisForth
15306: employs peephole optimization of the threaded code) and TILE (compiled
15307: with @code{make opt}). We benchmarked Gforth, PFE, ThisForth and TILE on
15308: a 486DX2/66 under Linux. Kenneth O'Heskin kindly provided the results
15309: for Win32Forth and NT Forth on a 486DX2/66 with similar memory
15310: performance under Windows NT. Marcel Hendrix ported Eforth to Linux,
15311: then extended it to run the benchmarks, added the peephole optimizer,
15312: ran the benchmarks and reported the results.
15313: 
15314: We used four small benchmarks: the ubiquitous Sieve; bubble-sorting and
15315: matrix multiplication come from the Stanford integer benchmarks and have
15316: been translated into Forth by Martin Fraeman; we used the versions
15317: included in the TILE Forth package, but with bigger data set sizes; and
15318: a recursive Fibonacci number computation for benchmarking calling
15319: performance. The following table shows the time taken for the benchmarks
15320: scaled by the time taken by Gforth (in other words, it shows the speedup
15321: factor that Gforth achieved over the other systems).
15322: 
15323: @example
15324: relative       Win32-    NT       eforth       This-      
15325: time     Gforth Forth Forth eforth  +opt   PFE Forth  TILE
15326: sieve      1.00  2.16  1.78   2.16  1.32  2.46  4.96 13.37
15327: bubble     1.00  1.93  2.07   2.18  1.29  2.21        5.70
15328: matmul     1.00  1.92  1.76   1.90  0.96  2.06        5.32
15329: fib        1.00  2.32  2.03   1.86  1.31  2.64  4.55  6.54
15330: @end example
15331: 
15332: You may be quite surprised by the good performance of Gforth when
15333: compared with systems written in assembly language. One important reason
15334: for the disappointing performance of these other systems is probably
15335: that they are not written optimally for the 486 (e.g., they use the
15336: @code{lods} instruction). In addition, Win32Forth uses a comfortable,
15337: but costly method for relocating the Forth image: like @code{cforth}, it
15338: computes the actual addresses at run time, resulting in two address
15339: computations per @code{NEXT} (@pxref{Image File Background}).
15340: 
15341: The speedup of Gforth over PFE, ThisForth and TILE can be easily
15342: explained with the self-imposed restriction of the latter systems to
15343: standard C, which makes efficient threading impossible (however, the
15344: measured implementation of PFE uses a GNU C extension: @pxref{Global Reg
15345: Vars, , Defining Global Register Variables, gcc.info, GNU C Manual}).
15346: Moreover, current C compilers have a hard time optimizing other aspects
15347: of the ThisForth and the TILE source.
15348: 
15349: The performance of Gforth on 386 architecture processors varies widely
15350: with the version of @code{gcc} used. E.g., @code{gcc-2.5.8} failed to
15351: allocate any of the virtual machine registers into real machine
15352: registers by itself and would not work correctly with explicit register
15353: declarations, giving a significantly slower engine (on a 486DX2/66
15354: running the Sieve) than the one measured above.
15355: 
15356: Note that there have been several releases of Win32Forth since the
15357: release presented here, so the results presented above may have little
15358: predictive value for the performance of Win32Forth today (results for
15359: the current release on an i486DX2/66 are welcome).
15360: 
15361: @cindex @file{Benchres}
15362: In
15363: @cite{@uref{http://www.complang.tuwien.ac.at/papers/ertl&maierhofer95.ps.gz,
15364: Translating Forth to Efficient C}} by M. Anton Ertl and Martin
15365: Maierhofer (presented at EuroForth '95), an indirect threaded version of
15366: Gforth is compared with Win32Forth, NT Forth, PFE, ThisForth, and
15367: several native code systems; that version of Gforth is slower on a 486
15368: than the version used here. You can find a newer version of these
15369: measurements at
15370: @uref{http://www.complang.tuwien.ac.at/forth/performance.html}. You can
15371: find numbers for Gforth on various machines in @file{Benchres}.
15372: 
15373: @c ******************************************************************
15374: @c @node Binding to System Library, Cross Compiler, Engine, Top
15375: @c @chapter Binding to System Library
15376: 
15377: @c ****************************************************************
15378: @node Cross Compiler, Bugs, Engine, Top
15379: @chapter Cross Compiler
15380: @cindex @file{cross.fs}
15381: @cindex cross-compiler
15382: @cindex metacompiler
15383: @cindex target compiler
15384: 
15385: The cross compiler is used to bootstrap a Forth kernel. Since Gforth is
15386: mostly written in Forth, including crucial parts like the outer
15387: interpreter and compiler, it needs compiled Forth code to get
15388: started. The cross compiler allows to create new images for other
15389: architectures, even running under another Forth system.
15390: 
15391: @menu
15392: * Using the Cross Compiler::    
15393: * How the Cross Compiler Works::  
15394: @end menu
15395: 
15396: @node Using the Cross Compiler, How the Cross Compiler Works, Cross Compiler, Cross Compiler
15397: @section Using the Cross Compiler
15398: 
15399: The cross compiler uses a language that resembles Forth, but isn't. The
15400: main difference is that you can execute Forth code after definition,
15401: while you usually can't execute the code compiled by cross, because the
15402: code you are compiling is typically for a different computer than the
15403: one you are compiling on.
15404: 
15405: @c anton: This chapter is somewhat different from waht I would expect: I
15406: @c would expect an explanation of the cross language and how to create an
15407: @c application image with it.  The section explains some aspects of
15408: @c creating a Gforth kernel.
15409: 
15410: The Makefile is already set up to allow you to create kernels for new
15411: architectures with a simple make command. The generic kernels using the
15412: GCC compiled virtual machine are created in the normal build process
15413: with @code{make}. To create a embedded Gforth executable for e.g. the
15414: 8086 processor (running on a DOS machine), type
15415: 
15416: @example
15417: make kernl-8086.fi
15418: @end example
15419: 
15420: This will use the machine description from the @file{arch/8086}
15421: directory to create a new kernel. A machine file may look like that:
15422: 
15423: @example
15424: \ Parameter for target systems                         06oct92py
15425: 
15426:     4 Constant cell             \ cell size in bytes
15427:     2 Constant cell<<           \ cell shift to bytes
15428:     5 Constant cell>bit         \ cell shift to bits
15429:     8 Constant bits/char        \ bits per character
15430:     8 Constant bits/byte        \ bits per byte [default: 8]
15431:     8 Constant float            \ bytes per float
15432:     8 Constant /maxalign        \ maximum alignment in bytes
15433: false Constant bigendian        \ byte order
15434: ( true=big, false=little )
15435: 
15436: include machpc.fs               \ feature list
15437: @end example
15438: 
15439: This part is obligatory for the cross compiler itself, the feature list
15440: is used by the kernel to conditionally compile some features in and out,
15441: depending on whether the target supports these features.
15442: 
15443: There are some optional features, if you define your own primitives,
15444: have an assembler, or need special, nonstandard preparation to make the
15445: boot process work. @code{asm-include} includes an assembler,
15446: @code{prims-include} includes primitives, and @code{>boot} prepares for
15447: booting.
15448: 
15449: @example
15450: : asm-include    ." Include assembler" cr
15451:   s" arch/8086/asm.fs" included ;
15452: 
15453: : prims-include  ." Include primitives" cr
15454:   s" arch/8086/prim.fs" included ;
15455: 
15456: : >boot          ." Prepare booting" cr
15457:   s" ' boot >body into-forth 1+ !" evaluate ;
15458: @end example
15459: 
15460: These words are used as sort of macro during the cross compilation in
15461: the file @file{kernel/main.fs}. Instead of using these macros, it would
15462: be possible --- but more complicated --- to write a new kernel project
15463: file, too.
15464: 
15465: @file{kernel/main.fs} expects the machine description file name on the
15466: stack; the cross compiler itself (@file{cross.fs}) assumes that either
15467: @code{mach-file} leaves a counted string on the stack, or
15468: @code{machine-file} leaves an address, count pair of the filename on the
15469: stack.
15470: 
15471: The feature list is typically controlled using @code{SetValue}, generic
15472: files that are used by several projects can use @code{DefaultValue}
15473: instead. Both functions work like @code{Value}, when the value isn't
15474: defined, but @code{SetValue} works like @code{to} if the value is
15475: defined, and @code{DefaultValue} doesn't set anything, if the value is
15476: defined.
15477: 
15478: @example
15479: \ generic mach file for pc gforth                       03sep97jaw
15480: 
15481: true DefaultValue NIL  \ relocating
15482: 
15483: >ENVIRON
15484: 
15485: true DefaultValue file          \ controls the presence of the
15486:                                 \ file access wordset
15487: true DefaultValue OS            \ flag to indicate a operating system
15488: 
15489: true DefaultValue prims         \ true: primitives are c-code
15490: 
15491: true DefaultValue floating      \ floating point wordset is present
15492: 
15493: true DefaultValue glocals       \ gforth locals are present
15494:                                 \ will be loaded
15495: true DefaultValue dcomps        \ double number comparisons
15496: 
15497: true DefaultValue hash          \ hashing primitives are loaded/present
15498: 
15499: true DefaultValue xconds        \ used together with glocals,
15500:                                 \ special conditionals supporting gforths'
15501:                                 \ local variables
15502: true DefaultValue header        \ save a header information
15503: 
15504: true DefaultValue backtrace     \ enables backtrace code
15505: 
15506: false DefaultValue ec
15507: false DefaultValue crlf
15508: 
15509: cell 2 = [IF] &32 [ELSE] &256 [THEN] KB DefaultValue kernel-size
15510: 
15511: &16 KB          DefaultValue stack-size
15512: &15 KB &512 +   DefaultValue fstack-size
15513: &15 KB          DefaultValue rstack-size
15514: &14 KB &512 +   DefaultValue lstack-size
15515: @end example
15516: 
15517: @node How the Cross Compiler Works,  , Using the Cross Compiler, Cross Compiler
15518: @section How the Cross Compiler Works
15519: 
15520: @node Bugs, Origin, Cross Compiler, Top
15521: @appendix Bugs
15522: @cindex bug reporting
15523: 
15524: Known bugs are described in the file @file{BUGS} in the Gforth distribution.
15525: 
15526: If you find a bug, please submit a bug report through
15527: @uref{https://savannah.gnu.org/bugs/?func=addbug&group=gforth}.
15528: 
15529: @itemize @bullet
15530: @item
15531: A program (or a sequence of keyboard commands) that reproduces the bug.
15532: @item
15533: A description of what you think constitutes the buggy behaviour.
15534: @item
15535: The Gforth version used (it is announced at the start of an
15536: interactive Gforth session).
15537: @item
15538: The machine and operating system (on Unix
15539: systems @code{uname -a} will report this information).
15540: @item
15541: The installation options (you can find the configure options at the
15542: start of @file{config.status}) and configuration (@code{configure}
15543: output or @file{config.cache}).
15544: @item
15545: A complete list of changes (if any) you (or your installer) have made to the
15546: Gforth sources.
15547: @end itemize
15548: 
15549: For a thorough guide on reporting bugs read @ref{Bug Reporting, , How
15550: to Report Bugs, gcc.info, GNU C Manual}.
15551: 
15552: 
15553: @node Origin, Forth-related information, Bugs, Top
15554: @appendix Authors and Ancestors of Gforth
15555: 
15556: @section Authors and Contributors
15557: @cindex authors of Gforth
15558: @cindex contributors to Gforth
15559: 
15560: The Gforth project was started in mid-1992 by Bernd Paysan and Anton
15561: Ertl. The third major author was Jens Wilke.  Neal Crook contributed a
15562: lot to the manual.  Assemblers and disassemblers were contributed by
15563: Andrew McKewan, Christian Pirker, and Bernd Thallner.  Lennart Benschop
15564: (who was one of Gforth's first users, in mid-1993) and Stuart Ramsden
15565: inspired us with their continuous feedback. Lennart Benshop contributed
15566: @file{glosgen.fs}, while Stuart Ramsden has been working on automatic
15567: support for calling C libraries. Helpful comments also came from Paul
15568: Kleinrubatscher, Christian Pirker, Dirk Zoller, Marcel Hendrix, John
15569: Wavrik, Barrie Stott, Marc de Groot, Jorge Acerada, Bruce Hoyt, Robert
15570: Epprecht, Dennis Ruffer and David N. Williams. Since the release of
15571: Gforth-0.2.1 there were also helpful comments from many others; thank
15572: you all, sorry for not listing you here (but digging through my mailbox
15573: to extract your names is on my to-do list).
15574: 
15575: Gforth also owes a lot to the authors of the tools we used (GCC, CVS,
15576: and autoconf, among others), and to the creators of the Internet: Gforth
15577: was developed across the Internet, and its authors did not meet
15578: physically for the first 4 years of development.
15579: 
15580: @section Pedigree
15581: @cindex pedigree of Gforth
15582: 
15583: Gforth descends from bigFORTH (1993) and fig-Forth.  Of course, a
15584: significant part of the design of Gforth was prescribed by ANS Forth.
15585: 
15586: Bernd Paysan wrote bigFORTH, a descendent from TurboForth, an unreleased
15587: 32 bit native code version of VolksForth for the Atari ST, written
15588: mostly by Dietrich Weineck.
15589: 
15590: VolksForth was written by Klaus Schleisiek, Bernd Pennemann, Georg
15591: Rehfeld and Dietrich Weineck for the C64 (called UltraForth there) in
15592: the mid-80s and ported to the Atari ST in 1986.  It descends from fig-Forth.
15593: 
15594: @c Henry Laxen and Mike Perry wrote F83 as a model implementation of the
15595: @c Forth-83 standard. !! Pedigree? When?
15596: 
15597: A team led by Bill Ragsdale implemented fig-Forth on many processors in
15598: 1979. Robert Selzer and Bill Ragsdale developed the original
15599: implementation of fig-Forth for the 6502 based on microForth.
15600: 
15601: The principal architect of microForth was Dean Sanderson. microForth was
15602: FORTH, Inc.'s first off-the-shelf product. It was developed in 1976 for
15603: the 1802, and subsequently implemented on the 8080, the 6800 and the
15604: Z80.
15605: 
15606: All earlier Forth systems were custom-made, usually by Charles Moore,
15607: who discovered (as he puts it) Forth during the late 60s. The first full
15608: Forth existed in 1971.
15609: 
15610: A part of the information in this section comes from
15611: @cite{@uref{http://www.forth.com/Content/History/History1.htm,The
15612: Evolution of Forth}} by Elizabeth D. Rather, Donald R. Colburn and
15613: Charles H. Moore, presented at the HOPL-II conference and preprinted
15614: in SIGPLAN Notices 28(3), 1993.  You can find more historical and
15615: genealogical information about Forth there.  For a more general (and
15616: graphical) Forth family tree look see
15617: @cite{@uref{http://www.complang.tuwien.ac.at/forth/family-tree/},
15618: Forth Family Tree and Timeline}.
15619: 
15620: @c ------------------------------------------------------------------
15621: @node Forth-related information, Licenses, Origin, Top
15622: @appendix Other Forth-related information
15623: @cindex Forth-related information
15624: 
15625: @c anton: I threw most of this stuff out, because it can be found through
15626: @c the FAQ and the FAQ is more likely to be up-to-date.
15627: 
15628: @cindex comp.lang.forth
15629: @cindex frequently asked questions
15630: There is an active news group (comp.lang.forth) discussing Forth
15631: (including Gforth) and Forth-related issues. Its
15632: @uref{http://www.complang.tuwien.ac.at/forth/faq/faq-general-2.html,FAQs}
15633: (frequently asked questions and their answers) contains a lot of
15634: information on Forth.  You should read it before posting to
15635: comp.lang.forth.
15636: 
15637: The ANS Forth standard is most usable in its
15638: @uref{http://www.taygeta.com/forth/dpans.html, HTML form}.
15639: 
15640: @c ---------------------------------------------------
15641: @node  Licenses, Word Index, Forth-related information, Top
15642: @appendix Licenses
15643: 
15644: @menu
15645: * GNU Free Documentation License::  License for copying this manual.
15646: * Copying::                         GPL (for copying this software).
15647: @end menu
15648: 
15649: @include fdl.texi
15650: 
15651: @include gpl.texi
15652: 
15653: 
15654: 
15655: @c ------------------------------------------------------------------
15656: @node Word Index, Concept Index, Licenses, Top
15657: @unnumbered Word Index
15658: 
15659: This index is a list of Forth words that have ``glossary'' entries
15660: within this manual. Each word is listed with its stack effect and
15661: wordset.
15662: 
15663: @printindex fn
15664: 
15665: @c anton: the name index seems superfluous given the word and concept indices.
15666: 
15667: @c @node Name Index, Concept Index, Word Index, Top
15668: @c @unnumbered Name Index
15669: 
15670: @c This index is a list of Forth words that have ``glossary'' entries
15671: @c within this manual.
15672: 
15673: @c @printindex ky
15674: 
15675: @c -------------------------------------------------------
15676: @node Concept Index,  , Word Index, Top
15677: @unnumbered Concept and Word Index
15678: 
15679: Not all entries listed in this index are present verbatim in the
15680: text. This index also duplicates, in abbreviated form, all of the words
15681: listed in the Word Index (only the names are listed for the words here).
15682: 
15683: @printindex cp
15684: 
15685: @bye
15686: 
15687: 
15688: 

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