File:  [gforth] / gforth / doc / gforth.ds
Revision 1.234: download - view: text, annotated - select for diffs
Sat Dec 31 15:29:25 2011 UTC (12 years, 2 months ago) by anton
Branches: MAIN
CVS tags: HEAD
updated copyright years

    1: \input texinfo   @c -*-texinfo-*-
    2: @comment The source is gforth.ds, from which gforth.texi is generated
    3: 
    4: @comment TODO: nac29jan99 - a list of things to add in the next edit:
    5: @comment 1. x-ref all ambiguous or implementation-defined features?
    6: @comment 2. Describe the use of Auser Avariable AConstant A, etc.
    7: @comment 3. words in miscellaneous section need a home.
    8: @comment 4. search for TODO for other minor and major works required.
    9: @comment 5. [rats] change all @var to @i in Forth source so that info
   10: @comment    file looks decent.
   11: @c          Not an improvement IMO - anton
   12: @c          and anyway, this should be taken up
   13: @c          with Karl Berry (the texinfo guy) - anton
   14: @c
   15: @c Karl Berry writes:
   16: @c  If they don't like the all-caps for @var Info output, all I can say is
   17: @c  that it's always been that way, and the usage of all-caps for
   18: @c  metavariables has a long tradition.  I think it's best to just let it be
   19: @c  what it is, for the sake of consistency among manuals.
   20: @c
   21: @comment .. would be useful to have a word that identified all deferred words
   22: @comment should semantics stuff in intro be moved to another section
   23: 
   24: @c POSTPONE, COMPILE, [COMPILE], LITERAL should have their own section
   25: 
   26: @comment %**start of header (This is for running Texinfo on a region.)
   27: @setfilename gforth.info
   28: @include version.texi
   29: @settitle Gforth Manual
   30: @c @syncodeindex pg cp
   31: 
   32: @macro progstyle {}
   33: Programming style note:
   34: @end macro
   35: 
   36: @macro assignment {}
   37: @table @i
   38: @item Assignment:
   39: @end macro
   40: @macro endassignment {}
   41: @end table
   42: @end macro
   43: 
   44: @comment macros for beautifying glossary entries
   45: @macro GLOSS-START {}
   46: @iftex
   47: @ninerm
   48: @end iftex
   49: @end macro
   50: 
   51: @macro GLOSS-END {}
   52: @iftex
   53: @rm
   54: @end iftex
   55: @end macro
   56: 
   57: @comment %**end of header (This is for running Texinfo on a region.)
   58: @copying
   59: This manual is for Gforth (version @value{VERSION}, @value{UPDATED}),
   60: a fast and portable implementation of the ANS Forth language.  It
   61: serves as reference manual, but it also contains an introduction to
   62: Forth and a Forth tutorial.
   63: 
   64: Copyright @copyright{} 1995, 1996, 1997, 1998, 2000, 2003, 2004,2005,2006,2007,2008,2009,2010,2011 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 14ms is not fast enough ...
  149: 
  150: Forth Tutorial
  151: 
  152: * Starting Gforth Tutorial::    
  153: * Syntax Tutorial::             
  154: * Crash Course Tutorial::       
  155: * Stack Tutorial::              
  156: * Arithmetics Tutorial::        
  157: * Stack Manipulation Tutorial::  
  158: * Using files for Forth code Tutorial::  
  159: * Comments Tutorial::           
  160: * Colon Definitions Tutorial::  
  161: * Decompilation Tutorial::      
  162: * Stack-Effect Comments Tutorial::  
  163: * Types Tutorial::              
  164: * Factoring Tutorial::          
  165: * Designing the stack effect Tutorial::  
  166: * Local Variables Tutorial::    
  167: * Conditional execution Tutorial::  
  168: * Flags and Comparisons Tutorial::  
  169: * General Loops Tutorial::      
  170: * Counted loops Tutorial::      
  171: * Recursion Tutorial::          
  172: * Leaving definitions or loops Tutorial::  
  173: * Return Stack Tutorial::       
  174: * Memory Tutorial::             
  175: * Characters and Strings Tutorial::  
  176: * Alignment Tutorial::          
  177: * Floating Point Tutorial::     
  178: * Files Tutorial::              
  179: * Interpretation and Compilation Semantics and Immediacy Tutorial::  
  180: * Execution Tokens Tutorial::   
  181: * Exceptions Tutorial::         
  182: * Defining Words Tutorial::     
  183: * Arrays and Records Tutorial::  
  184: * POSTPONE Tutorial::           
  185: * Literal Tutorial::            
  186: * Advanced macros Tutorial::    
  187: * Compilation Tokens Tutorial::  
  188: * Wordlists and Search Order Tutorial::  
  189: 
  190: An Introduction to ANS Forth
  191: 
  192: * Introducing the Text Interpreter::  
  193: * Stacks and Postfix notation::  
  194: * Your first definition::       
  195: * How does that work?::         
  196: * Forth is written in Forth::   
  197: * Review - elements of a Forth system::  
  198: * Where to go next::            
  199: * Exercises::                   
  200: 
  201: Forth Words
  202: 
  203: * Notation::                    
  204: * Case insensitivity::          
  205: * Comments::                    
  206: * Boolean Flags::               
  207: * Arithmetic::                  
  208: * Stack Manipulation::          
  209: * Memory::                      
  210: * Control Structures::          
  211: * Defining Words::              
  212: * Interpretation and Compilation Semantics::  
  213: * Tokens for Words::            
  214: * Compiling words::             
  215: * The Text Interpreter::        
  216: * The Input Stream::            
  217: * Word Lists::                  
  218: * Environmental Queries::       
  219: * Files::                       
  220: * Blocks::                      
  221: * Other I/O::                   
  222: * OS command line arguments::   
  223: * Locals::                      
  224: * Structures::                  
  225: * Object-oriented Forth::       
  226: * Programming Tools::           
  227: * C Interface::                 
  228: * Assembler and Code Words::    
  229: * Threading Words::             
  230: * Passing Commands to the OS::  
  231: * Keeping track of Time::       
  232: * Miscellaneous Words::         
  233: 
  234: Arithmetic
  235: 
  236: * Single precision::            
  237: * Double precision::            Double-cell integer arithmetic
  238: * Bitwise operations::          
  239: * Numeric comparison::          
  240: * Mixed precision::             Operations with single and double-cell integers
  241: * Floating Point::              
  242: 
  243: Stack Manipulation
  244: 
  245: * Data stack::                  
  246: * Floating point stack::        
  247: * Return stack::                
  248: * Locals stack::                
  249: * Stack pointer manipulation::  
  250: 
  251: Memory
  252: 
  253: * Memory model::                
  254: * Dictionary allocation::       
  255: * Heap Allocation::             
  256: * Memory Access::               
  257: * Address arithmetic::          
  258: * Memory Blocks::               
  259: 
  260: Control Structures
  261: 
  262: * Selection::                   IF ... ELSE ... ENDIF
  263: * Simple Loops::                BEGIN ...
  264: * Counted Loops::               DO
  265: * Arbitrary control structures::  
  266: * Calls and returns::           
  267: * Exception Handling::          
  268: 
  269: Defining Words
  270: 
  271: * CREATE::                      
  272: * Variables::                   Variables and user variables
  273: * Constants::                   
  274: * Values::                      Initialised variables
  275: * Colon Definitions::           
  276: * Anonymous Definitions::       Definitions without names
  277: * Supplying names::             Passing definition names as strings
  278: * User-defined Defining Words::  
  279: * Deferred Words::              Allow forward references
  280: * Aliases::                     
  281: 
  282: User-defined Defining Words
  283: 
  284: * CREATE..DOES> applications::  
  285: * CREATE..DOES> details::       
  286: * Advanced does> usage example::  
  287: * Const-does>::                 
  288: 
  289: Interpretation and Compilation Semantics
  290: 
  291: * Combined words::              
  292: 
  293: Tokens for Words
  294: 
  295: * Execution token::             represents execution/interpretation semantics
  296: * Compilation token::           represents compilation semantics
  297: * Name token::                  represents named words
  298: 
  299: Compiling words
  300: 
  301: * Literals::                    Compiling data values
  302: * Macros::                      Compiling words
  303: 
  304: The Text Interpreter
  305: 
  306: * Input Sources::               
  307: * Number Conversion::           
  308: * Interpret/Compile states::    
  309: * Interpreter Directives::      
  310: 
  311: Word Lists
  312: 
  313: * Vocabularies::                
  314: * Why use word lists?::         
  315: * Word list example::           
  316: 
  317: Files
  318: 
  319: * Forth source files::          
  320: * General files::               
  321: * Redirection::                 
  322: * Search Paths::                
  323: 
  324: Search Paths
  325: 
  326: * Source Search Paths::         
  327: * General Search Paths::        
  328: 
  329: Other I/O
  330: 
  331: * Simple numeric output::       Predefined formats
  332: * Formatted numeric output::    Formatted (pictured) output
  333: * String Formats::              How Forth stores strings in memory
  334: * Displaying characters and strings::  Other stuff
  335: * Terminal output::             Cursor positioning etc.
  336: * Single-key input::            
  337: * Line input and conversion::   
  338: * Pipes::                       How to create your own pipes
  339: * Xchars and Unicode::          Non-ASCII characters
  340: 
  341: Locals
  342: 
  343: * Gforth locals::               
  344: * ANS Forth locals::            
  345: 
  346: Gforth locals
  347: 
  348: * Where are locals visible by name?::  
  349: * How long do locals live?::    
  350: * Locals programming style::    
  351: * Locals implementation::       
  352: 
  353: Structures
  354: 
  355: * Why explicit structure support?::  
  356: * Structure Usage::             
  357: * Structure Naming Convention::  
  358: * Structure Implementation::    
  359: * Structure Glossary::          
  360: * Forth200x Structures::        
  361: 
  362: Object-oriented Forth
  363: 
  364: * Why object-oriented programming?::  
  365: * Object-Oriented Terminology::  
  366: * Objects::                     
  367: * OOF::                         
  368: * Mini-OOF::                    
  369: * Comparison with other object models::  
  370: 
  371: The @file{objects.fs} model
  372: 
  373: * Properties of the Objects model::  
  374: * Basic Objects Usage::         
  375: * The Objects base class::      
  376: * Creating objects::            
  377: * Object-Oriented Programming Style::  
  378: * Class Binding::               
  379: * Method conveniences::         
  380: * Classes and Scoping::         
  381: * Dividing classes::            
  382: * Object Interfaces::           
  383: * Objects Implementation::      
  384: * Objects Glossary::            
  385: 
  386: The @file{oof.fs} model
  387: 
  388: * Properties of the OOF model::  
  389: * Basic OOF Usage::             
  390: * The OOF base class::          
  391: * Class Declaration::           
  392: * Class Implementation::        
  393: 
  394: The @file{mini-oof.fs} model
  395: 
  396: * Basic Mini-OOF Usage::        
  397: * Mini-OOF Example::            
  398: * Mini-OOF Implementation::     
  399: 
  400: Programming Tools
  401: 
  402: * Examining::                   Data and Code.
  403: * Forgetting words::            Usually before reloading.
  404: * Debugging::                   Simple and quick.
  405: * Assertions::                  Making your programs self-checking.
  406: * Singlestep Debugger::         Executing your program word by word.
  407: 
  408: C Interface
  409: 
  410: * Calling C Functions::         
  411: * Declaring C Functions::       
  412: * Calling C function pointers::  
  413: * Defining library interfaces::  
  414: * Declaring OS-level libraries::  
  415: * Callbacks::                   
  416: * C interface internals::       
  417: * Low-Level C Interface Words::  
  418: 
  419: Assembler and Code Words
  420: 
  421: * Assembler Definitions::       Definitions in assembly language
  422: * Common Assembler::            Assembler Syntax
  423: * Common Disassembler::         
  424: * 386 Assembler::               Deviations and special cases
  425: * AMD64 Assembler::             
  426: * Alpha Assembler::             Deviations and special cases
  427: * MIPS assembler::              Deviations and special cases
  428: * PowerPC assembler::           Deviations and special cases
  429: * ARM Assembler::               Deviations and special cases
  430: * Other assemblers::            How to write them
  431: 
  432: Tools
  433: 
  434: * ANS Report::                  Report the words used, sorted by wordset.
  435: * Stack depth changes::         Where does this stack item come from?
  436: 
  437: ANS conformance
  438: 
  439: * The Core Words::              
  440: * The optional Block word set::  
  441: * The optional Double Number word set::  
  442: * The optional Exception word set::  
  443: * The optional Facility word set::  
  444: * The optional File-Access word set::  
  445: * The optional Floating-Point word set::  
  446: * The optional Locals word set::  
  447: * The optional Memory-Allocation word set::  
  448: * The optional Programming-Tools word set::  
  449: * The optional Search-Order word set::  
  450: 
  451: The Core Words
  452: 
  453: * core-idef::                   Implementation Defined Options                   
  454: * core-ambcond::                Ambiguous Conditions                
  455: * core-other::                  Other System Documentation                  
  456: 
  457: The optional Block word set
  458: 
  459: * block-idef::                  Implementation Defined Options
  460: * block-ambcond::               Ambiguous Conditions               
  461: * block-other::                 Other System Documentation                 
  462: 
  463: The optional Double Number word set
  464: 
  465: * double-ambcond::              Ambiguous Conditions              
  466: 
  467: The optional Exception word set
  468: 
  469: * exception-idef::              Implementation Defined Options              
  470: 
  471: The optional Facility word set
  472: 
  473: * facility-idef::               Implementation Defined Options               
  474: * facility-ambcond::            Ambiguous Conditions            
  475: 
  476: The optional File-Access word set
  477: 
  478: * file-idef::                   Implementation Defined Options
  479: * file-ambcond::                Ambiguous Conditions                
  480: 
  481: The optional Floating-Point word set
  482: 
  483: * floating-idef::               Implementation Defined Options
  484: * floating-ambcond::            Ambiguous Conditions            
  485: 
  486: The optional Locals word set
  487: 
  488: * locals-idef::                 Implementation Defined Options                 
  489: * locals-ambcond::              Ambiguous Conditions              
  490: 
  491: The optional Memory-Allocation word set
  492: 
  493: * memory-idef::                 Implementation Defined Options                 
  494: 
  495: The optional Programming-Tools word set
  496: 
  497: * programming-idef::            Implementation Defined Options            
  498: * programming-ambcond::         Ambiguous Conditions         
  499: 
  500: The optional Search-Order word set
  501: 
  502: * search-idef::                 Implementation Defined Options                 
  503: * search-ambcond::              Ambiguous Conditions              
  504: 
  505: Emacs and Gforth
  506: 
  507: * Installing gforth.el::        Making Emacs aware of Forth.
  508: * Emacs Tags::                  Viewing the source of a word in Emacs.
  509: * Hilighting::                  Making Forth code look prettier.
  510: * Auto-Indentation::            Customizing auto-indentation.
  511: * Blocks Files::                Reading and writing blocks files.
  512: 
  513: Image Files
  514: 
  515: * Image Licensing Issues::      Distribution terms for images.
  516: * Image File Background::       Why have image files?
  517: * Non-Relocatable Image Files::  don't always work.
  518: * Data-Relocatable Image Files::  are better.
  519: * Fully Relocatable Image Files::  better yet.
  520: * Stack and Dictionary Sizes::  Setting the default sizes for an image.
  521: * Running Image Files::         @code{gforth -i @i{file}} or @i{file}.
  522: * Modifying the Startup Sequence::  and turnkey applications.
  523: 
  524: Fully Relocatable Image Files
  525: 
  526: * gforthmi::                    The normal way
  527: * cross.fs::                    The hard way
  528: 
  529: Engine
  530: 
  531: * Portability::                 
  532: * Threading::                   
  533: * Primitives::                  
  534: * Performance::                 
  535: 
  536: Threading
  537: 
  538: * Scheduling::                  
  539: * Direct or Indirect Threaded?::  
  540: * Dynamic Superinstructions::   
  541: * DOES>::                       
  542: 
  543: Primitives
  544: 
  545: * Automatic Generation::        
  546: * TOS Optimization::            
  547: * Produced code::               
  548: 
  549: Cross Compiler
  550: 
  551: * Using the Cross Compiler::    
  552: * How the Cross Compiler Works::  
  553: 
  554: Licenses
  555: 
  556: * GNU Free Documentation License::  License for copying this manual.
  557: * Copying::                     GPL (for copying this software).
  558: 
  559: @end detailmenu
  560: @end menu
  561: 
  562: @c ----------------------------------------------------------
  563: @iftex
  564: @unnumbered Preface
  565: @cindex Preface
  566: This manual documents Gforth. Some introductory material is provided for
  567: readers who are unfamiliar with Forth or who are migrating to Gforth
  568: from other Forth compilers. However, this manual is primarily a
  569: reference manual.
  570: @end iftex
  571: 
  572: @comment TODO much more blurb here.
  573: 
  574: @c ******************************************************************
  575: @node Goals, Gforth Environment, Top, Top
  576: @comment node-name,     next,           previous, up
  577: @chapter Goals of Gforth
  578: @cindex goals of the Gforth project
  579: The goal of the Gforth Project is to develop a standard model for
  580: ANS Forth. This can be split into several subgoals:
  581: 
  582: @itemize @bullet
  583: @item
  584: Gforth should conform to the ANS Forth Standard.
  585: @item
  586: It should be a model, i.e. it should define all the
  587: implementation-dependent things.
  588: @item
  589: It should become standard, i.e. widely accepted and used. This goal
  590: is the most difficult one.
  591: @end itemize
  592: 
  593: To achieve these goals Gforth should be
  594: @itemize @bullet
  595: @item
  596: Similar to previous models (fig-Forth, F83)
  597: @item
  598: Powerful. It should provide for all the things that are considered
  599: necessary today and even some that are not yet considered necessary.
  600: @item
  601: Efficient. It should not get the reputation of being exceptionally
  602: slow.
  603: @item
  604: Free.
  605: @item
  606: Available on many machines/easy to port.
  607: @end itemize
  608: 
  609: Have we achieved these goals? Gforth conforms to the ANS Forth
  610: standard. It may be considered a model, but we have not yet documented
  611: which parts of the model are stable and which parts we are likely to
  612: change. It certainly has not yet become a de facto standard, but it
  613: appears to be quite popular. It has some similarities to and some
  614: differences from previous models. It has some powerful features, but not
  615: yet everything that we envisioned. We certainly have achieved our
  616: execution speed goals (@pxref{Performance})@footnote{However, in 1998
  617: the bar was raised when the major commercial Forth vendors switched to
  618: native code compilers.}.  It is free and available on many machines.
  619: 
  620: @c ******************************************************************
  621: @node Gforth Environment, Tutorial, Goals, Top
  622: @chapter Gforth Environment
  623: @cindex Gforth environment
  624: 
  625: Note: ultimately, the Gforth man page will be auto-generated from the
  626: material in this chapter.
  627: 
  628: @menu
  629: * Invoking Gforth::             Getting in
  630: * Leaving Gforth::              Getting out
  631: * Command-line editing::        
  632: * Environment variables::       that affect how Gforth starts up
  633: * Gforth Files::                What gets installed and where
  634: * Gforth in pipes::             
  635: * Startup speed::               When 14ms is not fast enough ...
  636: @end menu
  637: 
  638: For related information about the creation of images see @ref{Image Files}.
  639: 
  640: @comment ----------------------------------------------
  641: @node Invoking Gforth, Leaving Gforth, Gforth Environment, Gforth Environment
  642: @section Invoking Gforth
  643: @cindex invoking Gforth
  644: @cindex running Gforth
  645: @cindex command-line options
  646: @cindex options on the command line
  647: @cindex flags on the command line
  648: 
  649: Gforth is made up of two parts; an executable ``engine'' (named
  650: @command{gforth} or @command{gforth-fast}) and an image file. To start it, you
  651: will usually just say @code{gforth} -- this automatically loads the
  652: default image file @file{gforth.fi}. In many other cases the default
  653: Gforth image will be invoked like this:
  654: @example
  655: gforth [file | -e forth-code] ...
  656: @end example
  657: @noindent
  658: This interprets the contents of the files and the Forth code in the order they
  659: are given.
  660: 
  661: In addition to the @command{gforth} engine, there is also an engine
  662: called @command{gforth-fast}, which is faster, but gives less
  663: informative error messages (@pxref{Error messages}) and may catch some
  664: errors (in particular, stack underflows and integer division errors)
  665: later or not at all.  You should use it for debugged,
  666: performance-critical programs.
  667: 
  668: Moreover, there is an engine called @command{gforth-itc}, which is
  669: useful in some backwards-compatibility situations (@pxref{Direct or
  670: Indirect Threaded?}).
  671: 
  672: In general, the command line looks like this:
  673: 
  674: @example
  675: gforth[-fast] [engine options] [image options]
  676: @end example
  677: 
  678: The engine options must come before the rest of the command
  679: line. They are:
  680: 
  681: @table @code
  682: @cindex -i, command-line option
  683: @cindex --image-file, command-line option
  684: @item --image-file @i{file}
  685: @itemx -i @i{file}
  686: Loads the Forth image @i{file} instead of the default
  687: @file{gforth.fi} (@pxref{Image Files}).
  688: 
  689: @cindex --appl-image, command-line option
  690: @item --appl-image @i{file}
  691: Loads the image @i{file} and leaves all further command-line arguments
  692: to the image (instead of processing them as engine options).  This is
  693: useful for building executable application images on Unix, built with
  694: @code{gforthmi --application ...}.
  695: 
  696: @cindex --path, command-line option
  697: @cindex -p, command-line option
  698: @item --path @i{path}
  699: @itemx -p @i{path}
  700: Uses @i{path} for searching the image file and Forth source code files
  701: instead of the default in the environment variable @code{GFORTHPATH} or
  702: the path specified at installation time (e.g.,
  703: @file{/usr/local/share/gforth/0.2.0:.}). A path is given as a list of
  704: directories, separated by @samp{:} (on Unix) or @samp{;} (on other OSs).
  705: 
  706: @cindex --dictionary-size, command-line option
  707: @cindex -m, command-line option
  708: @cindex @i{size} parameters for command-line options
  709: @cindex size of the dictionary and the stacks
  710: @item --dictionary-size @i{size}
  711: @itemx -m @i{size}
  712: Allocate @i{size} space for the Forth dictionary space instead of
  713: using the default specified in the image (typically 256K). The
  714: @i{size} specification for this and subsequent options consists of
  715: an integer and a unit (e.g.,
  716: @code{4M}). The unit can be one of @code{b} (bytes), @code{e} (element
  717: size, in this case Cells), @code{k} (kilobytes), @code{M} (Megabytes),
  718: @code{G} (Gigabytes), and @code{T} (Terabytes). If no unit is specified,
  719: @code{e} is used.
  720: 
  721: @cindex --data-stack-size, command-line option
  722: @cindex -d, command-line option
  723: @item --data-stack-size @i{size}
  724: @itemx -d @i{size}
  725: Allocate @i{size} space for the data stack instead of using the
  726: default specified in the image (typically 16K).
  727: 
  728: @cindex --return-stack-size, command-line option
  729: @cindex -r, command-line option
  730: @item --return-stack-size @i{size}
  731: @itemx -r @i{size}
  732: Allocate @i{size} space for the return stack instead of using the
  733: default specified in the image (typically 15K).
  734: 
  735: @cindex --fp-stack-size, command-line option
  736: @cindex -f, command-line option
  737: @item --fp-stack-size @i{size}
  738: @itemx -f @i{size}
  739: Allocate @i{size} space for the floating point stack instead of
  740: using the default specified in the image (typically 15.5K). In this case
  741: the unit specifier @code{e} refers to floating point numbers.
  742: 
  743: @cindex --locals-stack-size, command-line option
  744: @cindex -l, command-line option
  745: @item --locals-stack-size @i{size}
  746: @itemx -l @i{size}
  747: Allocate @i{size} space for the locals stack instead of using the
  748: default specified in the image (typically 14.5K).
  749: 
  750: @cindex --vm-commit, command-line option
  751: @cindex overcommit memory for dictionary and stacks
  752: @cindex memory overcommit for dictionary and stacks
  753: @item --vm-commit
  754: Normally, Gforth tries to start up even if there is not enough virtual
  755: memory for the dictionary and the stacks (using @code{MAP_NORESERVE}
  756: on OSs that support it); so you can ask for a really big dictionary
  757: and/or stacks, and as long as you don't use more virtual memory than
  758: is available, everything will be fine (but if you use more, processes
  759: get killed).  With this option you just use the default allocation
  760: policy of the OS; for OSs that don't overcommit (e.g., Solaris), this
  761: means that you cannot and should not ask for as big dictionary and
  762: stacks, but once Gforth successfully starts up, out-of-memory won't
  763: kill it.
  764: 
  765: @cindex -h, command-line option
  766: @cindex --help, command-line option
  767: @item --help
  768: @itemx -h
  769: Print a message about the command-line options
  770: 
  771: @cindex -v, command-line option
  772: @cindex --version, command-line option
  773: @item --version
  774: @itemx -v
  775: Print version and exit
  776: 
  777: @cindex --debug, command-line option
  778: @item --debug
  779: Print some information useful for debugging on startup.
  780: 
  781: @cindex --offset-image, command-line option
  782: @item --offset-image
  783: Start the dictionary at a slightly different position than would be used
  784: otherwise (useful for creating data-relocatable images,
  785: @pxref{Data-Relocatable Image Files}).
  786: 
  787: @cindex --no-offset-im, command-line option
  788: @item --no-offset-im
  789: Start the dictionary at the normal position.
  790: 
  791: @cindex --clear-dictionary, command-line option
  792: @item --clear-dictionary
  793: Initialize all bytes in the dictionary to 0 before loading the image
  794: (@pxref{Data-Relocatable Image Files}).
  795: 
  796: @cindex --die-on-signal, command-line-option
  797: @item --die-on-signal
  798: Normally Gforth handles most signals (e.g., the user interrupt SIGINT,
  799: or the segmentation violation SIGSEGV) by translating it into a Forth
  800: @code{THROW}. With this option, Gforth exits if it receives such a
  801: signal. This option is useful when the engine and/or the image might be
  802: severely broken (such that it causes another signal before recovering
  803: from the first); this option avoids endless loops in such cases.
  804: 
  805: @cindex --no-dynamic, command-line option
  806: @cindex --dynamic, command-line option
  807: @item --no-dynamic
  808: @item --dynamic
  809: Disable or enable dynamic superinstructions with replication
  810: (@pxref{Dynamic Superinstructions}).
  811: 
  812: @cindex --no-super, command-line option
  813: @item --no-super
  814: Disable dynamic superinstructions, use just dynamic replication; this is
  815: useful if you want to patch threaded code (@pxref{Dynamic
  816: Superinstructions}).
  817: 
  818: @cindex --ss-number, command-line option
  819: @item --ss-number=@var{N}
  820: Use only the first @var{N} static superinstructions compiled into the
  821: engine (default: use them all; note that only @code{gforth-fast} has
  822: any).  This option is useful for measuring the performance impact of
  823: static superinstructions.
  824: 
  825: @cindex --ss-min-..., command-line options
  826: @item --ss-min-codesize
  827: @item --ss-min-ls
  828: @item --ss-min-lsu
  829: @item --ss-min-nexts
  830: Use specified metric for determining the cost of a primitive or static
  831: superinstruction for static superinstruction selection.  @code{Codesize}
  832: is the native code size of the primive or static superinstruction,
  833: @code{ls} is the number of loads and stores, @code{lsu} is the number of
  834: loads, stores, and updates, and @code{nexts} is the number of dispatches
  835: (not taking dynamic superinstructions into account), i.e. every
  836: primitive or static superinstruction has cost 1. Default:
  837: @code{codesize} if you use dynamic code generation, otherwise
  838: @code{nexts}.
  839: 
  840: @cindex --ss-greedy, command-line option
  841: @item --ss-greedy
  842: This option is useful for measuring the performance impact of static
  843: superinstructions.  By default, an optimal shortest-path algorithm is
  844: used for selecting static superinstructions.  With @option{--ss-greedy}
  845: this algorithm is modified to assume that anything after the static
  846: superinstruction currently under consideration is not combined into
  847: static superinstructions.  With @option{--ss-min-nexts} this produces
  848: the same result as a greedy algorithm that always selects the longest
  849: superinstruction available at the moment.  E.g., if there are
  850: superinstructions AB and BCD, then for the sequence A B C D the optimal
  851: algorithm will select A BCD and the greedy algorithm will select AB C D.
  852: 
  853: @cindex --print-metrics, command-line option
  854: @item --print-metrics
  855: Prints some metrics used during static superinstruction selection:
  856: @code{code size} is the actual size of the dynamically generated code.
  857: @code{Metric codesize} is the sum of the codesize metrics as seen by
  858: static superinstruction selection; there is a difference from @code{code
  859: size}, because not all primitives and static superinstructions are
  860: compiled into dynamically generated code, and because of markers.  The
  861: other metrics correspond to the @option{ss-min-...} options.  This
  862: option is useful for evaluating the effects of the @option{--ss-...}
  863: options.
  864: 
  865: @end table
  866: 
  867: @cindex loading files at startup
  868: @cindex executing code on startup
  869: @cindex batch processing with Gforth
  870: As explained above, the image-specific command-line arguments for the
  871: default image @file{gforth.fi} consist of a sequence of filenames and
  872: @code{-e @var{forth-code}} options that are interpreted in the sequence
  873: in which they are given. The @code{-e @var{forth-code}} or
  874: @code{--evaluate @var{forth-code}} option evaluates the Forth code. This
  875: option takes only one argument; if you want to evaluate more Forth
  876: words, you have to quote them or use @code{-e} several times. To exit
  877: after processing the command line (instead of entering interactive mode)
  878: append @code{-e bye} to the command line.  You can also process the
  879: command-line arguments with a Forth program (@pxref{OS command line
  880: arguments}).
  881: 
  882: @cindex versions, invoking other versions of Gforth
  883: If you have several versions of Gforth installed, @code{gforth} will
  884: invoke the version that was installed last. @code{gforth-@i{version}}
  885: invokes a specific version. If your environment contains the variable
  886: @code{GFORTHPATH}, you may want to override it by using the
  887: @code{--path} option.
  888: 
  889: Not yet implemented:
  890: On startup the system first executes the system initialization file
  891: (unless the option @code{--no-init-file} is given; note that the system
  892: resulting from using this option may not be ANS Forth conformant). Then
  893: the user initialization file @file{.gforth.fs} is executed, unless the
  894: option @code{--no-rc} is given; this file is searched for in @file{.},
  895: then in @file{~}, then in the normal path (see above).
  896: 
  897: 
  898: 
  899: @comment ----------------------------------------------
  900: @node Leaving Gforth, Command-line editing, Invoking Gforth, Gforth Environment
  901: @section Leaving Gforth
  902: @cindex Gforth - leaving
  903: @cindex leaving Gforth
  904: 
  905: You can leave Gforth by typing @code{bye} or @kbd{Ctrl-d} (at the start
  906: of a line) or (if you invoked Gforth with the @code{--die-on-signal}
  907: option) @kbd{Ctrl-c}. When you leave Gforth, all of your definitions and
  908: data are discarded.  For ways of saving the state of the system before
  909: leaving Gforth see @ref{Image Files}.
  910: 
  911: doc-bye
  912: 
  913: 
  914: @comment ----------------------------------------------
  915: @node Command-line editing, Environment variables, Leaving Gforth, Gforth Environment
  916: @section Command-line editing
  917: @cindex command-line editing
  918: 
  919: Gforth maintains a history file that records every line that you type to
  920: the text interpreter. This file is preserved between sessions, and is
  921: used to provide a command-line recall facility; if you type @kbd{Ctrl-P}
  922: repeatedly you can recall successively older commands from this (or
  923: previous) session(s). The full list of command-line editing facilities is:
  924: 
  925: @itemize @bullet
  926: @item
  927: @kbd{Ctrl-p} (``previous'') (or up-arrow) to recall successively older
  928: commands from the history buffer.
  929: @item
  930: @kbd{Ctrl-n} (``next'') (or down-arrow) to recall successively newer commands
  931: from the history buffer.
  932: @item
  933: @kbd{Ctrl-f} (or right-arrow) to move the cursor right, non-destructively.
  934: @item
  935: @kbd{Ctrl-b} (or left-arrow) to move the cursor left, non-destructively.
  936: @item
  937: @kbd{Ctrl-h} (backspace) to delete the character to the left of the cursor,
  938: closing up the line.
  939: @item
  940: @kbd{Ctrl-k} to delete (``kill'') from the cursor to the end of the line.
  941: @item
  942: @kbd{Ctrl-a} to move the cursor to the start of the line.
  943: @item
  944: @kbd{Ctrl-e} to move the cursor to the end of the line.
  945: @item
  946: @key{RET} (@kbd{Ctrl-m}) or @key{LFD} (@kbd{Ctrl-j}) to submit the current
  947: line.
  948: @item
  949: @key{TAB} to step through all possible full-word completions of the word
  950: currently being typed.
  951: @item
  952: @kbd{Ctrl-d} on an empty line line to terminate Gforth (gracefully,
  953: using @code{bye}). 
  954: @item
  955: @kbd{Ctrl-x} (or @code{Ctrl-d} on a non-empty line) to delete the
  956: character under the cursor.
  957: @end itemize
  958: 
  959: When editing, displayable characters are inserted to the left of the
  960: cursor position; the line is always in ``insert'' (as opposed to
  961: ``overstrike'') mode.
  962: 
  963: @cindex history file
  964: @cindex @file{.gforth-history}
  965: On Unix systems, the history file is @file{~/.gforth-history} by
  966: default@footnote{i.e. it is stored in the user's home directory.}. You
  967: can find out the name and location of your history file using:
  968: 
  969: @example 
  970: history-file type \ Unix-class systems
  971: 
  972: history-file type \ Other systems
  973: history-dir  type
  974: @end example
  975: 
  976: If you enter long definitions by hand, you can use a text editor to
  977: paste them out of the history file into a Forth source file for reuse at
  978: a later time.
  979: 
  980: Gforth never trims the size of the history file, so you should do this
  981: periodically, if necessary.
  982: 
  983: @comment this is all defined in history.fs
  984: @comment NAC TODO the ctrl-D behaviour can either do a bye or a beep.. how is that option
  985: @comment chosen?
  986: 
  987: 
  988: @comment ----------------------------------------------
  989: @node Environment variables, Gforth Files, Command-line editing, Gforth Environment
  990: @section Environment variables
  991: @cindex environment variables
  992: 
  993: Gforth uses these environment variables:
  994: 
  995: @itemize @bullet
  996: @item
  997: @cindex @code{GFORTHHIST} -- environment variable
  998: @code{GFORTHHIST} -- (Unix systems only) specifies the directory in which to
  999: open/create the history file, @file{.gforth-history}. Default:
 1000: @code{$HOME}.
 1001: 
 1002: @item
 1003: @cindex @code{GFORTHPATH} -- environment variable
 1004: @code{GFORTHPATH} -- specifies the path used when searching for the gforth image file and
 1005: for Forth source-code files.
 1006: 
 1007: @item
 1008: @cindex @code{LANG} -- environment variable
 1009: @code{LANG} -- see @code{LC_CTYPE}
 1010: 
 1011: @item
 1012: @cindex @code{LC_ALL} -- environment variable
 1013: @code{LC_ALL} -- see @code{LC_CTYPE}
 1014: 
 1015: @item
 1016: @cindex @code{LC_CTYPE} -- environment variable
 1017: @code{LC_CTYPE} -- If this variable contains ``UTF-8'' on Gforth
 1018: startup, Gforth uses the UTF-8 encoding for strings internally and
 1019: expects its input and produces its output in UTF-8 encoding, otherwise
 1020: the encoding is 8bit (see @pxref{Xchars and Unicode}).  If this
 1021: environment variable is unset, Gforth looks in @code{LC_ALL}, and if
 1022: that is unset, in @code{LANG}.
 1023: 
 1024: @item
 1025: @cindex @code{GFORTHSYSTEMPREFIX} -- environment variable
 1026: 
 1027: @code{GFORTHSYSTEMPREFIX} -- specifies what to prepend to the argument
 1028: of @code{system} before passing it to C's @code{system()}.  Default:
 1029: @code{"./$COMSPEC /c "} on Windows, @code{""} on other OSs.  The prefix
 1030: and the command are directly concatenated, so if a space between them is
 1031: necessary, append it to the prefix.
 1032: 
 1033: @item
 1034: @cindex @code{GFORTH} -- environment variable
 1035: @code{GFORTH} -- used by @file{gforthmi}, @xref{gforthmi}.
 1036: 
 1037: @item
 1038: @cindex @code{GFORTHD} -- environment variable
 1039: @code{GFORTHD} -- used by @file{gforthmi}, @xref{gforthmi}.
 1040: 
 1041: @item
 1042: @cindex @code{TMP}, @code{TEMP} - environment variable
 1043: @code{TMP}, @code{TEMP} - (non-Unix systems only) used as a potential
 1044: location for the history file.
 1045: @end itemize
 1046: 
 1047: @comment also POSIXELY_CORRECT LINES COLUMNS HOME but no interest in
 1048: @comment mentioning these.
 1049: 
 1050: All the Gforth environment variables default to sensible values if they
 1051: are not set.
 1052: 
 1053: 
 1054: @comment ----------------------------------------------
 1055: @node Gforth Files, Gforth in pipes, Environment variables, Gforth Environment
 1056: @section Gforth files
 1057: @cindex Gforth files
 1058: 
 1059: When you install Gforth on a Unix system, it installs files in these
 1060: locations by default:
 1061: 
 1062: @itemize @bullet
 1063: @item
 1064: @file{/usr/local/bin/gforth}
 1065: @item
 1066: @file{/usr/local/bin/gforthmi}
 1067: @item
 1068: @file{/usr/local/man/man1/gforth.1} - man page.
 1069: @item
 1070: @file{/usr/local/info} - the Info version of this manual.
 1071: @item
 1072: @file{/usr/local/lib/gforth/<version>/...} - Gforth @file{.fi} files.
 1073: @item
 1074: @file{/usr/local/share/gforth/<version>/TAGS} - Emacs TAGS file.
 1075: @item
 1076: @file{/usr/local/share/gforth/<version>/...} - Gforth source files.
 1077: @item
 1078: @file{.../emacs/site-lisp/gforth.el} - Emacs gforth mode.
 1079: @end itemize
 1080: 
 1081: You can select different places for installation by using
 1082: @code{configure} options (listed with @code{configure --help}).
 1083: 
 1084: @comment ----------------------------------------------
 1085: @node Gforth in pipes, Startup speed, Gforth Files, Gforth Environment
 1086: @section Gforth in pipes
 1087: @cindex pipes, Gforth as part of
 1088: 
 1089: Gforth can be used in pipes created elsewhere (described here).  It can
 1090: also create pipes on its own (@pxref{Pipes}).
 1091: 
 1092: @cindex input from pipes
 1093: If you pipe into Gforth, your program should read with @code{read-file}
 1094: or @code{read-line} from @code{stdin} (@pxref{General files}).
 1095: @code{Key} does not recognize the end of input.  Words like
 1096: @code{accept} echo the input and are therefore usually not useful for
 1097: reading from a pipe.  You have to invoke the Forth program with an OS
 1098: command-line option, as you have no chance to use the Forth command line
 1099: (the text interpreter would try to interpret the pipe input).
 1100: 
 1101: @cindex output in pipes
 1102: You can output to a pipe with @code{type}, @code{emit}, @code{cr} etc.
 1103: 
 1104: @cindex silent exiting from Gforth
 1105: When you write to a pipe that has been closed at the other end, Gforth
 1106: receives a SIGPIPE signal (``pipe broken'').  Gforth translates this
 1107: into the exception @code{broken-pipe-error}.  If your application does
 1108: not catch that exception, the system catches it and exits, usually
 1109: silently (unless you were working on the Forth command line; then it
 1110: prints an error message and exits).  This is usually the desired
 1111: behaviour.
 1112: 
 1113: If you do not like this behaviour, you have to catch the exception
 1114: yourself, and react to it.
 1115: 
 1116: Here's an example of an invocation of Gforth that is usable in a pipe:
 1117: 
 1118: @example
 1119: gforth -e ": foo begin pad dup 10 stdin read-file throw dup while \
 1120:  type repeat ; foo bye"
 1121: @end example
 1122: 
 1123: This example just copies the input verbatim to the output.  A very
 1124: simple pipe containing this example looks like this:
 1125: 
 1126: @example
 1127: cat startup.fs |
 1128: gforth -e ": foo begin pad dup 80 stdin read-file throw dup while \
 1129:  type repeat ; foo bye"|
 1130: head
 1131: @end example
 1132: 
 1133: @cindex stderr and pipes
 1134: Pipes involving Gforth's @code{stderr} output do not work.
 1135: 
 1136: @comment ----------------------------------------------
 1137: @node Startup speed,  , Gforth in pipes, Gforth Environment
 1138: @section Startup speed
 1139: @cindex Startup speed
 1140: @cindex speed, startup
 1141: 
 1142: If Gforth is used for CGI scripts or in shell scripts, its startup
 1143: speed may become a problem.  On a 3GHz Core 2 Duo E8400 under 64-bit
 1144: Linux 2.6.27.8 with libc-2.7, @code{gforth-fast -e bye} takes 13.1ms
 1145: user and 1.2ms system time (@code{gforth -e bye} is faster on startup
 1146: with about 3.4ms user time and 1.2ms system time, because it subsumes
 1147: some of the options discussed below).
 1148: 
 1149: If startup speed is a problem, you may consider the following ways to
 1150: improve it; or you may consider ways to reduce the number of startups
 1151: (for example, by using Fast-CGI).  Note that the first steps below
 1152: improve the startup time at the cost of run-time (including
 1153: compile-time), so whether they are profitable depends on the balance
 1154: of these times in your application.
 1155: 
 1156: An easy step that influences Gforth startup speed is the use of a
 1157: number of options that increase run-time, but decrease image-loading
 1158: time.
 1159: 
 1160: The first of these that you should try is @code{--ss-number=0
 1161: --ss-states=1} because this option buys relatively little run-time
 1162: speedup and costs quite a bit of time at startup.  @code{gforth-fast
 1163: --ss-number=0 --ss-states=1 -e bye} takes about 2.8ms user and 1.5ms
 1164: system time.
 1165: 
 1166: The next option is @code{--no-dynamic} which has a substantial impact
 1167: on run-time (about a factor of 2 on several platforms), but still
 1168: makes startup speed a little faster: @code{gforth-fast --ss-number=0
 1169: --ss-states=1 --no-dynamic -e bye} consumes about 2.6ms user and 1.2ms
 1170: system time.
 1171: 
 1172: The next step to improve startup speed is to use a data-relocatable
 1173: image (@pxref{Data-Relocatable Image Files}).  This avoids the
 1174: relocation cost for the code in the image (but not for the data).
 1175: Note that the image is then specific to the particular binary you are
 1176: using (i.e., whether it is @code{gforth}, @code{gforth-fast}, and even
 1177: the particular build).  You create the data-relocatable image that
 1178: works with @code{./gforth-fast} with @code{GFORTHD="./gforth-fast
 1179: --no-dynamic" gforthmi gforthdr.fi} (the @code{--no-dynamic} is
 1180: required here or the image will not work).  And you run it with
 1181: @code{gforth-fast -i gforthdr.fi ... -e bye} (the flags discussed
 1182: above don't matter here, because they only come into play on
 1183: relocatable code).  @code{gforth-fast -i gforthdr.fi -e bye} takes
 1184: about 1.1ms user and 1.2ms system time.
 1185: 
 1186: One step further is to avoid all relocation cost and part of the
 1187: copy-on-write cost through using a non-relocatable image
 1188: (@pxref{Non-Relocatable Image Files}).  However, this has the
 1189: disadvantage that it does not work on operating systems with address
 1190: space randomization (the default in, e.g., Linux nowadays), or if the
 1191: dictionary moves for any other reason (e.g., because of a change of
 1192: the OS kernel or an updated library), so we cannot really recommend
 1193: it.  You create a non-relocatable image with @code{gforth-fast
 1194: --no-dynamic -e "savesystem gforthnr.fi bye"} (the @code{--no-dynamic}
 1195: is required here, too).  And you run it with @code{gforth-fast -i
 1196: gforthnr.fi ... -e bye} (again the flags discussed above don't
 1197: matter).  @code{gforth-fast -i gforthdr.fi -e bye} takes
 1198: about 0.9ms user and 0.9ms system time.
 1199: 
 1200: If the script you want to execute contains a significant amount of
 1201: code, it may be profitable to compile it into the image to avoid the
 1202: cost of compiling it at startup time.
 1203: 
 1204: @c ******************************************************************
 1205: @node Tutorial, Introduction, Gforth Environment, Top
 1206: @chapter Forth Tutorial
 1207: @cindex Tutorial
 1208: @cindex Forth Tutorial
 1209: 
 1210: @c Topics from nac's Introduction that could be mentioned:
 1211: @c press <ret> after each line
 1212: @c Prompt
 1213: @c numbers vs. words in dictionary on text interpretation
 1214: @c what happens on redefinition
 1215: @c parsing words (in particular, defining words)
 1216: 
 1217: The difference of this chapter from the Introduction
 1218: (@pxref{Introduction}) is that this tutorial is more fast-paced, should
 1219: be used while sitting in front of a computer, and covers much more
 1220: material, but does not explain how the Forth system works.
 1221: 
 1222: This tutorial can be used with any ANS-compliant Forth; any
 1223: Gforth-specific features are marked as such and you can skip them if
 1224: you work with another Forth.  This tutorial does not explain all
 1225: features of Forth, just enough to get you started and give you some
 1226: ideas about the facilities available in Forth.  Read the rest of the
 1227: manual when you are through this.
 1228: 
 1229: The intended way to use this tutorial is that you work through it while
 1230: sitting in front of the console, take a look at the examples and predict
 1231: what they will do, then try them out; if the outcome is not as expected,
 1232: find out why (e.g., by trying out variations of the example), so you
 1233: understand what's going on.  There are also some assignments that you
 1234: should solve.
 1235: 
 1236: This tutorial assumes that you have programmed before and know what,
 1237: e.g., a loop is.
 1238: 
 1239: @c !! explain compat library
 1240: 
 1241: @menu
 1242: * Starting Gforth Tutorial::    
 1243: * Syntax Tutorial::             
 1244: * Crash Course Tutorial::       
 1245: * Stack Tutorial::              
 1246: * Arithmetics Tutorial::        
 1247: * Stack Manipulation Tutorial::  
 1248: * Using files for Forth code Tutorial::  
 1249: * Comments Tutorial::           
 1250: * Colon Definitions Tutorial::  
 1251: * Decompilation Tutorial::      
 1252: * Stack-Effect Comments Tutorial::  
 1253: * Types Tutorial::              
 1254: * Factoring Tutorial::          
 1255: * Designing the stack effect Tutorial::  
 1256: * Local Variables Tutorial::    
 1257: * Conditional execution Tutorial::  
 1258: * Flags and Comparisons Tutorial::  
 1259: * General Loops Tutorial::      
 1260: * Counted loops Tutorial::      
 1261: * Recursion Tutorial::          
 1262: * Leaving definitions or loops Tutorial::  
 1263: * Return Stack Tutorial::       
 1264: * Memory Tutorial::             
 1265: * Characters and Strings Tutorial::  
 1266: * Alignment Tutorial::          
 1267: * Floating Point Tutorial::     
 1268: * Files Tutorial::              
 1269: * Interpretation and Compilation Semantics and Immediacy Tutorial::  
 1270: * Execution Tokens Tutorial::   
 1271: * Exceptions Tutorial::         
 1272: * Defining Words Tutorial::     
 1273: * Arrays and Records Tutorial::  
 1274: * POSTPONE Tutorial::           
 1275: * Literal Tutorial::            
 1276: * Advanced macros Tutorial::    
 1277: * Compilation Tokens Tutorial::  
 1278: * Wordlists and Search Order Tutorial::  
 1279: @end menu
 1280: 
 1281: @node Starting Gforth Tutorial, Syntax Tutorial, Tutorial, Tutorial
 1282: @section Starting Gforth
 1283: @cindex starting Gforth tutorial
 1284: You can start Gforth by typing its name:
 1285: 
 1286: @example
 1287: gforth
 1288: @end example
 1289: 
 1290: That puts you into interactive mode; you can leave Gforth by typing
 1291: @code{bye}.  While in Gforth, you can edit the command line and access
 1292: the command line history with cursor keys, similar to bash.
 1293: 
 1294: 
 1295: @node Syntax Tutorial, Crash Course Tutorial, Starting Gforth Tutorial, Tutorial
 1296: @section Syntax
 1297: @cindex syntax tutorial
 1298: 
 1299: A @dfn{word} is a sequence of arbitrary characters (except white
 1300: space).  Words are separated by white space.  E.g., each of the
 1301: following lines contains exactly one word:
 1302: 
 1303: @example
 1304: word
 1305: !@@#$%^&*()
 1306: 1234567890
 1307: 5!a
 1308: @end example
 1309: 
 1310: A frequent beginner's error is to leave out necessary white space,
 1311: resulting in an error like @samp{Undefined word}; so if you see such an
 1312: error, check if you have put spaces wherever necessary.
 1313: 
 1314: @example
 1315: ." hello, world" \ correct
 1316: ."hello, world"  \ gives an "Undefined word" error
 1317: @end example
 1318: 
 1319: Gforth and most other Forth systems ignore differences in case (they are
 1320: case-insensitive), i.e., @samp{word} is the same as @samp{Word}.  If
 1321: your system is case-sensitive, you may have to type all the examples
 1322: given here in upper case.
 1323: 
 1324: 
 1325: @node Crash Course Tutorial, Stack Tutorial, Syntax Tutorial, Tutorial
 1326: @section Crash Course
 1327: 
 1328: Forth does not prevent you from shooting yourself in the foot.  Let's
 1329: try a few ways to crash Gforth:
 1330: 
 1331: @example
 1332: 0 0 !
 1333: here execute
 1334: ' catch >body 20 erase abort
 1335: ' (quit) >body 20 erase
 1336: @end example
 1337: 
 1338: The last two examples are guaranteed to destroy important parts of
 1339: Gforth (and most other systems), so you better leave Gforth afterwards
 1340: (if it has not finished by itself).  On some systems you may have to
 1341: kill gforth from outside (e.g., in Unix with @code{kill}).
 1342: 
 1343: You will find out later what these lines do and then you will get an
 1344: idea why they produce crashes.
 1345: 
 1346: Now that you know how to produce crashes (and that there's not much to
 1347: them), let's learn how to produce meaningful programs.
 1348: 
 1349: 
 1350: @node Stack Tutorial, Arithmetics Tutorial, Crash Course Tutorial, Tutorial
 1351: @section Stack
 1352: @cindex stack tutorial
 1353: 
 1354: The most obvious feature of Forth is the stack.  When you type in a
 1355: number, it is pushed on the stack.  You can display the contents of the
 1356: stack with @code{.s}.
 1357: 
 1358: @example
 1359: 1 2 .s
 1360: 3 .s
 1361: @end example
 1362: 
 1363: @code{.s} displays the top-of-stack to the right, i.e., the numbers
 1364: appear in @code{.s} output as they appeared in the input.
 1365: 
 1366: You can print the top element of the stack with @code{.}.
 1367: 
 1368: @example
 1369: 1 2 3 . . .
 1370: @end example
 1371: 
 1372: In general, words consume their stack arguments (@code{.s} is an
 1373: exception).
 1374: 
 1375: @quotation Assignment
 1376: What does the stack contain after @code{5 6 7 .}?
 1377: @end quotation
 1378: 
 1379: 
 1380: @node Arithmetics Tutorial, Stack Manipulation Tutorial, Stack Tutorial, Tutorial
 1381: @section Arithmetics
 1382: @cindex arithmetics tutorial
 1383: 
 1384: The words @code{+}, @code{-}, @code{*}, @code{/}, and @code{mod} always
 1385: operate on the top two stack items:
 1386: 
 1387: @example
 1388: 2 2 .s
 1389: + .s
 1390: .
 1391: 2 1 - .
 1392: 7 3 mod .
 1393: @end example
 1394: 
 1395: The operands of @code{-}, @code{/}, and @code{mod} are in the same order
 1396: as in the corresponding infix expression (this is generally the case in
 1397: Forth).
 1398: 
 1399: Parentheses are superfluous (and not available), because the order of
 1400: the words unambiguously determines the order of evaluation and the
 1401: operands:
 1402: 
 1403: @example
 1404: 3 4 + 5 * .
 1405: 3 4 5 * + .
 1406: @end example
 1407: 
 1408: @quotation Assignment
 1409: What are the infix expressions corresponding to the Forth code above?
 1410: Write @code{6-7*8+9} in Forth notation@footnote{This notation is also
 1411: known as Postfix or RPN (Reverse Polish Notation).}.
 1412: @end quotation
 1413: 
 1414: To change the sign, use @code{negate}:
 1415: 
 1416: @example
 1417: 2 negate .
 1418: @end example
 1419: 
 1420: @quotation Assignment
 1421: Convert -(-3)*4-5 to Forth.
 1422: @end quotation
 1423: 
 1424: @code{/mod} performs both @code{/} and @code{mod}.
 1425: 
 1426: @example
 1427: 7 3 /mod . .
 1428: @end example
 1429: 
 1430: Reference: @ref{Arithmetic}.
 1431: 
 1432: 
 1433: @node Stack Manipulation Tutorial, Using files for Forth code Tutorial, Arithmetics Tutorial, Tutorial
 1434: @section Stack Manipulation
 1435: @cindex stack manipulation tutorial
 1436: 
 1437: Stack manipulation words rearrange the data on the stack.
 1438: 
 1439: @example
 1440: 1 .s drop .s
 1441: 1 .s dup .s drop drop .s
 1442: 1 2 .s over .s drop drop drop
 1443: 1 2 .s swap .s drop drop
 1444: 1 2 3 .s rot .s drop drop drop
 1445: @end example
 1446: 
 1447: These are the most important stack manipulation words.  There are also
 1448: variants that manipulate twice as many stack items:
 1449: 
 1450: @example
 1451: 1 2 3 4 .s 2swap .s 2drop 2drop
 1452: @end example
 1453: 
 1454: Two more stack manipulation words are:
 1455: 
 1456: @example
 1457: 1 2 .s nip .s drop
 1458: 1 2 .s tuck .s 2drop drop
 1459: @end example
 1460: 
 1461: @quotation Assignment
 1462: Replace @code{nip} and @code{tuck} with combinations of other stack
 1463: manipulation words.
 1464: 
 1465: @example
 1466: Given:          How do you get:
 1467: 1 2 3           3 2 1           
 1468: 1 2 3           1 2 3 2                 
 1469: 1 2 3           1 2 3 3                 
 1470: 1 2 3           1 3 3           
 1471: 1 2 3           2 1 3           
 1472: 1 2 3 4         4 3 2 1         
 1473: 1 2 3           1 2 3 1 2 3             
 1474: 1 2 3 4         1 2 3 4 1 2             
 1475: 1 2 3
 1476: 1 2 3           1 2 3 4                 
 1477: 1 2 3           1 3             
 1478: @end example
 1479: @end quotation
 1480: 
 1481: @example
 1482: 5 dup * .
 1483: @end example
 1484: 
 1485: @quotation Assignment
 1486: Write 17^3 and 17^4 in Forth, without writing @code{17} more than once.
 1487: Write a piece of Forth code that expects two numbers on the stack
 1488: (@var{a} and @var{b}, with @var{b} on top) and computes
 1489: @code{(a-b)(a+1)}.
 1490: @end quotation
 1491: 
 1492: Reference: @ref{Stack Manipulation}.
 1493: 
 1494: 
 1495: @node Using files for Forth code Tutorial, Comments Tutorial, Stack Manipulation Tutorial, Tutorial
 1496: @section Using files for Forth code
 1497: @cindex loading Forth code, tutorial
 1498: @cindex files containing Forth code, tutorial
 1499: 
 1500: While working at the Forth command line is convenient for one-line
 1501: examples and short one-off code, you probably want to store your source
 1502: code in files for convenient editing and persistence.  You can use your
 1503: favourite editor (Gforth includes Emacs support, @pxref{Emacs and
 1504: Gforth}) to create @var{file.fs} and use
 1505: 
 1506: @example
 1507: s" @var{file.fs}" included
 1508: @end example
 1509: 
 1510: to load it into your Forth system.  The file name extension I use for
 1511: Forth files is @samp{.fs}.
 1512: 
 1513: You can easily start Gforth with some files loaded like this:
 1514: 
 1515: @example
 1516: gforth @var{file1.fs} @var{file2.fs}
 1517: @end example
 1518: 
 1519: If an error occurs during loading these files, Gforth terminates,
 1520: whereas an error during @code{INCLUDED} within Gforth usually gives you
 1521: a Gforth command line.  Starting the Forth system every time gives you a
 1522: clean start every time, without interference from the results of earlier
 1523: tries.
 1524: 
 1525: I often put all the tests in a file, then load the code and run the
 1526: tests with
 1527: 
 1528: @example
 1529: gforth @var{code.fs} @var{tests.fs} -e bye
 1530: @end example
 1531: 
 1532: (often by performing this command with @kbd{C-x C-e} in Emacs).  The
 1533: @code{-e bye} ensures that Gforth terminates afterwards so that I can
 1534: restart this command without ado.
 1535: 
 1536: The advantage of this approach is that the tests can be repeated easily
 1537: every time the program ist changed, making it easy to catch bugs
 1538: introduced by the change.
 1539: 
 1540: Reference: @ref{Forth source files}.
 1541: 
 1542: 
 1543: @node Comments Tutorial, Colon Definitions Tutorial, Using files for Forth code Tutorial, Tutorial
 1544: @section Comments
 1545: @cindex comments tutorial
 1546: 
 1547: @example
 1548: \ That's a comment; it ends at the end of the line
 1549: ( Another comment; it ends here: )  .s
 1550: @end example
 1551: 
 1552: @code{\} and @code{(} are ordinary Forth words and therefore have to be
 1553: separated with white space from the following text.
 1554: 
 1555: @example
 1556: \This gives an "Undefined word" error
 1557: @end example
 1558: 
 1559: The first @code{)} ends a comment started with @code{(}, so you cannot
 1560: nest @code{(}-comments; and you cannot comment out text containing a
 1561: @code{)} with @code{( ... )}@footnote{therefore it's a good idea to
 1562: avoid @code{)} in word names.}.
 1563: 
 1564: I use @code{\}-comments for descriptive text and for commenting out code
 1565: of one or more line; I use @code{(}-comments for describing the stack
 1566: effect, the stack contents, or for commenting out sub-line pieces of
 1567: code.
 1568: 
 1569: The Emacs mode @file{gforth.el} (@pxref{Emacs and Gforth}) supports
 1570: these uses by commenting out a region with @kbd{C-x \}, uncommenting a
 1571: region with @kbd{C-u C-x \}, and filling a @code{\}-commented region
 1572: with @kbd{M-q}.
 1573: 
 1574: Reference: @ref{Comments}.
 1575: 
 1576: 
 1577: @node Colon Definitions Tutorial, Decompilation Tutorial, Comments Tutorial, Tutorial
 1578: @section Colon Definitions
 1579: @cindex colon definitions, tutorial
 1580: @cindex definitions, tutorial
 1581: @cindex procedures, tutorial
 1582: @cindex functions, tutorial
 1583: 
 1584: are similar to procedures and functions in other programming languages.
 1585: 
 1586: @example
 1587: : squared ( n -- n^2 )
 1588:    dup * ;
 1589: 5 squared .
 1590: 7 squared .
 1591: @end example
 1592: 
 1593: @code{:} starts the colon definition; its name is @code{squared}.  The
 1594: following comment describes its stack effect.  The words @code{dup *}
 1595: are not executed, but compiled into the definition.  @code{;} ends the
 1596: colon definition.
 1597: 
 1598: The newly-defined word can be used like any other word, including using
 1599: it in other definitions:
 1600: 
 1601: @example
 1602: : cubed ( n -- n^3 )
 1603:    dup squared * ;
 1604: -5 cubed .
 1605: : fourth-power ( n -- n^4 )
 1606:    squared squared ;
 1607: 3 fourth-power .
 1608: @end example
 1609: 
 1610: @quotation Assignment
 1611: Write colon definitions for @code{nip}, @code{tuck}, @code{negate}, and
 1612: @code{/mod} in terms of other Forth words, and check if they work (hint:
 1613: test your tests on the originals first).  Don't let the
 1614: @samp{redefined}-Messages spook you, they are just warnings.
 1615: @end quotation
 1616: 
 1617: Reference: @ref{Colon Definitions}.
 1618: 
 1619: 
 1620: @node Decompilation Tutorial, Stack-Effect Comments Tutorial, Colon Definitions Tutorial, Tutorial
 1621: @section Decompilation
 1622: @cindex decompilation tutorial
 1623: @cindex see tutorial
 1624: 
 1625: You can decompile colon definitions with @code{see}:
 1626: 
 1627: @example
 1628: see squared
 1629: see cubed
 1630: @end example
 1631: 
 1632: In Gforth @code{see} shows you a reconstruction of the source code from
 1633: the executable code.  Informations that were present in the source, but
 1634: not in the executable code, are lost (e.g., comments).
 1635: 
 1636: You can also decompile the predefined words:
 1637: 
 1638: @example
 1639: see .
 1640: see +
 1641: @end example
 1642: 
 1643: 
 1644: @node Stack-Effect Comments Tutorial, Types Tutorial, Decompilation Tutorial, Tutorial
 1645: @section Stack-Effect Comments
 1646: @cindex stack-effect comments, tutorial
 1647: @cindex --, tutorial
 1648: By convention the comment after the name of a definition describes the
 1649: stack effect: The part in front of the @samp{--} describes the state of
 1650: the stack before the execution of the definition, i.e., the parameters
 1651: that are passed into the colon definition; the part behind the @samp{--}
 1652: is the state of the stack after the execution of the definition, i.e.,
 1653: the results of the definition.  The stack comment only shows the top
 1654: stack items that the definition accesses and/or changes.
 1655: 
 1656: You should put a correct stack effect on every definition, even if it is
 1657: just @code{( -- )}.  You should also add some descriptive comment to
 1658: more complicated words (I usually do this in the lines following
 1659: @code{:}).  If you don't do this, your code becomes unreadable (because
 1660: you have to work through every definition before you can understand
 1661: any).
 1662: 
 1663: @quotation Assignment
 1664: The stack effect of @code{swap} can be written like this: @code{x1 x2 --
 1665: x2 x1}.  Describe the stack effect of @code{-}, @code{drop}, @code{dup},
 1666: @code{over}, @code{rot}, @code{nip}, and @code{tuck}.  Hint: When you
 1667: are done, you can compare your stack effects to those in this manual
 1668: (@pxref{Word Index}).
 1669: @end quotation
 1670: 
 1671: Sometimes programmers put comments at various places in colon
 1672: definitions that describe the contents of the stack at that place (stack
 1673: comments); i.e., they are like the first part of a stack-effect
 1674: comment. E.g.,
 1675: 
 1676: @example
 1677: : cubed ( n -- n^3 )
 1678:    dup squared  ( n n^2 ) * ;
 1679: @end example
 1680: 
 1681: In this case the stack comment is pretty superfluous, because the word
 1682: is simple enough.  If you think it would be a good idea to add such a
 1683: comment to increase readability, you should also consider factoring the
 1684: word into several simpler words (@pxref{Factoring Tutorial,,
 1685: Factoring}), which typically eliminates the need for the stack comment;
 1686: however, if you decide not to refactor it, then having such a comment is
 1687: better than not having it.
 1688: 
 1689: The names of the stack items in stack-effect and stack comments in the
 1690: standard, in this manual, and in many programs specify the type through
 1691: a type prefix, similar to Fortran and Hungarian notation.  The most
 1692: frequent prefixes are:
 1693: 
 1694: @table @code
 1695: @item n
 1696: signed integer
 1697: @item u
 1698: unsigned integer
 1699: @item c
 1700: character
 1701: @item f
 1702: Boolean flags, i.e. @code{false} or @code{true}.
 1703: @item a-addr,a-
 1704: Cell-aligned address
 1705: @item c-addr,c-
 1706: Char-aligned address (note that a Char may have two bytes in Windows NT)
 1707: @item xt
 1708: Execution token, same size as Cell
 1709: @item w,x
 1710: Cell, can contain an integer or an address.  It usually takes 32, 64 or
 1711: 16 bits (depending on your platform and Forth system). A cell is more
 1712: commonly known as machine word, but the term @emph{word} already means
 1713: something different in Forth.
 1714: @item d
 1715: signed double-cell integer
 1716: @item ud
 1717: unsigned double-cell integer
 1718: @item r
 1719: Float (on the FP stack)
 1720: @end table
 1721: 
 1722: You can find a more complete list in @ref{Notation}.
 1723: 
 1724: @quotation Assignment
 1725: Write stack-effect comments for all definitions you have written up to
 1726: now.
 1727: @end quotation
 1728: 
 1729: 
 1730: @node Types Tutorial, Factoring Tutorial, Stack-Effect Comments Tutorial, Tutorial
 1731: @section Types
 1732: @cindex types tutorial
 1733: 
 1734: In Forth the names of the operations are not overloaded; so similar
 1735: operations on different types need different names; e.g., @code{+} adds
 1736: integers, and you have to use @code{f+} to add floating-point numbers.
 1737: The following prefixes are often used for related operations on
 1738: different types:
 1739: 
 1740: @table @code
 1741: @item (none)
 1742: signed integer
 1743: @item u
 1744: unsigned integer
 1745: @item c
 1746: character
 1747: @item d
 1748: signed double-cell integer
 1749: @item ud, du
 1750: unsigned double-cell integer
 1751: @item 2
 1752: two cells (not-necessarily double-cell numbers)
 1753: @item m, um
 1754: mixed single-cell and double-cell operations
 1755: @item f
 1756: floating-point (note that in stack comments @samp{f} represents flags,
 1757: and @samp{r} represents FP numbers; also, you need to include the
 1758: exponent part in literal FP numbers, @pxref{Floating Point Tutorial}).
 1759: @end table
 1760: 
 1761: If there are no differences between the signed and the unsigned variant
 1762: (e.g., for @code{+}), there is only the prefix-less variant.
 1763: 
 1764: Forth does not perform type checking, neither at compile time, nor at
 1765: run time.  If you use the wrong operation, the data are interpreted
 1766: incorrectly:
 1767: 
 1768: @example
 1769: -1 u.
 1770: @end example
 1771: 
 1772: If you have only experience with type-checked languages until now, and
 1773: have heard how important type-checking is, don't panic!  In my
 1774: experience (and that of other Forthers), type errors in Forth code are
 1775: usually easy to find (once you get used to it), the increased vigilance
 1776: of the programmer tends to catch some harder errors in addition to most
 1777: type errors, and you never have to work around the type system, so in
 1778: most situations the lack of type-checking seems to be a win (projects to
 1779: add type checking to Forth have not caught on).
 1780: 
 1781: 
 1782: @node Factoring Tutorial, Designing the stack effect Tutorial, Types Tutorial, Tutorial
 1783: @section Factoring
 1784: @cindex factoring tutorial
 1785: 
 1786: If you try to write longer definitions, you will soon find it hard to
 1787: keep track of the stack contents.  Therefore, good Forth programmers
 1788: tend to write only short definitions (e.g., three lines).  The art of
 1789: finding meaningful short definitions is known as factoring (as in
 1790: factoring polynomials).
 1791: 
 1792: Well-factored programs offer additional advantages: smaller, more
 1793: general words, are easier to test and debug and can be reused more and
 1794: better than larger, specialized words.
 1795: 
 1796: So, if you run into difficulties with stack management, when writing
 1797: code, try to define meaningful factors for the word, and define the word
 1798: in terms of those.  Even if a factor contains only two words, it is
 1799: often helpful.
 1800: 
 1801: Good factoring is not easy, and it takes some practice to get the knack
 1802: for it; but even experienced Forth programmers often don't find the
 1803: right solution right away, but only when rewriting the program.  So, if
 1804: you don't come up with a good solution immediately, keep trying, don't
 1805: despair.
 1806: 
 1807: @c example !!
 1808: 
 1809: 
 1810: @node Designing the stack effect Tutorial, Local Variables Tutorial, Factoring Tutorial, Tutorial
 1811: @section Designing the stack effect
 1812: @cindex Stack effect design, tutorial
 1813: @cindex design of stack effects, tutorial
 1814: 
 1815: In other languages you can use an arbitrary order of parameters for a
 1816: function; and since there is only one result, you don't have to deal with
 1817: the order of results, either.
 1818: 
 1819: In Forth (and other stack-based languages, e.g., PostScript) the
 1820: parameter and result order of a definition is important and should be
 1821: designed well.  The general guideline is to design the stack effect such
 1822: that the word is simple to use in most cases, even if that complicates
 1823: the implementation of the word.  Some concrete rules are:
 1824: 
 1825: @itemize @bullet
 1826: 
 1827: @item
 1828: Words consume all of their parameters (e.g., @code{.}).
 1829: 
 1830: @item
 1831: If there is a convention on the order of parameters (e.g., from
 1832: mathematics or another programming language), stick with it (e.g.,
 1833: @code{-}).
 1834: 
 1835: @item
 1836: If one parameter usually requires only a short computation (e.g., it is
 1837: a constant), pass it on the top of the stack.  Conversely, parameters
 1838: that usually require a long sequence of code to compute should be passed
 1839: as the bottom (i.e., first) parameter.  This makes the code easier to
 1840: read, because the reader does not need to keep track of the bottom item
 1841: through a long sequence of code (or, alternatively, through stack
 1842: manipulations). E.g., @code{!} (store, @pxref{Memory}) expects the
 1843: address on top of the stack because it is usually simpler to compute
 1844: than the stored value (often the address is just a variable).
 1845: 
 1846: @item
 1847: Similarly, results that are usually consumed quickly should be returned
 1848: on the top of stack, whereas a result that is often used in long
 1849: computations should be passed as bottom result.  E.g., the file words
 1850: like @code{open-file} return the error code on the top of stack, because
 1851: it is usually consumed quickly by @code{throw}; moreover, the error code
 1852: has to be checked before doing anything with the other results.
 1853: 
 1854: @end itemize
 1855: 
 1856: These rules are just general guidelines, don't lose sight of the overall
 1857: goal to make the words easy to use.  E.g., if the convention rule
 1858: conflicts with the computation-length rule, you might decide in favour
 1859: of the convention if the word will be used rarely, and in favour of the
 1860: computation-length rule if the word will be used frequently (because
 1861: with frequent use the cost of breaking the computation-length rule would
 1862: be quite high, and frequent use makes it easier to remember an
 1863: unconventional order).
 1864: 
 1865: @c example !! structure package
 1866: 
 1867: 
 1868: @node Local Variables Tutorial, Conditional execution Tutorial, Designing the stack effect Tutorial, Tutorial
 1869: @section Local Variables
 1870: @cindex local variables, tutorial
 1871: 
 1872: You can define local variables (@emph{locals}) in a colon definition:
 1873: 
 1874: @example
 1875: : swap @{ a b -- b a @}
 1876:   b a ;
 1877: 1 2 swap .s 2drop
 1878: @end example
 1879: 
 1880: (If your Forth system does not support this syntax, include
 1881: @file{compat/anslocal.fs} first).
 1882: 
 1883: In this example @code{@{ a b -- b a @}} is the locals definition; it
 1884: takes two cells from the stack, puts the top of stack in @code{b} and
 1885: the next stack element in @code{a}.  @code{--} starts a comment ending
 1886: with @code{@}}.  After the locals definition, using the name of the
 1887: local will push its value on the stack.  You can leave the comment
 1888: part (@code{-- b a}) away:
 1889: 
 1890: @example
 1891: : swap ( x1 x2 -- x2 x1 )
 1892:   @{ a b @} b a ;
 1893: @end example
 1894: 
 1895: In Gforth you can have several locals definitions, anywhere in a colon
 1896: definition; in contrast, in a standard program you can have only one
 1897: locals definition per colon definition, and that locals definition must
 1898: be outside any control structure.
 1899: 
 1900: With locals you can write slightly longer definitions without running
 1901: into stack trouble.  However, I recommend trying to write colon
 1902: definitions without locals for exercise purposes to help you gain the
 1903: essential factoring skills.
 1904: 
 1905: @quotation Assignment
 1906: Rewrite your definitions until now with locals
 1907: @end quotation
 1908: 
 1909: Reference: @ref{Locals}.
 1910: 
 1911: 
 1912: @node Conditional execution Tutorial, Flags and Comparisons Tutorial, Local Variables Tutorial, Tutorial
 1913: @section Conditional execution
 1914: @cindex conditionals, tutorial
 1915: @cindex if, tutorial
 1916: 
 1917: In Forth you can use control structures only inside colon definitions.
 1918: An @code{if}-structure looks like this:
 1919: 
 1920: @example
 1921: : abs ( n1 -- +n2 )
 1922:     dup 0 < if
 1923:         negate
 1924:     endif ;
 1925: 5 abs .
 1926: -5 abs .
 1927: @end example
 1928: 
 1929: @code{if} takes a flag from the stack.  If the flag is non-zero (true),
 1930: the following code is performed, otherwise execution continues after the
 1931: @code{endif} (or @code{else}).  @code{<} compares the top two stack
 1932: elements and produces a flag:
 1933: 
 1934: @example
 1935: 1 2 < .
 1936: 2 1 < .
 1937: 1 1 < .
 1938: @end example
 1939: 
 1940: Actually the standard name for @code{endif} is @code{then}.  This
 1941: tutorial presents the examples using @code{endif}, because this is often
 1942: less confusing for people familiar with other programming languages
 1943: where @code{then} has a different meaning.  If your system does not have
 1944: @code{endif}, define it with
 1945: 
 1946: @example
 1947: : endif postpone then ; immediate
 1948: @end example
 1949: 
 1950: You can optionally use an @code{else}-part:
 1951: 
 1952: @example
 1953: : min ( n1 n2 -- n )
 1954:   2dup < if
 1955:     drop
 1956:   else
 1957:     nip
 1958:   endif ;
 1959: 2 3 min .
 1960: 3 2 min .
 1961: @end example
 1962: 
 1963: @quotation Assignment
 1964: Write @code{min} without @code{else}-part (hint: what's the definition
 1965: of @code{nip}?).
 1966: @end quotation
 1967: 
 1968: Reference: @ref{Selection}.
 1969: 
 1970: 
 1971: @node Flags and Comparisons Tutorial, General Loops Tutorial, Conditional execution Tutorial, Tutorial
 1972: @section Flags and Comparisons
 1973: @cindex flags tutorial
 1974: @cindex comparison tutorial
 1975: 
 1976: In a false-flag all bits are clear (0 when interpreted as integer).  In
 1977: a canonical true-flag all bits are set (-1 as a twos-complement signed
 1978: integer); in many contexts (e.g., @code{if}) any non-zero value is
 1979: treated as true flag.
 1980: 
 1981: @example
 1982: false .
 1983: true .
 1984: true hex u. decimal
 1985: @end example
 1986: 
 1987: Comparison words produce canonical flags:
 1988: 
 1989: @example
 1990: 1 1 = .
 1991: 1 0= .
 1992: 0 1 < .
 1993: 0 0 < .
 1994: -1 1 u< . \ type error, u< interprets -1 as large unsigned number
 1995: -1 1 < .
 1996: @end example
 1997: 
 1998: Gforth supports all combinations of the prefixes @code{0 u d d0 du f f0}
 1999: (or none) and the comparisons @code{= <> < > <= >=}.  Only a part of
 2000: these combinations are standard (for details see the standard,
 2001: @ref{Numeric comparison}, @ref{Floating Point} or @ref{Word Index}).
 2002: 
 2003: You can use @code{and or xor invert} as operations on canonical flags.
 2004: Actually they are bitwise operations:
 2005: 
 2006: @example
 2007: 1 2 and .
 2008: 1 2 or .
 2009: 1 3 xor .
 2010: 1 invert .
 2011: @end example
 2012: 
 2013: You can convert a zero/non-zero flag into a canonical flag with
 2014: @code{0<>} (and complement it on the way with @code{0=}).
 2015: 
 2016: @example
 2017: 1 0= .
 2018: 1 0<> .
 2019: @end example
 2020: 
 2021: You can use the all-bits-set feature of canonical flags and the bitwise
 2022: operation of the Boolean operations to avoid @code{if}s:
 2023: 
 2024: @example
 2025: : foo ( n1 -- n2 )
 2026:   0= if
 2027:     14
 2028:   else
 2029:     0
 2030:   endif ;
 2031: 0 foo .
 2032: 1 foo .
 2033: 
 2034: : foo ( n1 -- n2 )
 2035:   0= 14 and ;
 2036: 0 foo .
 2037: 1 foo .
 2038: @end example
 2039: 
 2040: @quotation Assignment
 2041: Write @code{min} without @code{if}.
 2042: @end quotation
 2043: 
 2044: For reference, see @ref{Boolean Flags}, @ref{Numeric comparison}, and
 2045: @ref{Bitwise operations}.
 2046: 
 2047: 
 2048: @node General Loops Tutorial, Counted loops Tutorial, Flags and Comparisons Tutorial, Tutorial
 2049: @section General Loops
 2050: @cindex loops, indefinite, tutorial
 2051: 
 2052: The endless loop is the most simple one:
 2053: 
 2054: @example
 2055: : endless ( -- )
 2056:   0 begin
 2057:     dup . 1+
 2058:   again ;
 2059: endless
 2060: @end example
 2061: 
 2062: Terminate this loop by pressing @kbd{Ctrl-C} (in Gforth).  @code{begin}
 2063: does nothing at run-time, @code{again} jumps back to @code{begin}.
 2064: 
 2065: A loop with one exit at any place looks like this:
 2066: 
 2067: @example
 2068: : log2 ( +n1 -- n2 )
 2069: \ logarithmus dualis of n1>0, rounded down to the next integer
 2070:   assert( dup 0> )
 2071:   2/ 0 begin
 2072:     over 0> while
 2073:       1+ swap 2/ swap
 2074:   repeat
 2075:   nip ;
 2076: 7 log2 .
 2077: 8 log2 .
 2078: @end example
 2079: 
 2080: At run-time @code{while} consumes a flag; if it is 0, execution
 2081: continues behind the @code{repeat}; if the flag is non-zero, execution
 2082: continues behind the @code{while}.  @code{Repeat} jumps back to
 2083: @code{begin}, just like @code{again}.
 2084: 
 2085: In Forth there are a number of combinations/abbreviations, like
 2086: @code{1+}.  However, @code{2/} is not one of them; it shifts its
 2087: argument right by one bit (arithmetic shift right), and viewed as
 2088: division that always rounds towards negative infinity (floored
 2089: division).  In contrast, @code{/} rounds towards zero on some systems
 2090: (not on default installations of gforth (>=0.7.0), however).
 2091: 
 2092: @example
 2093: -5 2 / . \ -2 or -3
 2094: -5 2/ .  \ -3
 2095: @end example
 2096: 
 2097: @code{assert(} is no standard word, but you can get it on systems other
 2098: than Gforth by including @file{compat/assert.fs}.  You can see what it
 2099: does by trying
 2100: 
 2101: @example
 2102: 0 log2 .
 2103: @end example
 2104: 
 2105: Here's a loop with an exit at the end:
 2106: 
 2107: @example
 2108: : log2 ( +n1 -- n2 )
 2109: \ logarithmus dualis of n1>0, rounded down to the next integer
 2110:   assert( dup 0 > )
 2111:   -1 begin
 2112:     1+ swap 2/ swap
 2113:     over 0 <=
 2114:   until
 2115:   nip ;
 2116: @end example
 2117: 
 2118: @code{Until} consumes a flag; if it is non-zero, execution continues at
 2119: the @code{begin}, otherwise after the @code{until}.
 2120: 
 2121: @quotation Assignment
 2122: Write a definition for computing the greatest common divisor.
 2123: @end quotation
 2124: 
 2125: Reference: @ref{Simple Loops}.
 2126: 
 2127: 
 2128: @node Counted loops Tutorial, Recursion Tutorial, General Loops Tutorial, Tutorial
 2129: @section Counted loops
 2130: @cindex loops, counted, tutorial
 2131: 
 2132: @example
 2133: : ^ ( n1 u -- n )
 2134: \ n = the uth power of n1
 2135:   1 swap 0 u+do
 2136:     over *
 2137:   loop
 2138:   nip ;
 2139: 3 2 ^ .
 2140: 4 3 ^ .
 2141: @end example
 2142: 
 2143: @code{U+do} (from @file{compat/loops.fs}, if your Forth system doesn't
 2144: have it) takes two numbers of the stack @code{( u3 u4 -- )}, and then
 2145: performs the code between @code{u+do} and @code{loop} for @code{u3-u4}
 2146: times (or not at all, if @code{u3-u4<0}).
 2147: 
 2148: You can see the stack effect design rules at work in the stack effect of
 2149: the loop start words: Since the start value of the loop is more
 2150: frequently constant than the end value, the start value is passed on
 2151: the top-of-stack.
 2152: 
 2153: You can access the counter of a counted loop with @code{i}:
 2154: 
 2155: @example
 2156: : fac ( u -- u! )
 2157:   1 swap 1+ 1 u+do
 2158:     i *
 2159:   loop ;
 2160: 5 fac .
 2161: 7 fac .
 2162: @end example
 2163: 
 2164: There is also @code{+do}, which expects signed numbers (important for
 2165: deciding whether to enter the loop).
 2166: 
 2167: @quotation Assignment
 2168: Write a definition for computing the nth Fibonacci number.
 2169: @end quotation
 2170: 
 2171: You can also use increments other than 1:
 2172: 
 2173: @example
 2174: : up2 ( n1 n2 -- )
 2175:   +do
 2176:     i .
 2177:   2 +loop ;
 2178: 10 0 up2
 2179: 
 2180: : down2 ( n1 n2 -- )
 2181:   -do
 2182:     i .
 2183:   2 -loop ;
 2184: 0 10 down2
 2185: @end example
 2186: 
 2187: Reference: @ref{Counted Loops}.
 2188: 
 2189: 
 2190: @node Recursion Tutorial, Leaving definitions or loops Tutorial, Counted loops Tutorial, Tutorial
 2191: @section Recursion
 2192: @cindex recursion tutorial
 2193: 
 2194: Usually the name of a definition is not visible in the definition; but
 2195: earlier definitions are usually visible:
 2196: 
 2197: @example
 2198: 1 0 / . \ "Floating-point unidentified fault" in Gforth on some platforms
 2199: : / ( n1 n2 -- n )
 2200:   dup 0= if
 2201:     -10 throw \ report division by zero
 2202:   endif
 2203:   /           \ old version
 2204: ;
 2205: 1 0 /
 2206: @end example
 2207: 
 2208: For recursive definitions you can use @code{recursive} (non-standard) or
 2209: @code{recurse}:
 2210: 
 2211: @example
 2212: : fac1 ( n -- n! ) recursive
 2213:  dup 0> if
 2214:    dup 1- fac1 *
 2215:  else
 2216:    drop 1
 2217:  endif ;
 2218: 7 fac1 .
 2219: 
 2220: : fac2 ( n -- n! )
 2221:  dup 0> if
 2222:    dup 1- recurse *
 2223:  else
 2224:    drop 1
 2225:  endif ;
 2226: 8 fac2 .
 2227: @end example
 2228: 
 2229: @quotation Assignment
 2230: Write a recursive definition for computing the nth Fibonacci number.
 2231: @end quotation
 2232: 
 2233: Reference (including indirect recursion): @xref{Calls and returns}.
 2234: 
 2235: 
 2236: @node Leaving definitions or loops Tutorial, Return Stack Tutorial, Recursion Tutorial, Tutorial
 2237: @section Leaving definitions or loops
 2238: @cindex leaving definitions, tutorial
 2239: @cindex leaving loops, tutorial
 2240: 
 2241: @code{EXIT} exits the current definition right away.  For every counted
 2242: loop that is left in this way, an @code{UNLOOP} has to be performed
 2243: before the @code{EXIT}:
 2244: 
 2245: @c !! real examples
 2246: @example
 2247: : ...
 2248:  ... u+do
 2249:    ... if
 2250:      ... unloop exit
 2251:    endif
 2252:    ...
 2253:  loop
 2254:  ... ;
 2255: @end example
 2256: 
 2257: @code{LEAVE} leaves the innermost counted loop right away:
 2258: 
 2259: @example
 2260: : ...
 2261:  ... u+do
 2262:    ... if
 2263:      ... leave
 2264:    endif
 2265:    ...
 2266:  loop
 2267:  ... ;
 2268: @end example
 2269: 
 2270: @c !! example
 2271: 
 2272: Reference: @ref{Calls and returns}, @ref{Counted Loops}.
 2273: 
 2274: 
 2275: @node Return Stack Tutorial, Memory Tutorial, Leaving definitions or loops Tutorial, Tutorial
 2276: @section Return Stack
 2277: @cindex return stack tutorial
 2278: 
 2279: In addition to the data stack Forth also has a second stack, the return
 2280: stack; most Forth systems store the return addresses of procedure calls
 2281: there (thus its name).  Programmers can also use this stack:
 2282: 
 2283: @example
 2284: : foo ( n1 n2 -- )
 2285:  .s
 2286:  >r .s
 2287:  r@@ .
 2288:  >r .s
 2289:  r@@ .
 2290:  r> .
 2291:  r@@ .
 2292:  r> . ;
 2293: 1 2 foo
 2294: @end example
 2295: 
 2296: @code{>r} takes an element from the data stack and pushes it onto the
 2297: return stack; conversely, @code{r>} moves an elementm from the return to
 2298: the data stack; @code{r@@} pushes a copy of the top of the return stack
 2299: on the data stack.
 2300: 
 2301: Forth programmers usually use the return stack for storing data
 2302: temporarily, if using the data stack alone would be too complex, and
 2303: factoring and locals are not an option:
 2304: 
 2305: @example
 2306: : 2swap ( x1 x2 x3 x4 -- x3 x4 x1 x2 )
 2307:  rot >r rot r> ;
 2308: @end example
 2309: 
 2310: The return address of the definition and the loop control parameters of
 2311: counted loops usually reside on the return stack, so you have to take
 2312: all items, that you have pushed on the return stack in a colon
 2313: definition or counted loop, from the return stack before the definition
 2314: or loop ends.  You cannot access items that you pushed on the return
 2315: stack outside some definition or loop within the definition of loop.
 2316: 
 2317: If you miscount the return stack items, this usually ends in a crash:
 2318: 
 2319: @example
 2320: : crash ( n -- )
 2321:   >r ;
 2322: 5 crash
 2323: @end example
 2324: 
 2325: You cannot mix using locals and using the return stack (according to the
 2326: standard; Gforth has no problem).  However, they solve the same
 2327: problems, so this shouldn't be an issue.
 2328: 
 2329: @quotation Assignment
 2330: Can you rewrite any of the definitions you wrote until now in a better
 2331: way using the return stack?
 2332: @end quotation
 2333: 
 2334: Reference: @ref{Return stack}.
 2335: 
 2336: 
 2337: @node Memory Tutorial, Characters and Strings Tutorial, Return Stack Tutorial, Tutorial
 2338: @section Memory
 2339: @cindex memory access/allocation tutorial
 2340: 
 2341: You can create a global variable @code{v} with
 2342: 
 2343: @example
 2344: variable v ( -- addr )
 2345: @end example
 2346: 
 2347: @code{v} pushes the address of a cell in memory on the stack.  This cell
 2348: was reserved by @code{variable}.  You can use @code{!} (store) to store
 2349: values into this cell and @code{@@} (fetch) to load the value from the
 2350: stack into memory:
 2351: 
 2352: @example
 2353: v .
 2354: 5 v ! .s
 2355: v @@ .
 2356: @end example
 2357: 
 2358: You can see a raw dump of memory with @code{dump}:
 2359: 
 2360: @example
 2361: v 1 cells .s dump
 2362: @end example
 2363: 
 2364: @code{Cells ( n1 -- n2 )} gives you the number of bytes (or, more
 2365: generally, address units (aus)) that @code{n1 cells} occupy.  You can
 2366: also reserve more memory:
 2367: 
 2368: @example
 2369: create v2 20 cells allot
 2370: v2 20 cells dump
 2371: @end example
 2372: 
 2373: creates a variable-like word @code{v2} and reserves 20 uninitialized
 2374: cells; the address pushed by @code{v2} points to the start of these 20
 2375: cells (@pxref{CREATE}).  You can use address arithmetic to access
 2376: these cells:
 2377: 
 2378: @example
 2379: 3 v2 5 cells + !
 2380: v2 20 cells dump
 2381: @end example
 2382: 
 2383: You can reserve and initialize memory with @code{,}:
 2384: 
 2385: @example
 2386: create v3
 2387:   5 , 4 , 3 , 2 , 1 ,
 2388: v3 @@ .
 2389: v3 cell+ @@ .
 2390: v3 2 cells + @@ .
 2391: v3 5 cells dump
 2392: @end example
 2393: 
 2394: @quotation Assignment
 2395: Write a definition @code{vsum ( addr u -- n )} that computes the sum of
 2396: @code{u} cells, with the first of these cells at @code{addr}, the next
 2397: one at @code{addr cell+} etc.
 2398: @end quotation
 2399: 
 2400: The difference between @code{variable} and @code{create} is that
 2401: @code{variable} allots a cell, and that you cannot allot additional
 2402: memory to a variable in standard Forth.
 2403: 
 2404: You can also reserve memory without creating a new word:
 2405: 
 2406: @example
 2407: here 10 cells allot .
 2408: here .
 2409: @end example
 2410: 
 2411: The first @code{here} pushes the start address of the memory area, the
 2412: second @code{here} the address after the dictionary area.  You should
 2413: store the start address somewhere, or you will have a hard time
 2414: finding the memory area again.
 2415: 
 2416: @code{Allot} manages dictionary memory.  The dictionary memory contains
 2417: the system's data structures for words etc. on Gforth and most other
 2418: Forth systems.  It is managed like a stack: You can free the memory that
 2419: you have just @code{allot}ed with
 2420: 
 2421: @example
 2422: -10 cells allot
 2423: here .
 2424: @end example
 2425: 
 2426: Note that you cannot do this if you have created a new word in the
 2427: meantime (because then your @code{allot}ed memory is no longer on the
 2428: top of the dictionary ``stack'').
 2429: 
 2430: Alternatively, you can use @code{allocate} and @code{free} which allow
 2431: freeing memory in any order:
 2432: 
 2433: @example
 2434: 10 cells allocate throw .s
 2435: 20 cells allocate throw .s
 2436: swap
 2437: free throw
 2438: free throw
 2439: @end example
 2440: 
 2441: The @code{throw}s deal with errors (e.g., out of memory).
 2442: 
 2443: And there is also a
 2444: @uref{http://www.complang.tuwien.ac.at/forth/garbage-collection.zip,
 2445: garbage collector}, which eliminates the need to @code{free} memory
 2446: explicitly.
 2447: 
 2448: Reference: @ref{Memory}.
 2449: 
 2450: 
 2451: @node Characters and Strings Tutorial, Alignment Tutorial, Memory Tutorial, Tutorial
 2452: @section Characters and Strings
 2453: @cindex strings tutorial
 2454: @cindex characters tutorial
 2455: 
 2456: On the stack characters take up a cell, like numbers.  In memory they
 2457: have their own size (one 8-bit byte on most systems), and therefore
 2458: require their own words for memory access:
 2459: 
 2460: @example
 2461: create v4 
 2462:   104 c, 97 c, 108 c, 108 c, 111 c,
 2463: v4 4 chars + c@@ .
 2464: v4 5 chars dump
 2465: @end example
 2466: 
 2467: The preferred representation of strings on the stack is @code{addr
 2468: u-count}, where @code{addr} is the address of the first character and
 2469: @code{u-count} is the number of characters in the string.
 2470: 
 2471: @example
 2472: v4 5 type
 2473: @end example
 2474: 
 2475: You get a string constant with
 2476: 
 2477: @example
 2478: s" hello, world" .s
 2479: type
 2480: @end example
 2481: 
 2482: Make sure you have a space between @code{s"} and the string; @code{s"}
 2483: is a normal Forth word and must be delimited with white space (try what
 2484: happens when you remove the space).
 2485: 
 2486: However, this interpretive use of @code{s"} is quite restricted: the
 2487: string exists only until the next call of @code{s"} (some Forth systems
 2488: keep more than one of these strings, but usually they still have a
 2489: limited lifetime).
 2490: 
 2491: @example
 2492: s" hello," s" world" .s
 2493: type
 2494: type
 2495: @end example
 2496: 
 2497: You can also use @code{s"} in a definition, and the resulting
 2498: strings then live forever (well, for as long as the definition):
 2499: 
 2500: @example
 2501: : foo s" hello," s" world" ;
 2502: foo .s
 2503: type
 2504: type
 2505: @end example
 2506: 
 2507: @quotation Assignment
 2508: @code{Emit ( c -- )} types @code{c} as character (not a number).
 2509: Implement @code{type ( addr u -- )}.
 2510: @end quotation
 2511: 
 2512: Reference: @ref{Memory Blocks}.
 2513: 
 2514: 
 2515: @node Alignment Tutorial, Floating Point Tutorial, Characters and Strings Tutorial, Tutorial
 2516: @section Alignment
 2517: @cindex alignment tutorial
 2518: @cindex memory alignment tutorial
 2519: 
 2520: On many processors cells have to be aligned in memory, if you want to
 2521: access them with @code{@@} and @code{!} (and even if the processor does
 2522: not require alignment, access to aligned cells is faster).
 2523: 
 2524: @code{Create} aligns @code{here} (i.e., the place where the next
 2525: allocation will occur, and that the @code{create}d word points to).
 2526: Likewise, the memory produced by @code{allocate} starts at an aligned
 2527: address.  Adding a number of @code{cells} to an aligned address produces
 2528: another aligned address.
 2529: 
 2530: However, address arithmetic involving @code{char+} and @code{chars} can
 2531: create an address that is not cell-aligned.  @code{Aligned ( addr --
 2532: a-addr )} produces the next aligned address:
 2533: 
 2534: @example
 2535: v3 char+ aligned .s @@ .
 2536: v3 char+ .s @@ .
 2537: @end example
 2538: 
 2539: Similarly, @code{align} advances @code{here} to the next aligned
 2540: address:
 2541: 
 2542: @example
 2543: create v5 97 c,
 2544: here .
 2545: align here .
 2546: 1000 ,
 2547: @end example
 2548: 
 2549: Note that you should use aligned addresses even if your processor does
 2550: not require them, if you want your program to be portable.
 2551: 
 2552: Reference: @ref{Address arithmetic}.
 2553: 
 2554: @node Floating Point Tutorial, Files Tutorial, Alignment Tutorial, Tutorial
 2555: @section Floating Point
 2556: @cindex floating point tutorial
 2557: @cindex FP tutorial
 2558: 
 2559: Floating-point (FP) numbers and arithmetic in Forth works mostly as one
 2560: might expect, but there are a few things worth noting:
 2561: 
 2562: The first point is not specific to Forth, but so important and yet not
 2563: universally known that I mention it here: FP numbers are not reals.
 2564: Many properties (e.g., arithmetic laws) that reals have and that one
 2565: expects of all kinds of numbers do not hold for FP numbers.  If you
 2566: want to use FP computations, you should learn about their problems and
 2567: how to avoid them; a good starting point is @cite{David Goldberg,
 2568: @uref{http://docs.sun.com/source/806-3568/ncg_goldberg.html,What Every
 2569: Computer Scientist Should Know About Floating-Point Arithmetic}, ACM
 2570: Computing Surveys 23(1):5@minus{}48, March 1991}.
 2571: 
 2572: In Forth source code literal FP numbers need an exponent, e.g.,
 2573: @code{1e0}; this can also be written shorter as @code{1e}, longer as
 2574: @code{+1.0e+0}, and many variations in between.  The reason for this is
 2575: that, for historical reasons, Forth interprets a decimal point alone
 2576: (e.g., @code{1.}) as indicating a double-cell integer.  Examples:
 2577: 
 2578: @example
 2579: 2e 2e f+ f.
 2580: @end example
 2581: 
 2582: Another requirement for literal FP numbers is that the current base is
 2583: decimal; with a hex base @code{1e} is interpreted as an integer.
 2584: 
 2585: Forth has a separate stack for FP numbers.@footnote{Theoretically, an
 2586: ANS Forth system may implement the FP stack on the data stack, but
 2587: virtually all systems implement a separate FP stack; and programming
 2588: in a way that accommodates all models is so cumbersome that nobody
 2589: does it.}  One advantage of this model is that cells are not in the
 2590: way when accessing FP values, and vice versa.  Forth has a set of
 2591: words for manipulating the FP stack: @code{fdup fswap fdrop fover
 2592: frot} and (non-standard) @code{fnip ftuck fpick}.
 2593: 
 2594: FP arithmetic words are prefixed with @code{F}.  There is the usual
 2595: set @code{f+ f- f* f/ f** fnegate} as well as a number of words for
 2596: other functions, e.g., @code{fsqrt fsin fln fmin}.  One word that you
 2597: might expect is @code{f=}; but @code{f=} is non-standard, because FP
 2598: computation results are usually inaccurate, so exact comparison is
 2599: usually a mistake, and one should use approximate comparison.
 2600: Unfortunately, @code{f~}, the standard word for that purpose, is not
 2601: well designed, so Gforth provides @code{f~abs} and @code{f~rel} as
 2602: well.
 2603: 
 2604: And of course there are words for accessing FP numbers in memory
 2605: (@code{f@@ f!}), and for address arithmetic (@code{floats float+
 2606: faligned}).  There are also variants of these words with an @code{sf}
 2607: and @code{df} prefix for accessing IEEE format single-precision and
 2608: double-precision numbers in memory; their main purpose is for
 2609: accessing external FP data (e.g., that has been read from or will be
 2610: written to a file).
 2611: 
 2612: Here is an example of a dot-product word and its use:
 2613: 
 2614: @example
 2615: : v* ( f_addr1 nstride1 f_addr2 nstride2 ucount -- r )
 2616:   >r swap 2swap swap 0e r> 0 ?DO
 2617:     dup f@@ over + 2swap dup f@@ f* f+ over + 2swap
 2618:   LOOP
 2619:   2drop 2drop ;
 2620: 
 2621: create v 1.23e f, 4.56e f, 7.89e f,
 2622: 
 2623: v 1 floats  v 1 floats  3  v* f.
 2624: @end example
 2625: 
 2626: @quotation Assignment
 2627: Write a program to solve a quadratic equation.  Then read @cite{Henry
 2628: G. Baker,
 2629: @uref{http://home.pipeline.com/~hbaker1/sigplannotices/sigcol05.ps.gz,You
 2630: Could Learn a Lot from a Quadratic}, ACM SIGPLAN Notices,
 2631: 33(1):30@minus{}39, January 1998}, and see if you can improve your
 2632: program.  Finally, find a test case where the original and the
 2633: improved version produce different results.
 2634: @end quotation
 2635: 
 2636: Reference: @ref{Floating Point}; @ref{Floating point stack};
 2637: @ref{Number Conversion}; @ref{Memory Access}; @ref{Address
 2638: arithmetic}.
 2639: 
 2640: @node Files Tutorial, Interpretation and Compilation Semantics and Immediacy Tutorial, Floating Point Tutorial, Tutorial
 2641: @section Files
 2642: @cindex files tutorial
 2643: 
 2644: This section gives a short introduction into how to use files inside
 2645: Forth. It's broken up into five easy steps:
 2646: 
 2647: @enumerate 1
 2648: @item Opened an ASCII text file for input
 2649: @item Opened a file for output
 2650: @item Read input file until string matched (or some other condition matched)
 2651: @item Wrote some lines from input ( modified or not) to output
 2652: @item Closed the files.
 2653: @end enumerate
 2654: 
 2655: Reference: @ref{General files}.
 2656: 
 2657: @subsection Open file for input
 2658: 
 2659: @example
 2660: s" foo.in"  r/o open-file throw Value fd-in
 2661: @end example
 2662: 
 2663: @subsection Create file for output
 2664: 
 2665: @example
 2666: s" foo.out" w/o create-file throw Value fd-out
 2667: @end example
 2668: 
 2669: The available file modes are r/o for read-only access, r/w for
 2670: read-write access, and w/o for write-only access. You could open both
 2671: files with r/w, too, if you like. All file words return error codes; for
 2672: most applications, it's best to pass there error codes with @code{throw}
 2673: to the outer error handler.
 2674: 
 2675: If you want words for opening and assigning, define them as follows:
 2676: 
 2677: @example
 2678: 0 Value fd-in
 2679: 0 Value fd-out
 2680: : open-input ( addr u -- )  r/o open-file throw to fd-in ;
 2681: : open-output ( addr u -- )  w/o create-file throw to fd-out ;
 2682: @end example
 2683: 
 2684: Usage example:
 2685: 
 2686: @example
 2687: s" foo.in" open-input
 2688: s" foo.out" open-output
 2689: @end example
 2690: 
 2691: @subsection Scan file for a particular line
 2692: 
 2693: @example
 2694: 256 Constant max-line
 2695: Create line-buffer  max-line 2 + allot
 2696: 
 2697: : scan-file ( addr u -- )
 2698:   begin
 2699:       line-buffer max-line fd-in read-line throw
 2700:   while
 2701:          >r 2dup line-buffer r> compare 0=
 2702:      until
 2703:   else
 2704:      drop
 2705:   then
 2706:   2drop ;
 2707: @end example
 2708: 
 2709: @code{read-line ( addr u1 fd -- u2 flag ior )} reads up to u1 bytes into
 2710: the buffer at addr, and returns the number of bytes read, a flag that is
 2711: false when the end of file is reached, and an error code.
 2712: 
 2713: @code{compare ( addr1 u1 addr2 u2 -- n )} compares two strings and
 2714: returns zero if both strings are equal. It returns a positive number if
 2715: the first string is lexically greater, a negative if the second string
 2716: is lexically greater.
 2717: 
 2718: We haven't seen this loop here; it has two exits. Since the @code{while}
 2719: exits with the number of bytes read on the stack, we have to clean up
 2720: that separately; that's after the @code{else}.
 2721: 
 2722: Usage example:
 2723: 
 2724: @example
 2725: s" The text I search is here" scan-file
 2726: @end example
 2727: 
 2728: @subsection Copy input to output
 2729: 
 2730: @example
 2731: : copy-file ( -- )
 2732:   begin
 2733:       line-buffer max-line fd-in read-line throw
 2734:   while
 2735:       line-buffer swap fd-out write-line throw
 2736:   repeat 
 2737:   drop ;
 2738: @end example
 2739: @c !! does not handle long lines, no newline at end of file
 2740: 
 2741: @subsection Close files
 2742: 
 2743: @example
 2744: fd-in close-file throw
 2745: fd-out close-file throw
 2746: @end example
 2747: 
 2748: Likewise, you can put that into definitions, too:
 2749: 
 2750: @example
 2751: : close-input ( -- )  fd-in close-file throw ;
 2752: : close-output ( -- )  fd-out close-file throw ;
 2753: @end example
 2754: 
 2755: @quotation Assignment
 2756: How could you modify @code{copy-file} so that it copies until a second line is
 2757: matched? Can you write a program that extracts a section of a text file,
 2758: given the line that starts and the line that terminates that section?
 2759: @end quotation
 2760: 
 2761: @node Interpretation and Compilation Semantics and Immediacy Tutorial, Execution Tokens Tutorial, Files Tutorial, Tutorial
 2762: @section Interpretation and Compilation Semantics and Immediacy
 2763: @cindex semantics tutorial
 2764: @cindex interpretation semantics tutorial
 2765: @cindex compilation semantics tutorial
 2766: @cindex immediate, tutorial
 2767: 
 2768: When a word is compiled, it behaves differently from being interpreted.
 2769: E.g., consider @code{+}:
 2770: 
 2771: @example
 2772: 1 2 + .
 2773: : foo + ;
 2774: @end example
 2775: 
 2776: These two behaviours are known as compilation and interpretation
 2777: semantics.  For normal words (e.g., @code{+}), the compilation semantics
 2778: is to append the interpretation semantics to the currently defined word
 2779: (@code{foo} in the example above).  I.e., when @code{foo} is executed
 2780: later, the interpretation semantics of @code{+} (i.e., adding two
 2781: numbers) will be performed.
 2782: 
 2783: However, there are words with non-default compilation semantics, e.g.,
 2784: the control-flow words like @code{if}.  You can use @code{immediate} to
 2785: change the compilation semantics of the last defined word to be equal to
 2786: the interpretation semantics:
 2787: 
 2788: @example
 2789: : [FOO] ( -- )
 2790:  5 . ; immediate
 2791: 
 2792: [FOO]
 2793: : bar ( -- )
 2794:   [FOO] ;
 2795: bar
 2796: see bar
 2797: @end example
 2798: 
 2799: Two conventions to mark words with non-default compilation semantics are
 2800: names with brackets (more frequently used) and to write them all in
 2801: upper case (less frequently used).
 2802: 
 2803: In Gforth (and many other systems) you can also remove the
 2804: interpretation semantics with @code{compile-only} (the compilation
 2805: semantics is derived from the original interpretation semantics):
 2806: 
 2807: @example
 2808: : flip ( -- )
 2809:  6 . ; compile-only \ but not immediate
 2810: flip
 2811: 
 2812: : flop ( -- )
 2813:  flip ;
 2814: flop
 2815: @end example
 2816: 
 2817: In this example the interpretation semantics of @code{flop} is equal to
 2818: the original interpretation semantics of @code{flip}.
 2819: 
 2820: The text interpreter has two states: in interpret state, it performs the
 2821: interpretation semantics of words it encounters; in compile state, it
 2822: performs the compilation semantics of these words.
 2823: 
 2824: Among other things, @code{:} switches into compile state, and @code{;}
 2825: switches back to interpret state.  They contain the factors @code{]}
 2826: (switch to compile state) and @code{[} (switch to interpret state), that
 2827: do nothing but switch the state.
 2828: 
 2829: @example
 2830: : xxx ( -- )
 2831:   [ 5 . ]
 2832: ;
 2833: 
 2834: xxx
 2835: see xxx
 2836: @end example
 2837: 
 2838: These brackets are also the source of the naming convention mentioned
 2839: above.
 2840: 
 2841: Reference: @ref{Interpretation and Compilation Semantics}.
 2842: 
 2843: 
 2844: @node Execution Tokens Tutorial, Exceptions Tutorial, Interpretation and Compilation Semantics and Immediacy Tutorial, Tutorial
 2845: @section Execution Tokens
 2846: @cindex execution tokens tutorial
 2847: @cindex XT tutorial
 2848: 
 2849: @code{' word} gives you the execution token (XT) of a word.  The XT is a
 2850: cell representing the interpretation semantics of a word.  You can
 2851: execute this semantics with @code{execute}:
 2852: 
 2853: @example
 2854: ' + .s
 2855: 1 2 rot execute .
 2856: @end example
 2857: 
 2858: The XT is similar to a function pointer in C.  However, parameter
 2859: passing through the stack makes it a little more flexible:
 2860: 
 2861: @example
 2862: : map-array ( ... addr u xt -- ... )
 2863: \ executes xt ( ... x -- ... ) for every element of the array starting
 2864: \ at addr and containing u elements
 2865:   @{ xt @}
 2866:   cells over + swap ?do
 2867:     i @@ xt execute
 2868:   1 cells +loop ;
 2869: 
 2870: create a 3 , 4 , 2 , -1 , 4 ,
 2871: a 5 ' . map-array .s
 2872: 0 a 5 ' + map-array .
 2873: s" max-n" environment? drop .s
 2874: a 5 ' min map-array .
 2875: @end example
 2876: 
 2877: You can use map-array with the XTs of words that consume one element
 2878: more than they produce.  In theory you can also use it with other XTs,
 2879: but the stack effect then depends on the size of the array, which is
 2880: hard to understand.
 2881: 
 2882: Since XTs are cell-sized, you can store them in memory and manipulate
 2883: them on the stack like other cells.  You can also compile the XT into a
 2884: word with @code{compile,}:
 2885: 
 2886: @example
 2887: : foo1 ( n1 n2 -- n )
 2888:    [ ' + compile, ] ;
 2889: see foo1
 2890: @end example
 2891: 
 2892: This is non-standard, because @code{compile,} has no compilation
 2893: semantics in the standard, but it works in good Forth systems.  For the
 2894: broken ones, use
 2895: 
 2896: @example
 2897: : [compile,] compile, ; immediate
 2898: 
 2899: : foo1 ( n1 n2 -- n )
 2900:    [ ' + ] [compile,] ;
 2901: see foo
 2902: @end example
 2903: 
 2904: @code{'} is a word with default compilation semantics; it parses the
 2905: next word when its interpretation semantics are executed, not during
 2906: compilation:
 2907: 
 2908: @example
 2909: : foo ( -- xt )
 2910:   ' ;
 2911: see foo
 2912: : bar ( ... "word" -- ... )
 2913:   ' execute ;
 2914: see bar
 2915: 1 2 bar + .
 2916: @end example
 2917: 
 2918: You often want to parse a word during compilation and compile its XT so
 2919: it will be pushed on the stack at run-time.  @code{[']} does this:
 2920: 
 2921: @example
 2922: : xt-+ ( -- xt )
 2923:   ['] + ;
 2924: see xt-+
 2925: 1 2 xt-+ execute .
 2926: @end example
 2927: 
 2928: Many programmers tend to see @code{'} and the word it parses as one
 2929: unit, and expect it to behave like @code{[']} when compiled, and are
 2930: confused by the actual behaviour.  If you are, just remember that the
 2931: Forth system just takes @code{'} as one unit and has no idea that it is
 2932: a parsing word (attempts to convenience programmers in this issue have
 2933: usually resulted in even worse pitfalls, see
 2934: @uref{http://www.complang.tuwien.ac.at/papers/ertl98.ps.gz,
 2935: @code{State}-smartness---Why it is evil and How to Exorcise it}).
 2936: 
 2937: Note that the state of the interpreter does not come into play when
 2938: creating and executing XTs.  I.e., even when you execute @code{'} in
 2939: compile state, it still gives you the interpretation semantics.  And
 2940: whatever that state is, @code{execute} performs the semantics
 2941: represented by the XT (i.e., for XTs produced with @code{'} the
 2942: interpretation semantics).
 2943: 
 2944: Reference: @ref{Tokens for Words}.
 2945: 
 2946: 
 2947: @node Exceptions Tutorial, Defining Words Tutorial, Execution Tokens Tutorial, Tutorial
 2948: @section Exceptions
 2949: @cindex exceptions tutorial
 2950: 
 2951: @code{throw ( n -- )} causes an exception unless n is zero.
 2952: 
 2953: @example
 2954: 100 throw .s
 2955: 0 throw .s
 2956: @end example
 2957: 
 2958: @code{catch ( ... xt -- ... n )} behaves similar to @code{execute}, but
 2959: it catches exceptions and pushes the number of the exception on the
 2960: stack (or 0, if the xt executed without exception).  If there was an
 2961: exception, the stacks have the same depth as when entering @code{catch}:
 2962: 
 2963: @example
 2964: .s
 2965: 3 0 ' / catch .s
 2966: 3 2 ' / catch .s
 2967: @end example
 2968: 
 2969: @quotation Assignment
 2970: Try the same with @code{execute} instead of @code{catch}.
 2971: @end quotation
 2972: 
 2973: @code{Throw} always jumps to the dynamically next enclosing
 2974: @code{catch}, even if it has to leave several call levels to achieve
 2975: this:
 2976: 
 2977: @example
 2978: : foo 100 throw ;
 2979: : foo1 foo ." after foo" ;
 2980: : bar ['] foo1 catch ;
 2981: bar .
 2982: @end example
 2983: 
 2984: It is often important to restore a value upon leaving a definition, even
 2985: if the definition is left through an exception.  You can ensure this
 2986: like this:
 2987: 
 2988: @example
 2989: : ...
 2990:    save-x
 2991:    ['] word-changing-x catch ( ... n )
 2992:    restore-x
 2993:    ( ... n ) throw ;
 2994: @end example
 2995: 
 2996: However, this is still not safe against, e.g., the user pressing
 2997: @kbd{Ctrl-C} when execution is between the @code{catch} and
 2998: @code{restore-x}.
 2999: 
 3000: Gforth provides an alternative exception handling syntax that is safe
 3001: against such cases: @code{try ... restore ... endtry}.  If the code
 3002: between @code{try} and @code{endtry} has an exception, the stack
 3003: depths are restored, the exception number is pushed on the stack, and
 3004: the execution continues right after @code{restore}.
 3005: 
 3006: The safer equivalent to the restoration code above is
 3007: 
 3008: @example
 3009: : ...
 3010:   save-x
 3011:   try
 3012:     word-changing-x 0
 3013:   restore
 3014:     restore-x
 3015:   endtry
 3016:   throw ;
 3017: @end example
 3018: 
 3019: Reference: @ref{Exception Handling}.
 3020: 
 3021: 
 3022: @node Defining Words Tutorial, Arrays and Records Tutorial, Exceptions Tutorial, Tutorial
 3023: @section Defining Words
 3024: @cindex defining words tutorial
 3025: @cindex does> tutorial
 3026: @cindex create...does> tutorial
 3027: 
 3028: @c before semantics?
 3029: 
 3030: @code{:}, @code{create}, and @code{variable} are definition words: They
 3031: define other words.  @code{Constant} is another definition word:
 3032: 
 3033: @example
 3034: 5 constant foo
 3035: foo .
 3036: @end example
 3037: 
 3038: You can also use the prefixes @code{2} (double-cell) and @code{f}
 3039: (floating point) with @code{variable} and @code{constant}.
 3040: 
 3041: You can also define your own defining words.  E.g.:
 3042: 
 3043: @example
 3044: : variable ( "name" -- )
 3045:   create 0 , ;
 3046: @end example
 3047: 
 3048: You can also define defining words that create words that do something
 3049: other than just producing their address:
 3050: 
 3051: @example
 3052: : constant ( n "name" -- )
 3053:   create ,
 3054: does> ( -- n )
 3055:   ( addr ) @@ ;
 3056: 
 3057: 5 constant foo
 3058: foo .
 3059: @end example
 3060: 
 3061: The definition of @code{constant} above ends at the @code{does>}; i.e.,
 3062: @code{does>} replaces @code{;}, but it also does something else: It
 3063: changes the last defined word such that it pushes the address of the
 3064: body of the word and then performs the code after the @code{does>}
 3065: whenever it is called.
 3066: 
 3067: In the example above, @code{constant} uses @code{,} to store 5 into the
 3068: body of @code{foo}.  When @code{foo} executes, it pushes the address of
 3069: the body onto the stack, then (in the code after the @code{does>})
 3070: fetches the 5 from there.
 3071: 
 3072: The stack comment near the @code{does>} reflects the stack effect of the
 3073: defined word, not the stack effect of the code after the @code{does>}
 3074: (the difference is that the code expects the address of the body that
 3075: the stack comment does not show).
 3076: 
 3077: You can use these definition words to do factoring in cases that involve
 3078: (other) definition words.  E.g., a field offset is always added to an
 3079: address.  Instead of defining
 3080: 
 3081: @example
 3082: 2 cells constant offset-field1
 3083: @end example
 3084: 
 3085: and using this like
 3086: 
 3087: @example
 3088: ( addr ) offset-field1 +
 3089: @end example
 3090: 
 3091: you can define a definition word
 3092: 
 3093: @example
 3094: : simple-field ( n "name" -- )
 3095:   create ,
 3096: does> ( n1 -- n1+n )
 3097:   ( addr ) @@ + ;
 3098: @end example
 3099: 
 3100: Definition and use of field offsets now look like this:
 3101: 
 3102: @example
 3103: 2 cells simple-field field1
 3104: create mystruct 4 cells allot
 3105: mystruct .s field1 .s drop
 3106: @end example
 3107: 
 3108: If you want to do something with the word without performing the code
 3109: after the @code{does>}, you can access the body of a @code{create}d word
 3110: with @code{>body ( xt -- addr )}:
 3111: 
 3112: @example
 3113: : value ( n "name" -- )
 3114:   create ,
 3115: does> ( -- n1 )
 3116:   @@ ;
 3117: : to ( n "name" -- )
 3118:   ' >body ! ;
 3119: 
 3120: 5 value foo
 3121: foo .
 3122: 7 to foo
 3123: foo .
 3124: @end example
 3125: 
 3126: @quotation Assignment
 3127: Define @code{defer ( "name" -- )}, which creates a word that stores an
 3128: XT (at the start the XT of @code{abort}), and upon execution
 3129: @code{execute}s the XT.  Define @code{is ( xt "name" -- )} that stores
 3130: @code{xt} into @code{name}, a word defined with @code{defer}.  Indirect
 3131: recursion is one application of @code{defer}.
 3132: @end quotation
 3133: 
 3134: Reference: @ref{User-defined Defining Words}.
 3135: 
 3136: 
 3137: @node Arrays and Records Tutorial, POSTPONE Tutorial, Defining Words Tutorial, Tutorial
 3138: @section Arrays and Records
 3139: @cindex arrays tutorial
 3140: @cindex records tutorial
 3141: @cindex structs tutorial
 3142: 
 3143: Forth has no standard words for defining data structures such as arrays
 3144: and records (structs in C terminology), but you can build them yourself
 3145: based on address arithmetic.  You can also define words for defining
 3146: arrays and records (@pxref{Defining Words Tutorial,, Defining Words}).
 3147: 
 3148: One of the first projects a Forth newcomer sets out upon when learning
 3149: about defining words is an array defining word (possibly for
 3150: n-dimensional arrays).  Go ahead and do it, I did it, too; you will
 3151: learn something from it.  However, don't be disappointed when you later
 3152: learn that you have little use for these words (inappropriate use would
 3153: be even worse).  I have not found a set of useful array words yet;
 3154: the needs are just too diverse, and named, global arrays (the result of
 3155: naive use of defining words) are often not flexible enough (e.g.,
 3156: consider how to pass them as parameters).  Another such project is a set
 3157: of words to help dealing with strings.
 3158: 
 3159: On the other hand, there is a useful set of record words, and it has
 3160: been defined in @file{compat/struct.fs}; these words are predefined in
 3161: Gforth.  They are explained in depth elsewhere in this manual (see
 3162: @pxref{Structures}).  The @code{simple-field} example above is
 3163: simplified variant of fields in this package.
 3164: 
 3165: 
 3166: @node POSTPONE Tutorial, Literal Tutorial, Arrays and Records Tutorial, Tutorial
 3167: @section @code{POSTPONE}
 3168: @cindex postpone tutorial
 3169: 
 3170: You can compile the compilation semantics (instead of compiling the
 3171: interpretation semantics) of a word with @code{POSTPONE}:
 3172: 
 3173: @example
 3174: : MY-+ ( Compilation: -- ; Run-time of compiled code: n1 n2 -- n )
 3175:  POSTPONE + ; immediate
 3176: : foo ( n1 n2 -- n )
 3177:  MY-+ ;
 3178: 1 2 foo .
 3179: see foo
 3180: @end example
 3181: 
 3182: During the definition of @code{foo} the text interpreter performs the
 3183: compilation semantics of @code{MY-+}, which performs the compilation
 3184: semantics of @code{+}, i.e., it compiles @code{+} into @code{foo}.
 3185: 
 3186: This example also displays separate stack comments for the compilation
 3187: semantics and for the stack effect of the compiled code.  For words with
 3188: default compilation semantics these stack effects are usually not
 3189: displayed; the stack effect of the compilation semantics is always
 3190: @code{( -- )} for these words, the stack effect for the compiled code is
 3191: the stack effect of the interpretation semantics.
 3192: 
 3193: Note that the state of the interpreter does not come into play when
 3194: performing the compilation semantics in this way.  You can also perform
 3195: it interpretively, e.g.:
 3196: 
 3197: @example
 3198: : foo2 ( n1 n2 -- n )
 3199:  [ MY-+ ] ;
 3200: 1 2 foo .
 3201: see foo
 3202: @end example
 3203: 
 3204: However, there are some broken Forth systems where this does not always
 3205: work, and therefore this practice was been declared non-standard in
 3206: 1999.
 3207: @c !! repair.fs
 3208: 
 3209: Here is another example for using @code{POSTPONE}:
 3210: 
 3211: @example
 3212: : MY-- ( Compilation: -- ; Run-time of compiled code: n1 n2 -- n )
 3213:  POSTPONE negate POSTPONE + ; immediate compile-only
 3214: : bar ( n1 n2 -- n )
 3215:   MY-- ;
 3216: 2 1 bar .
 3217: see bar
 3218: @end example
 3219: 
 3220: You can define @code{ENDIF} in this way:
 3221: 
 3222: @example
 3223: : ENDIF ( Compilation: orig -- )
 3224:   POSTPONE then ; immediate
 3225: @end example
 3226: 
 3227: @quotation Assignment
 3228: Write @code{MY-2DUP} that has compilation semantics equivalent to
 3229: @code{2dup}, but compiles @code{over over}.
 3230: @end quotation
 3231: 
 3232: @c !! @xref{Macros} for reference
 3233: 
 3234: 
 3235: @node Literal Tutorial, Advanced macros Tutorial, POSTPONE Tutorial, Tutorial
 3236: @section @code{Literal}
 3237: @cindex literal tutorial
 3238: 
 3239: You cannot @code{POSTPONE} numbers:
 3240: 
 3241: @example
 3242: : [FOO] POSTPONE 500 ; immediate
 3243: @end example
 3244: 
 3245: Instead, you can use @code{LITERAL (compilation: n --; run-time: -- n )}:
 3246: 
 3247: @example
 3248: : [FOO] ( compilation: --; run-time: -- n )
 3249:   500 POSTPONE literal ; immediate
 3250: 
 3251: : flip [FOO] ;
 3252: flip .
 3253: see flip
 3254: @end example
 3255: 
 3256: @code{LITERAL} consumes a number at compile-time (when it's compilation
 3257: semantics are executed) and pushes it at run-time (when the code it
 3258: compiled is executed).  A frequent use of @code{LITERAL} is to compile a
 3259: number computed at compile time into the current word:
 3260: 
 3261: @example
 3262: : bar ( -- n )
 3263:   [ 2 2 + ] literal ;
 3264: see bar
 3265: @end example
 3266: 
 3267: @quotation Assignment
 3268: Write @code{]L} which allows writing the example above as @code{: bar (
 3269: -- n ) [ 2 2 + ]L ;}
 3270: @end quotation
 3271: 
 3272: @c !! @xref{Macros} for reference
 3273: 
 3274: 
 3275: @node Advanced macros Tutorial, Compilation Tokens Tutorial, Literal Tutorial, Tutorial
 3276: @section Advanced macros
 3277: @cindex macros, advanced tutorial
 3278: @cindex run-time code generation, tutorial
 3279: 
 3280: Reconsider @code{map-array} from @ref{Execution Tokens Tutorial,,
 3281: Execution Tokens}.  It frequently performs @code{execute}, a relatively
 3282: expensive operation in some Forth implementations.  You can use
 3283: @code{compile,} and @code{POSTPONE} to eliminate these @code{execute}s
 3284: and produce a word that contains the word to be performed directly:
 3285: 
 3286: @c use ]] ... [[
 3287: @example
 3288: : compile-map-array ( compilation: xt -- ; run-time: ... addr u -- ... )
 3289: \ at run-time, execute xt ( ... x -- ... ) for each element of the
 3290: \ array beginning at addr and containing u elements
 3291:   @{ xt @}
 3292:   POSTPONE cells POSTPONE over POSTPONE + POSTPONE swap POSTPONE ?do
 3293:     POSTPONE i POSTPONE @@ xt compile,
 3294:   1 cells POSTPONE literal POSTPONE +loop ;
 3295: 
 3296: : sum-array ( addr u -- n )
 3297:  0 rot rot [ ' + compile-map-array ] ;
 3298: see sum-array
 3299: a 5 sum-array .
 3300: @end example
 3301: 
 3302: You can use the full power of Forth for generating the code; here's an
 3303: example where the code is generated in a loop:
 3304: 
 3305: @example
 3306: : compile-vmul-step ( compilation: n --; run-time: n1 addr1 -- n2 addr2 )
 3307: \ n2=n1+(addr1)*n, addr2=addr1+cell
 3308:   POSTPONE tuck POSTPONE @@
 3309:   POSTPONE literal POSTPONE * POSTPONE +
 3310:   POSTPONE swap POSTPONE cell+ ;
 3311: 
 3312: : compile-vmul ( compilation: addr1 u -- ; run-time: addr2 -- n )
 3313: \ n=v1*v2 (inner product), where the v_i are represented as addr_i u
 3314:   0 postpone literal postpone swap
 3315:   [ ' compile-vmul-step compile-map-array ]
 3316:   postpone drop ;
 3317: see compile-vmul
 3318: 
 3319: : a-vmul ( addr -- n )
 3320: \ n=a*v, where v is a vector that's as long as a and starts at addr
 3321:  [ a 5 compile-vmul ] ;
 3322: see a-vmul
 3323: a a-vmul .
 3324: @end example
 3325: 
 3326: This example uses @code{compile-map-array} to show off, but you could
 3327: also use @code{map-array} instead (try it now!).
 3328: 
 3329: You can use this technique for efficient multiplication of large
 3330: matrices.  In matrix multiplication, you multiply every line of one
 3331: matrix with every column of the other matrix.  You can generate the code
 3332: for one line once, and use it for every column.  The only downside of
 3333: this technique is that it is cumbersome to recover the memory consumed
 3334: by the generated code when you are done (and in more complicated cases
 3335: it is not possible portably).
 3336: 
 3337: @c !! @xref{Macros} for reference
 3338: 
 3339: 
 3340: @node Compilation Tokens Tutorial, Wordlists and Search Order Tutorial, Advanced macros Tutorial, Tutorial
 3341: @section Compilation Tokens
 3342: @cindex compilation tokens, tutorial
 3343: @cindex CT, tutorial
 3344: 
 3345: This section is Gforth-specific.  You can skip it.
 3346: 
 3347: @code{' word compile,} compiles the interpretation semantics.  For words
 3348: with default compilation semantics this is the same as performing the
 3349: compilation semantics.  To represent the compilation semantics of other
 3350: words (e.g., words like @code{if} that have no interpretation
 3351: semantics), Gforth has the concept of a compilation token (CT,
 3352: consisting of two cells), and words @code{comp'} and @code{[comp']}.
 3353: You can perform the compilation semantics represented by a CT with
 3354: @code{execute}:
 3355: 
 3356: @example
 3357: : foo2 ( n1 n2 -- n )
 3358:    [ comp' + execute ] ;
 3359: see foo
 3360: @end example
 3361: 
 3362: You can compile the compilation semantics represented by a CT with
 3363: @code{postpone,}:
 3364: 
 3365: @example
 3366: : foo3 ( -- )
 3367:   [ comp' + postpone, ] ;
 3368: see foo3
 3369: @end example
 3370: 
 3371: @code{[ comp' word postpone, ]} is equivalent to @code{POSTPONE word}.
 3372: @code{comp'} is particularly useful for words that have no
 3373: interpretation semantics:
 3374: 
 3375: @example
 3376: ' if
 3377: comp' if .s 2drop
 3378: @end example
 3379: 
 3380: Reference: @ref{Tokens for Words}.
 3381: 
 3382: 
 3383: @node Wordlists and Search Order Tutorial,  , Compilation Tokens Tutorial, Tutorial
 3384: @section Wordlists and Search Order
 3385: @cindex wordlists tutorial
 3386: @cindex search order, tutorial
 3387: 
 3388: The dictionary is not just a memory area that allows you to allocate
 3389: memory with @code{allot}, it also contains the Forth words, arranged in
 3390: several wordlists.  When searching for a word in a wordlist,
 3391: conceptually you start searching at the youngest and proceed towards
 3392: older words (in reality most systems nowadays use hash-tables); i.e., if
 3393: you define a word with the same name as an older word, the new word
 3394: shadows the older word.
 3395: 
 3396: Which wordlists are searched in which order is determined by the search
 3397: order.  You can display the search order with @code{order}.  It displays
 3398: first the search order, starting with the wordlist searched first, then
 3399: it displays the wordlist that will contain newly defined words.
 3400: 
 3401: You can create a new, empty wordlist with @code{wordlist ( -- wid )}:
 3402: 
 3403: @example
 3404: wordlist constant mywords
 3405: @end example
 3406: 
 3407: @code{Set-current ( wid -- )} sets the wordlist that will contain newly
 3408: defined words (the @emph{current} wordlist):
 3409: 
 3410: @example
 3411: mywords set-current
 3412: order
 3413: @end example
 3414: 
 3415: Gforth does not display a name for the wordlist in @code{mywords}
 3416: because this wordlist was created anonymously with @code{wordlist}.
 3417: 
 3418: You can get the current wordlist with @code{get-current ( -- wid)}.  If
 3419: you want to put something into a specific wordlist without overall
 3420: effect on the current wordlist, this typically looks like this:
 3421: 
 3422: @example
 3423: get-current mywords set-current ( wid )
 3424: create someword
 3425: ( wid ) set-current
 3426: @end example
 3427: 
 3428: You can write the search order with @code{set-order ( wid1 .. widn n --
 3429: )} and read it with @code{get-order ( -- wid1 .. widn n )}.  The first
 3430: searched wordlist is topmost.
 3431: 
 3432: @example
 3433: get-order mywords swap 1+ set-order
 3434: order
 3435: @end example
 3436: 
 3437: Yes, the order of wordlists in the output of @code{order} is reversed
 3438: from stack comments and the output of @code{.s} and thus unintuitive.
 3439: 
 3440: @quotation Assignment
 3441: Define @code{>order ( wid -- )} with adds @code{wid} as first searched
 3442: wordlist to the search order.  Define @code{previous ( -- )}, which
 3443: removes the first searched wordlist from the search order.  Experiment
 3444: with boundary conditions (you will see some crashes or situations that
 3445: are hard or impossible to leave).
 3446: @end quotation
 3447: 
 3448: The search order is a powerful foundation for providing features similar
 3449: to Modula-2 modules and C++ namespaces.  However, trying to modularize
 3450: programs in this way has disadvantages for debugging and reuse/factoring
 3451: that overcome the advantages in my experience (I don't do huge projects,
 3452: though).  These disadvantages are not so clear in other
 3453: languages/programming environments, because these languages are not so
 3454: strong in debugging and reuse.
 3455: 
 3456: @c !! example
 3457: 
 3458: Reference: @ref{Word Lists}.
 3459: 
 3460: @c ******************************************************************
 3461: @node Introduction, Words, Tutorial, Top
 3462: @comment node-name,     next,           previous, up
 3463: @chapter An Introduction to ANS Forth
 3464: @cindex Forth - an introduction
 3465: 
 3466: The difference of this chapter from the Tutorial (@pxref{Tutorial}) is
 3467: that it is slower-paced in its examples, but uses them to dive deep into
 3468: explaining Forth internals (not covered by the Tutorial).  Apart from
 3469: that, this chapter covers far less material.  It is suitable for reading
 3470: without using a computer.
 3471: 
 3472: The primary purpose of this manual is to document Gforth. However, since
 3473: Forth is not a widely-known language and there is a lack of up-to-date
 3474: teaching material, it seems worthwhile to provide some introductory
 3475: material.  For other sources of Forth-related
 3476: information, see @ref{Forth-related information}.
 3477: 
 3478: The examples in this section should work on any ANS Forth; the
 3479: output shown was produced using Gforth. Each example attempts to
 3480: reproduce the exact output that Gforth produces. If you try out the
 3481: examples (and you should), what you should type is shown @kbd{like this}
 3482: and Gforth's response is shown @code{like this}. The single exception is
 3483: that, where the example shows @key{RET} it means that you should
 3484: press the ``carriage return'' key. Unfortunately, some output formats for
 3485: this manual cannot show the difference between @kbd{this} and
 3486: @code{this} which will make trying out the examples harder (but not
 3487: impossible).
 3488: 
 3489: Forth is an unusual language. It provides an interactive development
 3490: environment which includes both an interpreter and compiler. Forth
 3491: programming style encourages you to break a problem down into many
 3492: @cindex factoring
 3493: small fragments (@dfn{factoring}), and then to develop and test each
 3494: fragment interactively. Forth advocates assert that breaking the
 3495: edit-compile-test cycle used by conventional programming languages can
 3496: lead to great productivity improvements.
 3497: 
 3498: @menu
 3499: * Introducing the Text Interpreter::  
 3500: * Stacks and Postfix notation::  
 3501: * Your first definition::       
 3502: * How does that work?::         
 3503: * Forth is written in Forth::   
 3504: * Review - elements of a Forth system::  
 3505: * Where to go next::            
 3506: * Exercises::                   
 3507: @end menu
 3508: 
 3509: @comment ----------------------------------------------
 3510: @node Introducing the Text Interpreter, Stacks and Postfix notation, Introduction, Introduction
 3511: @section Introducing the Text Interpreter
 3512: @cindex text interpreter
 3513: @cindex outer interpreter
 3514: 
 3515: @c IMO this is too detailed and the pace is too slow for
 3516: @c an introduction.  If you know German, take a look at
 3517: @c http://www.complang.tuwien.ac.at/anton/lvas/skriptum-stack.html 
 3518: @c to see how I do it - anton 
 3519: 
 3520: @c nac-> Where I have accepted your comments 100% and modified the text
 3521: @c accordingly, I have deleted your comments. Elsewhere I have added a
 3522: @c response like this to attempt to rationalise what I have done. Of
 3523: @c course, this is a very clumsy mechanism for something that would be
 3524: @c done far more efficiently over a beer. Please delete any dialogue
 3525: @c you consider closed.
 3526: 
 3527: When you invoke the Forth image, you will see a startup banner printed
 3528: and nothing else (if you have Gforth installed on your system, try
 3529: invoking it now, by typing @kbd{gforth@key{RET}}). Forth is now running
 3530: its command line interpreter, which is called the @dfn{Text Interpreter}
 3531: (also known as the @dfn{Outer Interpreter}).  (You will learn a lot
 3532: about the text interpreter as you read through this chapter, for more
 3533: detail @pxref{The Text Interpreter}).
 3534: 
 3535: Although it's not obvious, Forth is actually waiting for your
 3536: input. Type a number and press the @key{RET} key:
 3537: 
 3538: @example
 3539: @kbd{45@key{RET}}  ok
 3540: @end example
 3541: 
 3542: Rather than give you a prompt to invite you to input something, the text
 3543: interpreter prints a status message @i{after} it has processed a line
 3544: of input. The status message in this case (``@code{ ok}'' followed by
 3545: carriage-return) indicates that the text interpreter was able to process
 3546: all of your input successfully. Now type something illegal:
 3547: 
 3548: @example
 3549: @kbd{qwer341@key{RET}}
 3550: *the terminal*:2: Undefined word
 3551: >>>qwer341<<<
 3552: Backtrace:
 3553: $2A95B42A20 throw 
 3554: $2A95B57FB8 no.extensions 
 3555: @end example
 3556: 
 3557: The exact text, other than the ``Undefined word'' may differ slightly
 3558: on your system, but the effect is the same; when the text interpreter
 3559: detects an error, it discards any remaining text on a line, resets
 3560: certain internal state and prints an error message. For a detailed
 3561: description of error messages see @ref{Error messages}.
 3562: 
 3563: The text interpreter waits for you to press carriage-return, and then
 3564: processes your input line. Starting at the beginning of the line, it
 3565: breaks the line into groups of characters separated by spaces. For each
 3566: group of characters in turn, it makes two attempts to do something:
 3567: 
 3568: @itemize @bullet
 3569: @item
 3570: @cindex name dictionary
 3571: It tries to treat it as a command. It does this by searching a @dfn{name
 3572: dictionary}. If the group of characters matches an entry in the name
 3573: dictionary, the name dictionary provides the text interpreter with
 3574: information that allows the text interpreter perform some actions. In
 3575: Forth jargon, we say that the group
 3576: @cindex word
 3577: @cindex definition
 3578: @cindex execution token
 3579: @cindex xt
 3580: of characters names a @dfn{word}, that the dictionary search returns an
 3581: @dfn{execution token (xt)} corresponding to the @dfn{definition} of the
 3582: word, and that the text interpreter executes the xt. Often, the terms
 3583: @dfn{word} and @dfn{definition} are used interchangeably.
 3584: @item
 3585: If the text interpreter fails to find a match in the name dictionary, it
 3586: tries to treat the group of characters as a number in the current number
 3587: base (when you start up Forth, the current number base is base 10). If
 3588: the group of characters legitimately represents a number, the text
 3589: interpreter pushes the number onto a stack (we'll learn more about that
 3590: in the next section).
 3591: @end itemize
 3592: 
 3593: If the text interpreter is unable to do either of these things with any
 3594: group of characters, it discards the group of characters and the rest of
 3595: the line, then prints an error message. If the text interpreter reaches
 3596: the end of the line without error, it prints the status message ``@code{ ok}''
 3597: followed by carriage-return.
 3598: 
 3599: This is the simplest command we can give to the text interpreter:
 3600: 
 3601: @example
 3602: @key{RET}  ok
 3603: @end example
 3604: 
 3605: The text interpreter did everything we asked it to do (nothing) without
 3606: an error, so it said that everything is ``@code{ ok}''. Try a slightly longer
 3607: command:
 3608: 
 3609: @example
 3610: @kbd{12 dup fred dup@key{RET}}
 3611: *the terminal*:3: Undefined word
 3612: 12 dup >>>fred<<< dup
 3613: Backtrace:
 3614: $2A95B42A20 throw 
 3615: $2A95B57FB8 no.extensions 
 3616: @end example
 3617: 
 3618: When you press the carriage-return key, the text interpreter starts to
 3619: work its way along the line:
 3620: 
 3621: @itemize @bullet
 3622: @item
 3623: When it gets to the space after the @code{2}, it takes the group of
 3624: characters @code{12} and looks them up in the name
 3625: dictionary@footnote{We can't tell if it found them or not, but assume
 3626: for now that it did not}. There is no match for this group of characters
 3627: in the name dictionary, so it tries to treat them as a number. It is
 3628: able to do this successfully, so it puts the number, 12, ``on the stack''
 3629: (whatever that means).
 3630: @item
 3631: The text interpreter resumes scanning the line and gets the next group
 3632: of characters, @code{dup}. It looks it up in the name dictionary and
 3633: (you'll have to take my word for this) finds it, and executes the word
 3634: @code{dup} (whatever that means).
 3635: @item
 3636: Once again, the text interpreter resumes scanning the line and gets the
 3637: group of characters @code{fred}. It looks them up in the name
 3638: dictionary, but can't find them. It tries to treat them as a number, but
 3639: they don't represent any legal number.
 3640: @end itemize
 3641: 
 3642: At this point, the text interpreter gives up and prints an error
 3643: message. The error message shows exactly how far the text interpreter
 3644: got in processing the line. In particular, it shows that the text
 3645: interpreter made no attempt to do anything with the final character
 3646: group, @code{dup}, even though we have good reason to believe that the
 3647: text interpreter would have no problem looking that word up and
 3648: executing it a second time.
 3649: 
 3650: 
 3651: @comment ----------------------------------------------
 3652: @node Stacks and Postfix notation, Your first definition, Introducing the Text Interpreter, Introduction
 3653: @section Stacks, postfix notation and parameter passing
 3654: @cindex text interpreter
 3655: @cindex outer interpreter
 3656: 
 3657: In procedural programming languages (like C and Pascal), the
 3658: building-block of programs is the @dfn{function} or @dfn{procedure}. These
 3659: functions or procedures are called with @dfn{explicit parameters}. For
 3660: example, in C we might write:
 3661: 
 3662: @example
 3663: total = total + new_volume(length,height,depth);
 3664: @end example
 3665: 
 3666: @noindent
 3667: where new_volume is a function-call to another piece of code, and total,
 3668: length, height and depth are all variables. length, height and depth are
 3669: parameters to the function-call.
 3670: 
 3671: In Forth, the equivalent of the function or procedure is the
 3672: @dfn{definition} and parameters are implicitly passed between
 3673: definitions using a shared stack that is visible to the
 3674: programmer. Although Forth does support variables, the existence of the
 3675: stack means that they are used far less often than in most other
 3676: programming languages. When the text interpreter encounters a number, it
 3677: will place (@dfn{push}) it on the stack. There are several stacks (the
 3678: actual number is implementation-dependent ...) and the particular stack
 3679: used for any operation is implied unambiguously by the operation being
 3680: performed. The stack used for all integer operations is called the @dfn{data
 3681: stack} and, since this is the stack used most commonly, references to
 3682: ``the data stack'' are often abbreviated to ``the stack''.
 3683: 
 3684: The stacks have a last-in, first-out (LIFO) organisation. If you type:
 3685: 
 3686: @example
 3687: @kbd{1 2 3@key{RET}}  ok
 3688: @end example
 3689: 
 3690: Then this instructs the text interpreter to placed three numbers on the
 3691: (data) stack. An analogy for the behaviour of the stack is to take a
 3692: pack of playing cards and deal out the ace (1), 2 and 3 into a pile on
 3693: the table. The 3 was the last card onto the pile (``last-in'') and if
 3694: you take a card off the pile then, unless you're prepared to fiddle a
 3695: bit, the card that you take off will be the 3 (``first-out''). The
 3696: number that will be first-out of the stack is called the @dfn{top of
 3697: stack}, which
 3698: @cindex TOS definition
 3699: is often abbreviated to @dfn{TOS}.
 3700: 
 3701: To understand how parameters are passed in Forth, consider the
 3702: behaviour of the definition @code{+} (pronounced ``plus''). You will not
 3703: be surprised to learn that this definition performs addition. More
 3704: precisely, it adds two number together and produces a result. Where does
 3705: it get the two numbers from? It takes the top two numbers off the
 3706: stack. Where does it place the result? On the stack. You can act-out the
 3707: behaviour of @code{+} with your playing cards like this:
 3708: 
 3709: @itemize @bullet
 3710: @item
 3711: Pick up two cards from the stack on the table
 3712: @item
 3713: Stare at them intently and ask yourself ``what @i{is} the sum of these two
 3714: numbers''
 3715: @item
 3716: Decide that the answer is 5
 3717: @item
 3718: Shuffle the two cards back into the pack and find a 5
 3719: @item
 3720: Put a 5 on the remaining ace that's on the table.
 3721: @end itemize
 3722: 
 3723: If you don't have a pack of cards handy but you do have Forth running,
 3724: you can use the definition @code{.s} to show the current state of the stack,
 3725: without affecting the stack. Type:
 3726: 
 3727: @example
 3728: @kbd{clearstacks 1 2 3@key{RET}} ok
 3729: @kbd{.s@key{RET}} <3> 1 2 3  ok
 3730: @end example
 3731: 
 3732: The text interpreter looks up the word @code{clearstacks} and executes
 3733: it; it tidies up the stacks and removes any entries that may have been
 3734: left on it by earlier examples. The text interpreter pushes each of the
 3735: three numbers in turn onto the stack. Finally, the text interpreter
 3736: looks up the word @code{.s} and executes it. The effect of executing
 3737: @code{.s} is to print the ``<3>'' (the total number of items on the stack)
 3738: followed by a list of all the items on the stack; the item on the far
 3739: right-hand side is the TOS.
 3740: 
 3741: You can now type:
 3742: 
 3743: @example
 3744: @kbd{+ .s@key{RET}} <2> 1 5  ok
 3745: @end example
 3746: 
 3747: @noindent
 3748: which is correct; there are now 2 items on the stack and the result of
 3749: the addition is 5.
 3750: 
 3751: If you're playing with cards, try doing a second addition: pick up the
 3752: two cards, work out that their sum is 6, shuffle them into the pack,
 3753: look for a 6 and place that on the table. You now have just one item on
 3754: the stack. What happens if you try to do a third addition? Pick up the
 3755: first card, pick up the second card -- ah! There is no second card. This
 3756: is called a @dfn{stack underflow} and consitutes an error. If you try to
 3757: do the same thing with Forth it often reports an error (probably a Stack
 3758: Underflow or an Invalid Memory Address error).
 3759: 
 3760: The opposite situation to a stack underflow is a @dfn{stack overflow},
 3761: which simply accepts that there is a finite amount of storage space
 3762: reserved for the stack. To stretch the playing card analogy, if you had
 3763: enough packs of cards and you piled the cards up on the table, you would
 3764: eventually be unable to add another card; you'd hit the ceiling. Gforth
 3765: allows you to set the maximum size of the stacks. In general, the only
 3766: time that you will get a stack overflow is because a definition has a
 3767: bug in it and is generating data on the stack uncontrollably.
 3768: 
 3769: There's one final use for the playing card analogy. If you model your
 3770: stack using a pack of playing cards, the maximum number of items on
 3771: your stack will be 52 (I assume you didn't use the Joker). The maximum
 3772: @i{value} of any item on the stack is 13 (the King). In fact, the only
 3773: possible numbers are positive integer numbers 1 through 13; you can't
 3774: have (for example) 0 or 27 or 3.52 or -2. If you change the way you
 3775: think about some of the cards, you can accommodate different
 3776: numbers. For example, you could think of the Jack as representing 0,
 3777: the Queen as representing -1 and the King as representing -2. Your
 3778: @i{range} remains unchanged (you can still only represent a total of 13
 3779: numbers) but the numbers that you can represent are -2 through 10.
 3780: 
 3781: In that analogy, the limit was the amount of information that a single
 3782: stack entry could hold, and Forth has a similar limit. In Forth, the
 3783: size of a stack entry is called a @dfn{cell}. The actual size of a cell is
 3784: implementation dependent and affects the maximum value that a stack
 3785: entry can hold. A Standard Forth provides a cell size of at least
 3786: 16-bits, and most desktop systems use a cell size of 32-bits.
 3787: 
 3788: Forth does not do any type checking for you, so you are free to
 3789: manipulate and combine stack items in any way you wish. A convenient way
 3790: of treating stack items is as 2's complement signed integers, and that
 3791: is what Standard words like @code{+} do. Therefore you can type:
 3792: 
 3793: @example
 3794: @kbd{-5 12 + .s@key{RET}} <1> 7  ok
 3795: @end example
 3796: 
 3797: If you use numbers and definitions like @code{+} in order to turn Forth
 3798: into a great big pocket calculator, you will realise that it's rather
 3799: different from a normal calculator. Rather than typing 2 + 3 = you had
 3800: to type 2 3 + (ignore the fact that you had to use @code{.s} to see the
 3801: result). The terminology used to describe this difference is to say that
 3802: your calculator uses @dfn{Infix Notation} (parameters and operators are
 3803: mixed) whilst Forth uses @dfn{Postfix Notation} (parameters and
 3804: operators are separate), also called @dfn{Reverse Polish Notation}.
 3805: 
 3806: Whilst postfix notation might look confusing to begin with, it has
 3807: several important advantages:
 3808: 
 3809: @itemize @bullet
 3810: @item
 3811: it is unambiguous
 3812: @item
 3813: it is more concise
 3814: @item
 3815: it fits naturally with a stack-based system
 3816: @end itemize
 3817: 
 3818: To examine these claims in more detail, consider these sums:
 3819: 
 3820: @example
 3821: 6 + 5 * 4 =
 3822: 4 * 5 + 6 =
 3823: @end example
 3824: 
 3825: If you're just learning maths or your maths is very rusty, you will
 3826: probably come up with the answer 44 for the first and 26 for the
 3827: second. If you are a bit of a whizz at maths you will remember the
 3828: @i{convention} that multiplication takes precendence over addition, and
 3829: you'd come up with the answer 26 both times. To explain the answer 26
 3830: to someone who got the answer 44, you'd probably rewrite the first sum
 3831: like this:
 3832: 
 3833: @example
 3834: 6 + (5 * 4) =
 3835: @end example
 3836: 
 3837: If what you really wanted was to perform the addition before the
 3838: multiplication, you would have to use parentheses to force it.
 3839: 
 3840: If you did the first two sums on a pocket calculator you would probably
 3841: get the right answers, unless you were very cautious and entered them using
 3842: these keystroke sequences:
 3843: 
 3844: 6 + 5 = * 4 =
 3845: 4 * 5 = + 6 =
 3846: 
 3847: Postfix notation is unambiguous because the order that the operators
 3848: are applied is always explicit; that also means that parentheses are
 3849: never required. The operators are @i{active} (the act of quoting the
 3850: operator makes the operation occur) which removes the need for ``=''.
 3851: 
 3852: The sum 6 + 5 * 4 can be written (in postfix notation) in two
 3853: equivalent ways:
 3854: 
 3855: @example
 3856: 6 5 4 * +      or:
 3857: 5 4 * 6 +
 3858: @end example
 3859: 
 3860: An important thing that you should notice about this notation is that
 3861: the @i{order} of the numbers does not change; if you want to subtract
 3862: 2 from 10 you type @code{10 2 -}.
 3863: 
 3864: The reason that Forth uses postfix notation is very simple to explain: it
 3865: makes the implementation extremely simple, and it follows naturally from
 3866: using the stack as a mechanism for passing parameters. Another way of
 3867: thinking about this is to realise that all Forth definitions are
 3868: @i{active}; they execute as they are encountered by the text
 3869: interpreter. The result of this is that the syntax of Forth is trivially
 3870: simple.
 3871: 
 3872: 
 3873: 
 3874: @comment ----------------------------------------------
 3875: @node Your first definition, How does that work?, Stacks and Postfix notation, Introduction
 3876: @section Your first Forth definition
 3877: @cindex first definition
 3878: 
 3879: Until now, the examples we've seen have been trivial; we've just been
 3880: using Forth as a bigger-than-pocket calculator. Also, each calculation
 3881: we've shown has been a ``one-off'' -- to repeat it we'd need to type it in
 3882: again@footnote{That's not quite true. If you press the up-arrow key on
 3883: your keyboard you should be able to scroll back to any earlier command,
 3884: edit it and re-enter it.} In this section we'll see how to add new
 3885: words to Forth's vocabulary.
 3886: 
 3887: The easiest way to create a new word is to use a @dfn{colon
 3888: definition}. We'll define a few and try them out before worrying too
 3889: much about how they work. Try typing in these examples; be careful to
 3890: copy the spaces accurately:
 3891: 
 3892: @example
 3893: : add-two 2 + . ;
 3894: : greet ." Hello and welcome" ;
 3895: : demo 5 add-two ;
 3896: @end example
 3897: 
 3898: @noindent
 3899: Now try them out:
 3900: 
 3901: @example
 3902: @kbd{greet@key{RET}} Hello and welcome  ok
 3903: @kbd{greet greet@key{RET}} Hello and welcomeHello and welcome  ok
 3904: @kbd{4 add-two@key{RET}} 6  ok
 3905: @kbd{demo@key{RET}} 7  ok
 3906: @kbd{9 greet demo add-two@key{RET}} Hello and welcome7 11  ok
 3907: @end example
 3908: 
 3909: The first new thing that we've introduced here is the pair of words
 3910: @code{:} and @code{;}. These are used to start and terminate a new
 3911: definition, respectively. The first word after the @code{:} is the name
 3912: for the new definition.
 3913: 
 3914: As you can see from the examples, a definition is built up of words that
 3915: have already been defined; Forth makes no distinction between
 3916: definitions that existed when you started the system up, and those that
 3917: you define yourself.
 3918: 
 3919: The examples also introduce the words @code{.} (dot), @code{."}
 3920: (dot-quote) and @code{dup} (dewp). Dot takes the value from the top of
 3921: the stack and displays it. It's like @code{.s} except that it only
 3922: displays the top item of the stack and it is destructive; after it has
 3923: executed, the number is no longer on the stack. There is always one
 3924: space printed after the number, and no spaces before it. Dot-quote
 3925: defines a string (a sequence of characters) that will be printed when
 3926: the word is executed. The string can contain any printable characters
 3927: except @code{"}. A @code{"} has a special function; it is not a Forth
 3928: word but it acts as a delimiter (the way that delimiters work is
 3929: described in the next section). Finally, @code{dup} duplicates the value
 3930: at the top of the stack. Try typing @code{5 dup .s} to see what it does.
 3931: 
 3932: We already know that the text interpreter searches through the
 3933: dictionary to locate names. If you've followed the examples earlier, you
 3934: will already have a definition called @code{add-two}. Lets try modifying
 3935: it by typing in a new definition:
 3936: 
 3937: @example
 3938: @kbd{: add-two dup . ." + 2 =" 2 + . ;@key{RET}} redefined add-two  ok
 3939: @end example
 3940: 
 3941: Forth recognised that we were defining a word that already exists, and
 3942: printed a message to warn us of that fact. Let's try out the new
 3943: definition:
 3944: 
 3945: @example
 3946: @kbd{9 add-two@key{RET}} 9 + 2 =11  ok
 3947: @end example
 3948: 
 3949: @noindent
 3950: All that we've actually done here, though, is to create a new
 3951: definition, with a particular name. The fact that there was already a
 3952: definition with the same name did not make any difference to the way
 3953: that the new definition was created (except that Forth printed a warning
 3954: message). The old definition of add-two still exists (try @code{demo}
 3955: again to see that this is true). Any new definition will use the new
 3956: definition of @code{add-two}, but old definitions continue to use the
 3957: version that already existed at the time that they were @code{compiled}.
 3958: 
 3959: Before you go on to the next section, try defining and redefining some
 3960: words of your own.
 3961: 
 3962: @comment ----------------------------------------------
 3963: @node How does that work?, Forth is written in Forth, Your first definition, Introduction
 3964: @section How does that work?
 3965: @cindex parsing words
 3966: 
 3967: @c That's pretty deep (IMO way too deep) for an introduction. - anton
 3968: 
 3969: @c Is it a good idea to talk about the interpretation semantics of a
 3970: @c number? We don't have an xt to go along with it. - anton
 3971: 
 3972: @c Now that I have eliminated execution semantics, I wonder if it would not
 3973: @c be better to keep them (or add run-time semantics), to make it easier to
 3974: @c explain what compilation semantics usually does. - anton
 3975: 
 3976: @c nac-> I removed the term ``default compilation sematics'' from the
 3977: @c introductory chapter. Removing ``execution semantics'' was making
 3978: @c everything simpler to explain, then I think the use of this term made
 3979: @c everything more complex again. I replaced it with ``default
 3980: @c semantics'' (which is used elsewhere in the manual) by which I mean
 3981: @c ``a definition that has neither the immediate nor the compile-only
 3982: @c flag set''.
 3983: 
 3984: @c anton: I have eliminated default semantics (except in one place where it
 3985: @c means "default interpretation and compilation semantics"), because it
 3986: @c makes no sense in the presence of combined words.  I reverted to
 3987: @c "execution semantics" where necessary.
 3988: 
 3989: @c nac-> I reworded big chunks of the ``how does that work''
 3990: @c section (and, unusually for me, I think I even made it shorter!).  See
 3991: @c what you think -- I know I have not addressed your primary concern
 3992: @c that it is too heavy-going for an introduction. From what I understood
 3993: @c of your course notes it looks as though they might be a good framework. 
 3994: @c Things that I've tried to capture here are some things that came as a
 3995: @c great revelation here when I first understood them. Also, I like the
 3996: @c fact that a very simple code example shows up almost all of the issues
 3997: @c that you need to understand to see how Forth works. That's unique and
 3998: @c worthwhile to emphasise.
 3999: 
 4000: @c anton: I think it's a good idea to present the details, especially those
 4001: @c that you found to be a revelation, and probably the tutorial tries to be
 4002: @c too superficial and does not get some of the things across that make
 4003: @c Forth special.  I do believe that most of the time these things should
 4004: @c be discussed at the end of a section or in separate sections instead of
 4005: @c in the middle of a section (e.g., the stuff you added in "User-defined
 4006: @c defining words" leads in a completely different direction from the rest
 4007: @c of the section).
 4008: 
 4009: Now we're going to take another look at the definition of @code{add-two}
 4010: from the previous section. From our knowledge of the way that the text
 4011: interpreter works, we would have expected this result when we tried to
 4012: define @code{add-two}:
 4013: 
 4014: @example
 4015: @kbd{: add-two 2 + . ;@key{RET}}
 4016: *the terminal*:4: Undefined word
 4017: : >>>add-two<<< 2 + . ;
 4018: @end example
 4019: 
 4020: The reason that this didn't happen is bound up in the way that @code{:}
 4021: works. The word @code{:} does two special things. The first special
 4022: thing that it does prevents the text interpreter from ever seeing the
 4023: characters @code{add-two}. The text interpreter uses a variable called
 4024: @cindex modifying >IN
 4025: @code{>IN} (pronounced ``to-in'') to keep track of where it is in the
 4026: input line. When it encounters the word @code{:} it behaves in exactly
 4027: the same way as it does for any other word; it looks it up in the name
 4028: dictionary, finds its xt and executes it. When @code{:} executes, it
 4029: looks at the input buffer, finds the word @code{add-two} and advances the
 4030: value of @code{>IN} to point past it. It then does some other stuff
 4031: associated with creating the new definition (including creating an entry
 4032: for @code{add-two} in the name dictionary). When the execution of @code{:}
 4033: completes, control returns to the text interpreter, which is oblivious
 4034: to the fact that it has been tricked into ignoring part of the input
 4035: line.
 4036: 
 4037: @cindex parsing words
 4038: Words like @code{:} -- words that advance the value of @code{>IN} and so
 4039: prevent the text interpreter from acting on the whole of the input line
 4040: -- are called @dfn{parsing words}.
 4041: 
 4042: @cindex @code{state} - effect on the text interpreter
 4043: @cindex text interpreter - effect of state
 4044: The second special thing that @code{:} does is change the value of a
 4045: variable called @code{state}, which affects the way that the text
 4046: interpreter behaves. When Gforth starts up, @code{state} has the value
 4047: 0, and the text interpreter is said to be @dfn{interpreting}. During a
 4048: colon definition (started with @code{:}), @code{state} is set to -1 and
 4049: the text interpreter is said to be @dfn{compiling}.
 4050: 
 4051: In this example, the text interpreter is compiling when it processes the
 4052: string ``@code{2 + . ;}''. It still breaks the string down into
 4053: character sequences in the same way. However, instead of pushing the
 4054: number @code{2} onto the stack, it lays down (@dfn{compiles}) some magic
 4055: into the definition of @code{add-two} that will make the number @code{2} get
 4056: pushed onto the stack when @code{add-two} is @dfn{executed}. Similarly,
 4057: the behaviours of @code{+} and @code{.} are also compiled into the
 4058: definition.
 4059: 
 4060: One category of words don't get compiled. These so-called @dfn{immediate
 4061: words} get executed (performed @i{now}) regardless of whether the text
 4062: interpreter is interpreting or compiling. The word @code{;} is an
 4063: immediate word. Rather than being compiled into the definition, it
 4064: executes. Its effect is to terminate the current definition, which
 4065: includes changing the value of @code{state} back to 0.
 4066: 
 4067: When you execute @code{add-two}, it has a @dfn{run-time effect} that is
 4068: exactly the same as if you had typed @code{2 + . @key{RET}} outside of a
 4069: definition.
 4070: 
 4071: In Forth, every word or number can be described in terms of two
 4072: properties:
 4073: 
 4074: @itemize @bullet
 4075: @item
 4076: @cindex interpretation semantics
 4077: Its @dfn{interpretation semantics} describe how it will behave when the
 4078: text interpreter encounters it in @dfn{interpret} state. The
 4079: interpretation semantics of a word are represented by an @dfn{execution
 4080: token}.
 4081: @item
 4082: @cindex compilation semantics
 4083: Its @dfn{compilation semantics} describe how it will behave when the
 4084: text interpreter encounters it in @dfn{compile} state. The compilation
 4085: semantics of a word are represented in an implementation-dependent way;
 4086: Gforth uses a @dfn{compilation token}.
 4087: @end itemize
 4088: 
 4089: @noindent
 4090: Numbers are always treated in a fixed way:
 4091: 
 4092: @itemize @bullet
 4093: @item
 4094: When the number is @dfn{interpreted}, its behaviour is to push the
 4095: number onto the stack.
 4096: @item
 4097: When the number is @dfn{compiled}, a piece of code is appended to the
 4098: current definition that pushes the number when it runs. (In other words,
 4099: the compilation semantics of a number are to postpone its interpretation
 4100: semantics until the run-time of the definition that it is being compiled
 4101: into.)
 4102: @end itemize
 4103: 
 4104: Words don't behave in such a regular way, but most have @i{default
 4105: semantics} which means that they behave like this:
 4106: 
 4107: @itemize @bullet
 4108: @item
 4109: The @dfn{interpretation semantics} of the word are to do something useful.
 4110: @item
 4111: The @dfn{compilation semantics} of the word are to append its
 4112: @dfn{interpretation semantics} to the current definition (so that its
 4113: run-time behaviour is to do something useful).
 4114: @end itemize
 4115: 
 4116: @cindex immediate words
 4117: The actual behaviour of any particular word can be controlled by using
 4118: the words @code{immediate} and @code{compile-only} when the word is
 4119: defined. These words set flags in the name dictionary entry of the most
 4120: recently defined word, and these flags are retrieved by the text
 4121: interpreter when it finds the word in the name dictionary.
 4122: 
 4123: A word that is marked as @dfn{immediate} has compilation semantics that
 4124: are identical to its interpretation semantics. In other words, it
 4125: behaves like this:
 4126: 
 4127: @itemize @bullet
 4128: @item
 4129: The @dfn{interpretation semantics} of the word are to do something useful.
 4130: @item
 4131: The @dfn{compilation semantics} of the word are to do something useful
 4132: (and actually the same thing); i.e., it is executed during compilation.
 4133: @end itemize
 4134: 
 4135: Marking a word as @dfn{compile-only} prohibits the text interpreter from
 4136: performing the interpretation semantics of the word directly; an attempt
 4137: to do so will generate an error. It is never necessary to use
 4138: @code{compile-only} (and it is not even part of ANS Forth, though it is
 4139: provided by many implementations) but it is good etiquette to apply it
 4140: to a word that will not behave correctly (and might have unexpected
 4141: side-effects) in interpret state. For example, it is only legal to use
 4142: the conditional word @code{IF} within a definition. If you forget this
 4143: and try to use it elsewhere, the fact that (in Gforth) it is marked as
 4144: @code{compile-only} allows the text interpreter to generate a helpful
 4145: error message rather than subjecting you to the consequences of your
 4146: folly.
 4147: 
 4148: This example shows the difference between an immediate and a
 4149: non-immediate word:
 4150: 
 4151: @example
 4152: : show-state state @@ . ;
 4153: : show-state-now show-state ; immediate
 4154: : word1 show-state ;
 4155: : word2 show-state-now ;
 4156: @end example
 4157: 
 4158: The word @code{immediate} after the definition of @code{show-state-now}
 4159: makes that word an immediate word. These definitions introduce a new
 4160: word: @code{@@} (pronounced ``fetch''). This word fetches the value of a
 4161: variable, and leaves it on the stack. Therefore, the behaviour of
 4162: @code{show-state} is to print a number that represents the current value
 4163: of @code{state}.
 4164: 
 4165: When you execute @code{word1}, it prints the number 0, indicating that
 4166: the system is interpreting. When the text interpreter compiled the
 4167: definition of @code{word1}, it encountered @code{show-state} whose
 4168: compilation semantics are to append its interpretation semantics to the
 4169: current definition. When you execute @code{word1}, it performs the
 4170: interpretation semantics of @code{show-state}.  At the time that @code{word1}
 4171: (and therefore @code{show-state}) are executed, the system is
 4172: interpreting.
 4173: 
 4174: When you pressed @key{RET} after entering the definition of @code{word2},
 4175: you should have seen the number -1 printed, followed by ``@code{
 4176: ok}''. When the text interpreter compiled the definition of
 4177: @code{word2}, it encountered @code{show-state-now}, an immediate word,
 4178: whose compilation semantics are therefore to perform its interpretation
 4179: semantics. It is executed straight away (even before the text
 4180: interpreter has moved on to process another group of characters; the
 4181: @code{;} in this example). The effect of executing it are to display the
 4182: value of @code{state} @i{at the time that the definition of}
 4183: @code{word2} @i{is being defined}. Printing -1 demonstrates that the
 4184: system is compiling at this time. If you execute @code{word2} it does
 4185: nothing at all.
 4186: 
 4187: @cindex @code{."}, how it works
 4188: Before leaving the subject of immediate words, consider the behaviour of
 4189: @code{."} in the definition of @code{greet}, in the previous
 4190: section. This word is both a parsing word and an immediate word. Notice
 4191: that there is a space between @code{."} and the start of the text
 4192: @code{Hello and welcome}, but that there is no space between the last
 4193: letter of @code{welcome} and the @code{"} character. The reason for this
 4194: is that @code{."} is a Forth word; it must have a space after it so that
 4195: the text interpreter can identify it. The @code{"} is not a Forth word;
 4196: it is a @dfn{delimiter}. The examples earlier show that, when the string
 4197: is displayed, there is neither a space before the @code{H} nor after the
 4198: @code{e}. Since @code{."} is an immediate word, it executes at the time
 4199: that @code{greet} is defined. When it executes, its behaviour is to
 4200: search forward in the input line looking for the delimiter. When it
 4201: finds the delimiter, it updates @code{>IN} to point past the
 4202: delimiter. It also compiles some magic code into the definition of
 4203: @code{greet}; the xt of a run-time routine that prints a text string. It
 4204: compiles the string @code{Hello and welcome} into memory so that it is
 4205: available to be printed later. When the text interpreter gains control,
 4206: the next word it finds in the input stream is @code{;} and so it
 4207: terminates the definition of @code{greet}.
 4208: 
 4209: 
 4210: @comment ----------------------------------------------
 4211: @node Forth is written in Forth, Review - elements of a Forth system, How does that work?, Introduction
 4212: @section Forth is written in Forth
 4213: @cindex structure of Forth programs
 4214: 
 4215: When you start up a Forth compiler, a large number of definitions
 4216: already exist. In Forth, you develop a new application using bottom-up
 4217: programming techniques to create new definitions that are defined in
 4218: terms of existing definitions. As you create each definition you can
 4219: test and debug it interactively.
 4220: 
 4221: If you have tried out the examples in this section, you will probably
 4222: have typed them in by hand; when you leave Gforth, your definitions will
 4223: be lost. You can avoid this by using a text editor to enter Forth source
 4224: code into a file, and then loading code from the file using
 4225: @code{include} (@pxref{Forth source files}). A Forth source file is
 4226: processed by the text interpreter, just as though you had typed it in by
 4227: hand@footnote{Actually, there are some subtle differences -- see
 4228: @ref{The Text Interpreter}.}.
 4229: 
 4230: Gforth also supports the traditional Forth alternative to using text
 4231: files for program entry (@pxref{Blocks}).
 4232: 
 4233: In common with many, if not most, Forth compilers, most of Gforth is
 4234: actually written in Forth. All of the @file{.fs} files in the
 4235: installation directory@footnote{For example,
 4236: @file{/usr/local/share/gforth...}} are Forth source files, which you can
 4237: study to see examples of Forth programming.
 4238: 
 4239: Gforth maintains a history file that records every line that you type to
 4240: the text interpreter. This file is preserved between sessions, and is
 4241: used to provide a command-line recall facility. If you enter long
 4242: definitions by hand, you can use a text editor to paste them out of the
 4243: history file into a Forth source file for reuse at a later time
 4244: (for more information @pxref{Command-line editing}).
 4245: 
 4246: 
 4247: @comment ----------------------------------------------
 4248: @node Review - elements of a Forth system, Where to go next, Forth is written in Forth, Introduction
 4249: @section Review - elements of a Forth system
 4250: @cindex elements of a Forth system
 4251: 
 4252: To summarise this chapter:
 4253: 
 4254: @itemize @bullet
 4255: @item
 4256: Forth programs use @dfn{factoring} to break a problem down into small
 4257: fragments called @dfn{words} or @dfn{definitions}.
 4258: @item
 4259: Forth program development is an interactive process.
 4260: @item
 4261: The main command loop that accepts input, and controls both
 4262: interpretation and compilation, is called the @dfn{text interpreter}
 4263: (also known as the @dfn{outer interpreter}).
 4264: @item
 4265: Forth has a very simple syntax, consisting of words and numbers
 4266: separated by spaces or carriage-return characters. Any additional syntax
 4267: is imposed by @dfn{parsing words}.
 4268: @item
 4269: Forth uses a stack to pass parameters between words. As a result, it
 4270: uses postfix notation.
 4271: @item
 4272: To use a word that has previously been defined, the text interpreter
 4273: searches for the word in the @dfn{name dictionary}.
 4274: @item
 4275: Words have @dfn{interpretation semantics} and @dfn{compilation semantics}.
 4276: @item
 4277: The text interpreter uses the value of @code{state} to select between
 4278: the use of the @dfn{interpretation semantics} and the  @dfn{compilation
 4279: semantics} of a word that it encounters.
 4280: @item
 4281: The relationship between the @dfn{interpretation semantics} and
 4282: @dfn{compilation semantics} for a word
 4283: depend upon the way in which the word was defined (for example, whether
 4284: it is an @dfn{immediate} word).
 4285: @item
 4286: Forth definitions can be implemented in Forth (called @dfn{high-level
 4287: definitions}) or in some other way (usually a lower-level language and
 4288: as a result often called @dfn{low-level definitions}, @dfn{code
 4289: definitions} or @dfn{primitives}).
 4290: @item
 4291: Many Forth systems are implemented mainly in Forth.
 4292: @end itemize
 4293: 
 4294: 
 4295: @comment ----------------------------------------------
 4296: @node Where to go next, Exercises, Review - elements of a Forth system, Introduction
 4297: @section Where To Go Next
 4298: @cindex where to go next
 4299: 
 4300: Amazing as it may seem, if you have read (and understood) this far, you
 4301: know almost all the fundamentals about the inner workings of a Forth
 4302: system. You certainly know enough to be able to read and understand the
 4303: rest of this manual and the ANS Forth document, to learn more about the
 4304: facilities that Forth in general and Gforth in particular provide. Even
 4305: scarier, you know almost enough to implement your own Forth system.
 4306: However, that's not a good idea just yet... better to try writing some
 4307: programs in Gforth.
 4308: 
 4309: Forth has such a rich vocabulary that it can be hard to know where to
 4310: start in learning it. This section suggests a few sets of words that are
 4311: enough to write small but useful programs. Use the word index in this
 4312: document to learn more about each word, then try it out and try to write
 4313: small definitions using it. Start by experimenting with these words:
 4314: 
 4315: @itemize @bullet
 4316: @item
 4317: Arithmetic: @code{+ - * / /MOD */ ABS INVERT}
 4318: @item
 4319: Comparison: @code{MIN MAX =}
 4320: @item
 4321: Logic: @code{AND OR XOR NOT}
 4322: @item
 4323: Stack manipulation: @code{DUP DROP SWAP OVER}
 4324: @item
 4325: Loops and decisions: @code{IF ELSE ENDIF ?DO I LOOP}
 4326: @item
 4327: Input/Output: @code{. ." EMIT CR KEY}
 4328: @item
 4329: Defining words: @code{: ; CREATE}
 4330: @item
 4331: Memory allocation words: @code{ALLOT ,}
 4332: @item
 4333: Tools: @code{SEE WORDS .S MARKER}
 4334: @end itemize
 4335: 
 4336: When you have mastered those, go on to:
 4337: 
 4338: @itemize @bullet
 4339: @item
 4340: More defining words: @code{VARIABLE CONSTANT VALUE TO CREATE DOES>}
 4341: @item
 4342: Memory access: @code{@@ !}
 4343: @end itemize
 4344: 
 4345: When you have mastered these, there's nothing for it but to read through
 4346: the whole of this manual and find out what you've missed.
 4347: 
 4348: @comment ----------------------------------------------
 4349: @node Exercises,  , Where to go next, Introduction
 4350: @section Exercises
 4351: @cindex exercises
 4352: 
 4353: TODO: provide a set of programming excercises linked into the stuff done
 4354: already and into other sections of the manual. Provide solutions to all
 4355: the exercises in a .fs file in the distribution.
 4356: 
 4357: @c Get some inspiration from Starting Forth and Kelly&Spies.
 4358: 
 4359: @c excercises:
 4360: @c 1. take inches and convert to feet and inches.
 4361: @c 2. take temperature and convert from fahrenheight to celcius;
 4362: @c    may need to care about symmetric vs floored??
 4363: @c 3. take input line and do character substitution
 4364: @c    to encipher or decipher
 4365: @c 4. as above but work on a file for in and out
 4366: @c 5. take input line and convert to pig-latin 
 4367: @c
 4368: @c thing of sets of things to exercise then come up with
 4369: @c problems that need those things.
 4370: 
 4371: 
 4372: @c ******************************************************************
 4373: @node Words, Error messages, Introduction, Top
 4374: @chapter Forth Words
 4375: @cindex words
 4376: 
 4377: @menu
 4378: * Notation::                    
 4379: * Case insensitivity::          
 4380: * Comments::                    
 4381: * Boolean Flags::               
 4382: * Arithmetic::                  
 4383: * Stack Manipulation::          
 4384: * Memory::                      
 4385: * Control Structures::          
 4386: * Defining Words::              
 4387: * Interpretation and Compilation Semantics::  
 4388: * Tokens for Words::            
 4389: * Compiling words::             
 4390: * The Text Interpreter::        
 4391: * The Input Stream::            
 4392: * Word Lists::                  
 4393: * Environmental Queries::       
 4394: * Files::                       
 4395: * Blocks::                      
 4396: * Other I/O::                   
 4397: * OS command line arguments::   
 4398: * Locals::                      
 4399: * Structures::                  
 4400: * Object-oriented Forth::       
 4401: * Programming Tools::           
 4402: * C Interface::                 
 4403: * Assembler and Code Words::    
 4404: * Threading Words::             
 4405: * Passing Commands to the OS::  
 4406: * Keeping track of Time::       
 4407: * Miscellaneous Words::         
 4408: @end menu
 4409: 
 4410: @node Notation, Case insensitivity, Words, Words
 4411: @section Notation
 4412: @cindex notation of glossary entries
 4413: @cindex format of glossary entries
 4414: @cindex glossary notation format
 4415: @cindex word glossary entry format
 4416: 
 4417: The Forth words are described in this section in the glossary notation
 4418: that has become a de-facto standard for Forth texts:
 4419: 
 4420: @format
 4421: @i{word}     @i{Stack effect}   @i{wordset}   @i{pronunciation}
 4422: @end format
 4423: @i{Description}
 4424: 
 4425: @table @var
 4426: @item word
 4427: The name of the word.
 4428: 
 4429: @item Stack effect
 4430: @cindex stack effect
 4431: The stack effect is written in the notation @code{@i{before} --
 4432: @i{after}}, where @i{before} and @i{after} describe the top of
 4433: stack entries before and after the execution of the word. The rest of
 4434: the stack is not touched by the word. The top of stack is rightmost,
 4435: i.e., a stack sequence is written as it is typed in. Note that Gforth
 4436: uses a separate floating point stack, but a unified stack
 4437: notation. Also, return stack effects are not shown in @i{stack
 4438: effect}, but in @i{Description}. The name of a stack item describes
 4439: the type and/or the function of the item. See below for a discussion of
 4440: the types.
 4441: 
 4442: All words have two stack effects: A compile-time stack effect and a
 4443: run-time stack effect. The compile-time stack-effect of most words is
 4444: @i{ -- }. If the compile-time stack-effect of a word deviates from
 4445: this standard behaviour, or the word does other unusual things at
 4446: compile time, both stack effects are shown; otherwise only the run-time
 4447: stack effect is shown.
 4448: 
 4449: Also note that in code templates or examples there can be comments in
 4450: parentheses that display the stack picture at this point; there is no
 4451: @code{--} in these places, because there is no before-after situation.
 4452: 
 4453: @cindex pronounciation of words
 4454: @item pronunciation
 4455: How the word is pronounced.
 4456: 
 4457: @cindex wordset
 4458: @cindex environment wordset
 4459: @item wordset
 4460: The ANS Forth standard is divided into several word sets. A standard
 4461: system need not support all of them. Therefore, in theory, the fewer
 4462: word sets your program uses the more portable it will be. However, we
 4463: suspect that most ANS Forth systems on personal machines will feature
 4464: all word sets. Words that are not defined in ANS Forth have
 4465: @code{gforth} or @code{gforth-internal} as word set. @code{gforth}
 4466: describes words that will work in future releases of Gforth;
 4467: @code{gforth-internal} words are more volatile. Environmental query
 4468: strings are also displayed like words; you can recognize them by the
 4469: @code{environment} in the word set field.
 4470: 
 4471: @item Description
 4472: A description of the behaviour of the word.
 4473: @end table
 4474: 
 4475: @cindex types of stack items
 4476: @cindex stack item types
 4477: The type of a stack item is specified by the character(s) the name
 4478: starts with:
 4479: 
 4480: @table @code
 4481: @item f
 4482: @cindex @code{f}, stack item type
 4483: Boolean flags, i.e. @code{false} or @code{true}.
 4484: @item c
 4485: @cindex @code{c}, stack item type
 4486: Char
 4487: @item w
 4488: @cindex @code{w}, stack item type
 4489: Cell, can contain an integer or an address
 4490: @item n
 4491: @cindex @code{n}, stack item type
 4492: signed integer
 4493: @item u
 4494: @cindex @code{u}, stack item type
 4495: unsigned integer
 4496: @item d
 4497: @cindex @code{d}, stack item type
 4498: double sized signed integer
 4499: @item ud
 4500: @cindex @code{ud}, stack item type
 4501: double sized unsigned integer
 4502: @item r
 4503: @cindex @code{r}, stack item type
 4504: Float (on the FP stack)
 4505: @item a-
 4506: @cindex @code{a_}, stack item type
 4507: Cell-aligned address
 4508: @item c-
 4509: @cindex @code{c_}, stack item type
 4510: Char-aligned address (note that a Char may have two bytes in Windows NT)
 4511: @item f-
 4512: @cindex @code{f_}, stack item type
 4513: Float-aligned address
 4514: @item df-
 4515: @cindex @code{df_}, stack item type
 4516: Address aligned for IEEE double precision float
 4517: @item sf-
 4518: @cindex @code{sf_}, stack item type
 4519: Address aligned for IEEE single precision float
 4520: @item xt
 4521: @cindex @code{xt}, stack item type
 4522: Execution token, same size as Cell
 4523: @item wid
 4524: @cindex @code{wid}, stack item type
 4525: Word list ID, same size as Cell
 4526: @item ior, wior
 4527: @cindex ior type description
 4528: @cindex wior type description
 4529: I/O result code, cell-sized.  In Gforth, you can @code{throw} iors.
 4530: @item f83name
 4531: @cindex @code{f83name}, stack item type
 4532: Pointer to a name structure
 4533: @item "
 4534: @cindex @code{"}, stack item type
 4535: string in the input stream (not on the stack). The terminating character
 4536: is a blank by default. If it is not a blank, it is shown in @code{<>}
 4537: quotes.
 4538: @end table
 4539: 
 4540: @comment ----------------------------------------------
 4541: @node Case insensitivity, Comments, Notation, Words
 4542: @section Case insensitivity
 4543: @cindex case sensitivity
 4544: @cindex upper and lower case
 4545: 
 4546: Gforth is case-insensitive; you can enter definitions and invoke
 4547: Standard words using upper, lower or mixed case (however,
 4548: @pxref{core-idef, Implementation-defined options, Implementation-defined
 4549: options}).
 4550: 
 4551: ANS Forth only @i{requires} implementations to recognise Standard words
 4552: when they are typed entirely in upper case. Therefore, a Standard
 4553: program must use upper case for all Standard words. You can use whatever
 4554: case you like for words that you define, but in a Standard program you
 4555: have to use the words in the same case that you defined them.
 4556: 
 4557: Gforth supports case sensitivity through @code{table}s (case-sensitive
 4558: wordlists, @pxref{Word Lists}).
 4559: 
 4560: Two people have asked how to convert Gforth to be case-sensitive; while
 4561: we think this is a bad idea, you can change all wordlists into tables
 4562: like this:
 4563: 
 4564: @example
 4565: ' table-find forth-wordlist wordlist-map @ !
 4566: @end example
 4567: 
 4568: Note that you now have to type the predefined words in the same case
 4569: that we defined them, which are varying.  You may want to convert them
 4570: to your favourite case before doing this operation (I won't explain how,
 4571: because if you are even contemplating doing this, you'd better have
 4572: enough knowledge of Forth systems to know this already).
 4573: 
 4574: @node Comments, Boolean Flags, Case insensitivity, Words
 4575: @section Comments
 4576: @cindex comments
 4577: 
 4578: Forth supports two styles of comment; the traditional @i{in-line} comment,
 4579: @code{(} and its modern cousin, the @i{comment to end of line}; @code{\}.
 4580: 
 4581: 
 4582: doc-(
 4583: doc-\
 4584: doc-\G
 4585: 
 4586: 
 4587: @node Boolean Flags, Arithmetic, Comments, Words
 4588: @section Boolean Flags
 4589: @cindex Boolean flags
 4590: 
 4591: A Boolean flag is cell-sized. A cell with all bits clear represents the
 4592: flag @code{false} and a flag with all bits set represents the flag
 4593: @code{true}. Words that check a flag (for example, @code{IF}) will treat
 4594: a cell that has @i{any} bit set as @code{true}.
 4595: @c on and off to Memory? 
 4596: @c true and false to "Bitwise operations" or "Numeric comparison"?
 4597: 
 4598: doc-true
 4599: doc-false
 4600: doc-on
 4601: doc-off
 4602: 
 4603: 
 4604: @node Arithmetic, Stack Manipulation, Boolean Flags, Words
 4605: @section Arithmetic
 4606: @cindex arithmetic words
 4607: 
 4608: @cindex division with potentially negative operands
 4609: Forth arithmetic is not checked, i.e., you will not hear about integer
 4610: overflow on addition or multiplication, you may hear about division by
 4611: zero if you are lucky. The operator is written after the operands, but
 4612: the operands are still in the original order. I.e., the infix @code{2-1}
 4613: corresponds to @code{2 1 -}. Forth offers a variety of division
 4614: operators. If you perform division with potentially negative operands,
 4615: you do not want to use @code{/} or @code{/mod} with its undefined
 4616: behaviour, but rather @code{fm/mod} or @code{sm/mod} (probably the
 4617: former, @pxref{Mixed precision}).
 4618: @comment TODO discuss the different division forms and the std approach
 4619: 
 4620: @menu
 4621: * Single precision::            
 4622: * Double precision::            Double-cell integer arithmetic
 4623: * Bitwise operations::          
 4624: * Numeric comparison::          
 4625: * Mixed precision::             Operations with single and double-cell integers
 4626: * Floating Point::              
 4627: @end menu
 4628: 
 4629: @node Single precision, Double precision, Arithmetic, Arithmetic
 4630: @subsection Single precision
 4631: @cindex single precision arithmetic words
 4632: 
 4633: @c !! cell undefined
 4634: 
 4635: By default, numbers in Forth are single-precision integers that are one
 4636: cell in size. They can be signed or unsigned, depending upon how you
 4637: treat them. For the rules used by the text interpreter for recognising
 4638: single-precision integers see @ref{Number Conversion}.
 4639: 
 4640: These words are all defined for signed operands, but some of them also
 4641: work for unsigned numbers: @code{+}, @code{1+}, @code{-}, @code{1-},
 4642: @code{*}.
 4643: 
 4644: doc-+
 4645: doc-1+
 4646: doc-under+
 4647: doc--
 4648: doc-1-
 4649: doc-*
 4650: doc-/
 4651: doc-mod
 4652: doc-/mod
 4653: doc-negate
 4654: doc-abs
 4655: doc-min
 4656: doc-max
 4657: doc-floored
 4658: 
 4659: 
 4660: @node Double precision, Bitwise operations, Single precision, Arithmetic
 4661: @subsection Double precision
 4662: @cindex double precision arithmetic words
 4663: 
 4664: For the rules used by the text interpreter for
 4665: recognising double-precision integers, see @ref{Number Conversion}.
 4666: 
 4667: A double precision number is represented by a cell pair, with the most
 4668: significant cell at the TOS. It is trivial to convert an unsigned single
 4669: to a double: simply push a @code{0} onto the TOS. Since numbers are
 4670: represented by Gforth using 2's complement arithmetic, converting a
 4671: signed single to a (signed) double requires sign-extension across the
 4672: most significant cell. This can be achieved using @code{s>d}. The moral
 4673: of the story is that you cannot convert a number without knowing whether
 4674: it represents an unsigned or a signed number.
 4675: 
 4676: These words are all defined for signed operands, but some of them also
 4677: work for unsigned numbers: @code{d+}, @code{d-}.
 4678: 
 4679: doc-s>d
 4680: doc-d>s
 4681: doc-d+
 4682: doc-d-
 4683: doc-dnegate
 4684: doc-dabs
 4685: doc-dmin
 4686: doc-dmax
 4687: 
 4688: 
 4689: @node Bitwise operations, Numeric comparison, Double precision, Arithmetic
 4690: @subsection Bitwise operations
 4691: @cindex bitwise operation words
 4692: 
 4693: 
 4694: doc-and
 4695: doc-or
 4696: doc-xor
 4697: doc-invert
 4698: doc-lshift
 4699: doc-rshift
 4700: doc-2*
 4701: doc-d2*
 4702: doc-2/
 4703: doc-d2/
 4704: 
 4705: 
 4706: @node Numeric comparison, Mixed precision, Bitwise operations, Arithmetic
 4707: @subsection Numeric comparison
 4708: @cindex numeric comparison words
 4709: 
 4710: Note that the words that compare for equality (@code{= <> 0= 0<> d= d<>
 4711: d0= d0<>}) work for for both signed and unsigned numbers.
 4712: 
 4713: doc-<
 4714: doc-<=
 4715: doc-<>
 4716: doc-=
 4717: doc->
 4718: doc->=
 4719: 
 4720: doc-0<
 4721: doc-0<=
 4722: doc-0<>
 4723: doc-0=
 4724: doc-0>
 4725: doc-0>=
 4726: 
 4727: doc-u<
 4728: doc-u<=
 4729: @c u<> and u= exist but are the same as <> and =
 4730: @c doc-u<>
 4731: @c doc-u=
 4732: doc-u>
 4733: doc-u>=
 4734: 
 4735: doc-within
 4736: 
 4737: doc-d<
 4738: doc-d<=
 4739: doc-d<>
 4740: doc-d=
 4741: doc-d>
 4742: doc-d>=
 4743: 
 4744: doc-d0<
 4745: doc-d0<=
 4746: doc-d0<>
 4747: doc-d0=
 4748: doc-d0>
 4749: doc-d0>=
 4750: 
 4751: doc-du<
 4752: doc-du<=
 4753: @c du<> and du= exist but are the same as d<> and d=
 4754: @c doc-du<>
 4755: @c doc-du=
 4756: doc-du>
 4757: doc-du>=
 4758: 
 4759: 
 4760: @node Mixed precision, Floating Point, Numeric comparison, Arithmetic
 4761: @subsection Mixed precision
 4762: @cindex mixed precision arithmetic words
 4763: 
 4764: 
 4765: doc-m+
 4766: doc-*/
 4767: doc-*/mod
 4768: doc-m*
 4769: doc-um*
 4770: doc-m*/
 4771: doc-um/mod
 4772: doc-fm/mod
 4773: doc-sm/rem
 4774: 
 4775: 
 4776: @node Floating Point,  , Mixed precision, Arithmetic
 4777: @subsection Floating Point
 4778: @cindex floating point arithmetic words
 4779: 
 4780: For the rules used by the text interpreter for
 4781: recognising floating-point numbers see @ref{Number Conversion}.
 4782: 
 4783: Gforth has a separate floating point stack, but the documentation uses
 4784: the unified notation.@footnote{It's easy to generate the separate
 4785: notation from that by just separating the floating-point numbers out:
 4786: e.g. @code{( n r1 u r2 -- r3 )} becomes @code{( n u -- ) ( F: r1 r2 --
 4787: r3 )}.}
 4788: 
 4789: @cindex floating-point arithmetic, pitfalls
 4790: Floating point numbers have a number of unpleasant surprises for the
 4791: unwary (e.g., floating point addition is not associative) and even a
 4792: few for the wary. You should not use them unless you know what you are
 4793: doing or you don't care that the results you get are totally bogus. If
 4794: you want to learn about the problems of floating point numbers (and
 4795: how to avoid them), you might start with @cite{David Goldberg,
 4796: @uref{http://docs.sun.com/source/806-3568/ncg_goldberg.html,What Every
 4797: Computer Scientist Should Know About Floating-Point Arithmetic}, ACM
 4798: Computing Surveys 23(1):5@minus{}48, March 1991}.
 4799: 
 4800: 
 4801: doc-d>f
 4802: doc-f>d
 4803: doc-f+
 4804: doc-f-
 4805: doc-f*
 4806: doc-f/
 4807: doc-fnegate
 4808: doc-fabs
 4809: doc-fmax
 4810: doc-fmin
 4811: doc-floor
 4812: doc-fround
 4813: doc-f**
 4814: doc-fsqrt
 4815: doc-fexp
 4816: doc-fexpm1
 4817: doc-fln
 4818: doc-flnp1
 4819: doc-flog
 4820: doc-falog
 4821: doc-f2*
 4822: doc-f2/
 4823: doc-1/f
 4824: doc-precision
 4825: doc-set-precision
 4826: 
 4827: @cindex angles in trigonometric operations
 4828: @cindex trigonometric operations
 4829: Angles in floating point operations are given in radians (a full circle
 4830: has 2 pi radians).
 4831: 
 4832: doc-fsin
 4833: doc-fcos
 4834: doc-fsincos
 4835: doc-ftan
 4836: doc-fasin
 4837: doc-facos
 4838: doc-fatan
 4839: doc-fatan2
 4840: doc-fsinh
 4841: doc-fcosh
 4842: doc-ftanh
 4843: doc-fasinh
 4844: doc-facosh
 4845: doc-fatanh
 4846: doc-pi
 4847: 
 4848: @cindex equality of floats
 4849: @cindex floating-point comparisons
 4850: One particular problem with floating-point arithmetic is that comparison
 4851: for equality often fails when you would expect it to succeed.  For this
 4852: reason approximate equality is often preferred (but you still have to
 4853: know what you are doing).  Also note that IEEE NaNs may compare
 4854: differently from what you might expect.  The comparison words are:
 4855: 
 4856: doc-f~rel
 4857: doc-f~abs
 4858: doc-f~
 4859: doc-f=
 4860: doc-f<>
 4861: 
 4862: doc-f<
 4863: doc-f<=
 4864: doc-f>
 4865: doc-f>=
 4866: 
 4867: doc-f0<
 4868: doc-f0<=
 4869: doc-f0<>
 4870: doc-f0=
 4871: doc-f0>
 4872: doc-f0>=
 4873: 
 4874: 
 4875: @node Stack Manipulation, Memory, Arithmetic, Words
 4876: @section Stack Manipulation
 4877: @cindex stack manipulation words
 4878: 
 4879: @cindex floating-point stack in the standard
 4880: Gforth maintains a number of separate stacks:
 4881: 
 4882: @cindex data stack
 4883: @cindex parameter stack
 4884: @itemize @bullet
 4885: @item
 4886: A data stack (also known as the @dfn{parameter stack}) -- for
 4887: characters, cells, addresses, and double cells.
 4888: 
 4889: @cindex floating-point stack
 4890: @item
 4891: A floating point stack -- for holding floating point (FP) numbers.
 4892: 
 4893: @cindex return stack
 4894: @item
 4895: A return stack -- for holding the return addresses of colon
 4896: definitions and other (non-FP) data.
 4897: 
 4898: @cindex locals stack
 4899: @item
 4900: A locals stack -- for holding local variables.
 4901: @end itemize
 4902: 
 4903: @menu
 4904: * Data stack::                  
 4905: * Floating point stack::        
 4906: * Return stack::                
 4907: * Locals stack::                
 4908: * Stack pointer manipulation::  
 4909: @end menu
 4910: 
 4911: @node Data stack, Floating point stack, Stack Manipulation, Stack Manipulation
 4912: @subsection Data stack
 4913: @cindex data stack manipulation words
 4914: @cindex stack manipulations words, data stack
 4915: 
 4916: 
 4917: doc-drop
 4918: doc-nip
 4919: doc-dup
 4920: doc-over
 4921: doc-tuck
 4922: doc-swap
 4923: doc-pick
 4924: doc-rot
 4925: doc--rot
 4926: doc-?dup
 4927: doc-roll
 4928: doc-2drop
 4929: doc-2nip
 4930: doc-2dup
 4931: doc-2over
 4932: doc-2tuck
 4933: doc-2swap
 4934: doc-2rot
 4935: 
 4936: 
 4937: @node Floating point stack, Return stack, Data stack, Stack Manipulation
 4938: @subsection Floating point stack
 4939: @cindex floating-point stack manipulation words
 4940: @cindex stack manipulation words, floating-point stack
 4941: 
 4942: Whilst every sane Forth has a separate floating-point stack, it is not
 4943: strictly required; an ANS Forth system could theoretically keep
 4944: floating-point numbers on the data stack. As an additional difficulty,
 4945: you don't know how many cells a floating-point number takes. It is
 4946: reportedly possible to write words in a way that they work also for a
 4947: unified stack model, but we do not recommend trying it. Instead, just
 4948: say that your program has an environmental dependency on a separate
 4949: floating-point stack.
 4950: 
 4951: doc-floating-stack
 4952: 
 4953: doc-fdrop
 4954: doc-fnip
 4955: doc-fdup
 4956: doc-fover
 4957: doc-ftuck
 4958: doc-fswap
 4959: doc-fpick
 4960: doc-frot
 4961: 
 4962: 
 4963: @node Return stack, Locals stack, Floating point stack, Stack Manipulation
 4964: @subsection Return stack
 4965: @cindex return stack manipulation words
 4966: @cindex stack manipulation words, return stack
 4967: 
 4968: @cindex return stack and locals
 4969: @cindex locals and return stack
 4970: A Forth system is allowed to keep local variables on the
 4971: return stack. This is reasonable, as local variables usually eliminate
 4972: the need to use the return stack explicitly. So, if you want to produce
 4973: a standard compliant program and you are using local variables in a
 4974: word, forget about return stack manipulations in that word (refer to the
 4975: standard document for the exact rules).
 4976: 
 4977: doc->r
 4978: doc-r>
 4979: doc-r@
 4980: doc-rdrop
 4981: doc-2>r
 4982: doc-2r>
 4983: doc-2r@
 4984: doc-2rdrop
 4985: 
 4986: 
 4987: @node Locals stack, Stack pointer manipulation, Return stack, Stack Manipulation
 4988: @subsection Locals stack
 4989: 
 4990: Gforth uses an extra locals stack.  It is described, along with the
 4991: reasons for its existence, in @ref{Locals implementation}.
 4992: 
 4993: @node Stack pointer manipulation,  , Locals stack, Stack Manipulation
 4994: @subsection Stack pointer manipulation
 4995: @cindex stack pointer manipulation words
 4996: 
 4997: @c removed s0 r0 l0 -- they are obsolete aliases for sp0 rp0 lp0
 4998: doc-sp0
 4999: doc-sp@
 5000: doc-sp!
 5001: doc-fp0
 5002: doc-fp@
 5003: doc-fp!
 5004: doc-rp0
 5005: doc-rp@
 5006: doc-rp!
 5007: doc-lp0
 5008: doc-lp@
 5009: doc-lp!
 5010: 
 5011: 
 5012: @node Memory, Control Structures, Stack Manipulation, Words
 5013: @section Memory
 5014: @cindex memory words
 5015: 
 5016: @menu
 5017: * Memory model::                
 5018: * Dictionary allocation::       
 5019: * Heap Allocation::             
 5020: * Memory Access::               
 5021: * Address arithmetic::          
 5022: * Memory Blocks::               
 5023: @end menu
 5024: 
 5025: In addition to the standard Forth memory allocation words, there is also
 5026: a @uref{http://www.complang.tuwien.ac.at/forth/garbage-collection.zip,
 5027: garbage collector}.
 5028: 
 5029: @node Memory model, Dictionary allocation, Memory, Memory
 5030: @subsection ANS Forth and Gforth memory models
 5031: 
 5032: @c The ANS Forth description is a mess (e.g., is the heap part of
 5033: @c the dictionary?), so let's not stick to closely with it.
 5034: 
 5035: ANS Forth considers a Forth system as consisting of several address
 5036: spaces, of which only @dfn{data space} is managed and accessible with
 5037: the memory words.  Memory not necessarily in data space includes the
 5038: stacks, the code (called code space) and the headers (called name
 5039: space). In Gforth everything is in data space, but the code for the
 5040: primitives is usually read-only.
 5041: 
 5042: Data space is divided into a number of areas: The (data space portion of
 5043: the) dictionary@footnote{Sometimes, the term @dfn{dictionary} is used to
 5044: refer to the search data structure embodied in word lists and headers,
 5045: because it is used for looking up names, just as you would in a
 5046: conventional dictionary.}, the heap, and a number of system-allocated
 5047: buffers.
 5048: 
 5049: @cindex address arithmetic restrictions, ANS vs. Gforth
 5050: @cindex contiguous regions, ANS vs. Gforth
 5051: In ANS Forth data space is also divided into contiguous regions.  You
 5052: can only use address arithmetic within a contiguous region, not between
 5053: them.  Usually each allocation gives you one contiguous region, but the
 5054: dictionary allocation words have additional rules (@pxref{Dictionary
 5055: allocation}).
 5056: 
 5057: Gforth provides one big address space, and address arithmetic can be
 5058: performed between any addresses. However, in the dictionary headers or
 5059: code are interleaved with data, so almost the only contiguous data space
 5060: regions there are those described by ANS Forth as contiguous; but you
 5061: can be sure that the dictionary is allocated towards increasing
 5062: addresses even between contiguous regions.  The memory order of
 5063: allocations in the heap is platform-dependent (and possibly different
 5064: from one run to the next).
 5065: 
 5066: 
 5067: @node Dictionary allocation, Heap Allocation, Memory model, Memory
 5068: @subsection Dictionary allocation
 5069: @cindex reserving data space
 5070: @cindex data space - reserving some
 5071: 
 5072: Dictionary allocation is a stack-oriented allocation scheme, i.e., if
 5073: you want to deallocate X, you also deallocate everything
 5074: allocated after X.
 5075: 
 5076: @cindex contiguous regions in dictionary allocation
 5077: The allocations using the words below are contiguous and grow the region
 5078: towards increasing addresses.  Other words that allocate dictionary
 5079: memory of any kind (i.e., defining words including @code{:noname}) end
 5080: the contiguous region and start a new one.
 5081: 
 5082: In ANS Forth only @code{create}d words are guaranteed to produce an
 5083: address that is the start of the following contiguous region.  In
 5084: particular, the cell allocated by @code{variable} is not guaranteed to
 5085: be contiguous with following @code{allot}ed memory.
 5086: 
 5087: You can deallocate memory by using @code{allot} with a negative argument
 5088: (with some restrictions, see @code{allot}). For larger deallocations use
 5089: @code{marker}.
 5090: 
 5091: 
 5092: doc-here
 5093: doc-unused
 5094: doc-allot
 5095: doc-c,
 5096: doc-f,
 5097: doc-,
 5098: doc-2,
 5099: 
 5100: Memory accesses have to be aligned (@pxref{Address arithmetic}). So of
 5101: course you should allocate memory in an aligned way, too. I.e., before
 5102: allocating allocating a cell, @code{here} must be cell-aligned, etc.
 5103: The words below align @code{here} if it is not already.  Basically it is
 5104: only already aligned for a type, if the last allocation was a multiple
 5105: of the size of this type and if @code{here} was aligned for this type
 5106: before.
 5107: 
 5108: After freshly @code{create}ing a word, @code{here} is @code{align}ed in
 5109: ANS Forth (@code{maxalign}ed in Gforth).
 5110: 
 5111: doc-align
 5112: doc-falign
 5113: doc-sfalign
 5114: doc-dfalign
 5115: doc-maxalign
 5116: doc-cfalign
 5117: 
 5118: 
 5119: @node Heap Allocation, Memory Access, Dictionary allocation, Memory
 5120: @subsection Heap allocation
 5121: @cindex heap allocation
 5122: @cindex dynamic allocation of memory
 5123: @cindex memory-allocation word set
 5124: 
 5125: @cindex contiguous regions and heap allocation
 5126: Heap allocation supports deallocation of allocated memory in any
 5127: order. Dictionary allocation is not affected by it (i.e., it does not
 5128: end a contiguous region). In Gforth, these words are implemented using
 5129: the standard C library calls malloc(), free() and resize().
 5130: 
 5131: The memory region produced by one invocation of @code{allocate} or
 5132: @code{resize} is internally contiguous.  There is no contiguity between
 5133: such a region and any other region (including others allocated from the
 5134: heap).
 5135: 
 5136: doc-allocate
 5137: doc-free
 5138: doc-resize
 5139: 
 5140: 
 5141: @node Memory Access, Address arithmetic, Heap Allocation, Memory
 5142: @subsection Memory Access
 5143: @cindex memory access words
 5144: 
 5145: doc-@
 5146: doc-!
 5147: doc-+!
 5148: doc-c@
 5149: doc-c!
 5150: doc-2@
 5151: doc-2!
 5152: doc-f@
 5153: doc-f!
 5154: doc-sf@
 5155: doc-sf!
 5156: doc-df@
 5157: doc-df!
 5158: doc-sw@
 5159: doc-uw@
 5160: doc-w!
 5161: doc-sl@
 5162: doc-ul@
 5163: doc-l!
 5164: 
 5165: @node Address arithmetic, Memory Blocks, Memory Access, Memory
 5166: @subsection Address arithmetic
 5167: @cindex address arithmetic words
 5168: 
 5169: Address arithmetic is the foundation on which you can build data
 5170: structures like arrays, records (@pxref{Structures}) and objects
 5171: (@pxref{Object-oriented Forth}).
 5172: 
 5173: @cindex address unit
 5174: @cindex au (address unit)
 5175: ANS Forth does not specify the sizes of the data types. Instead, it
 5176: offers a number of words for computing sizes and doing address
 5177: arithmetic. Address arithmetic is performed in terms of address units
 5178: (aus); on most systems the address unit is one byte. Note that a
 5179: character may have more than one au, so @code{chars} is no noop (on
 5180: platforms where it is a noop, it compiles to nothing).
 5181: 
 5182: The basic address arithmetic words are @code{+} and @code{-}.  E.g., if
 5183: you have the address of a cell, perform @code{1 cells +}, and you will
 5184: have the address of the next cell.
 5185: 
 5186: @cindex contiguous regions and address arithmetic
 5187: In ANS Forth you can perform address arithmetic only within a contiguous
 5188: region, i.e., if you have an address into one region, you can only add
 5189: and subtract such that the result is still within the region; you can
 5190: only subtract or compare addresses from within the same contiguous
 5191: region.  Reasons: several contiguous regions can be arranged in memory
 5192: in any way; on segmented systems addresses may have unusual
 5193: representations, such that address arithmetic only works within a
 5194: region.  Gforth provides a few more guarantees (linear address space,
 5195: dictionary grows upwards), but in general I have found it easy to stay
 5196: within contiguous regions (exception: computing and comparing to the
 5197: address just beyond the end of an array).
 5198: 
 5199: @cindex alignment of addresses for types
 5200: ANS Forth also defines words for aligning addresses for specific
 5201: types. Many computers require that accesses to specific data types
 5202: must only occur at specific addresses; e.g., that cells may only be
 5203: accessed at addresses divisible by 4. Even if a machine allows unaligned
 5204: accesses, it can usually perform aligned accesses faster. 
 5205: 
 5206: For the performance-conscious: alignment operations are usually only
 5207: necessary during the definition of a data structure, not during the
 5208: (more frequent) accesses to it.
 5209: 
 5210: ANS Forth defines no words for character-aligning addresses. This is not
 5211: an oversight, but reflects the fact that addresses that are not
 5212: char-aligned have no use in the standard and therefore will not be
 5213: created.
 5214: 
 5215: @cindex @code{CREATE} and alignment
 5216: ANS Forth guarantees that addresses returned by @code{CREATE}d words
 5217: are cell-aligned; in addition, Gforth guarantees that these addresses
 5218: are aligned for all purposes.
 5219: 
 5220: Note that the ANS Forth word @code{char} has nothing to do with address
 5221: arithmetic.
 5222: 
 5223: 
 5224: doc-chars
 5225: doc-char+
 5226: doc-cells
 5227: doc-cell+
 5228: doc-cell
 5229: doc-aligned
 5230: doc-floats
 5231: doc-float+
 5232: doc-float
 5233: doc-faligned
 5234: doc-sfloats
 5235: doc-sfloat+
 5236: doc-sfaligned
 5237: doc-dfloats
 5238: doc-dfloat+
 5239: doc-dfaligned
 5240: doc-maxaligned
 5241: doc-cfaligned
 5242: doc-address-unit-bits
 5243: doc-/w
 5244: doc-/l
 5245: 
 5246: @node Memory Blocks,  , Address arithmetic, Memory
 5247: @subsection Memory Blocks
 5248: @cindex memory block words
 5249: @cindex character strings - moving and copying
 5250: 
 5251: Memory blocks often represent character strings; For ways of storing
 5252: character strings in memory see @ref{String Formats}.  For other
 5253: string-processing words see @ref{Displaying characters and strings}.
 5254: 
 5255: A few of these words work on address unit blocks.  In that case, you
 5256: usually have to insert @code{CHARS} before the word when working on
 5257: character strings.  Most words work on character blocks, and expect a
 5258: char-aligned address.
 5259: 
 5260: When copying characters between overlapping memory regions, use
 5261: @code{chars move} or choose carefully between @code{cmove} and
 5262: @code{cmove>}.
 5263: 
 5264: doc-move
 5265: doc-erase
 5266: doc-cmove
 5267: doc-cmove>
 5268: doc-fill
 5269: doc-blank
 5270: doc-compare
 5271: doc-str=
 5272: doc-str<
 5273: doc-string-prefix?
 5274: doc-search
 5275: doc--trailing
 5276: doc-/string
 5277: doc-bounds
 5278: doc-pad
 5279: 
 5280: @comment TODO examples
 5281: 
 5282: 
 5283: @node Control Structures, Defining Words, Memory, Words
 5284: @section Control Structures
 5285: @cindex control structures
 5286: 
 5287: Control structures in Forth cannot be used interpretively, only in a
 5288: colon definition@footnote{To be precise, they have no interpretation
 5289: semantics (@pxref{Interpretation and Compilation Semantics}).}. We do
 5290: not like this limitation, but have not seen a satisfying way around it
 5291: yet, although many schemes have been proposed.
 5292: 
 5293: @menu
 5294: * Selection::                   IF ... ELSE ... ENDIF
 5295: * Simple Loops::                BEGIN ...
 5296: * Counted Loops::               DO
 5297: * Arbitrary control structures::  
 5298: * Calls and returns::           
 5299: * Exception Handling::          
 5300: @end menu
 5301: 
 5302: @node Selection, Simple Loops, Control Structures, Control Structures
 5303: @subsection Selection
 5304: @cindex selection control structures
 5305: @cindex control structures for selection
 5306: 
 5307: @cindex @code{IF} control structure
 5308: @example
 5309: @i{flag}
 5310: IF
 5311:   @i{code}
 5312: ENDIF
 5313: @end example
 5314: @noindent
 5315: 
 5316: If @i{flag} is non-zero (as far as @code{IF} etc. are concerned, a cell
 5317: with any bit set represents truth) @i{code} is executed.
 5318: 
 5319: @example
 5320: @i{flag}
 5321: IF
 5322:   @i{code1}
 5323: ELSE
 5324:   @i{code2}
 5325: ENDIF
 5326: @end example
 5327: 
 5328: If @var{flag} is true, @i{code1} is executed, otherwise @i{code2} is
 5329: executed.
 5330: 
 5331: You can use @code{THEN} instead of @code{ENDIF}. Indeed, @code{THEN} is
 5332: standard, and @code{ENDIF} is not, although it is quite popular. We
 5333: recommend using @code{ENDIF}, because it is less confusing for people
 5334: who also know other languages (and is not prone to reinforcing negative
 5335: prejudices against Forth in these people). Adding @code{ENDIF} to a
 5336: system that only supplies @code{THEN} is simple:
 5337: @example
 5338: : ENDIF   POSTPONE then ; immediate
 5339: @end example
 5340: 
 5341: [According to @cite{Webster's New Encyclopedic Dictionary}, @dfn{then
 5342: (adv.)}  has the following meanings:
 5343: @quotation
 5344: ... 2b: following next after in order ... 3d: as a necessary consequence
 5345: (if you were there, then you saw them).
 5346: @end quotation
 5347: Forth's @code{THEN} has the meaning 2b, whereas @code{THEN} in Pascal
 5348: and many other programming languages has the meaning 3d.]
 5349: 
 5350: Gforth also provides the words @code{?DUP-IF} and @code{?DUP-0=-IF}, so
 5351: you can avoid using @code{?dup}. Using these alternatives is also more
 5352: efficient than using @code{?dup}. Definitions in ANS Forth
 5353: for @code{ENDIF}, @code{?DUP-IF} and @code{?DUP-0=-IF} are provided in
 5354: @file{compat/control.fs}.
 5355: 
 5356: @cindex @code{CASE} control structure
 5357: @example
 5358: @i{x}
 5359: CASE
 5360:   @i{x1} OF @i{code1} ENDOF
 5361:   @i{x2} OF @i{code2} ENDOF
 5362:   @dots{}
 5363:   ( x ) @i{default-code} ( x )
 5364: ENDCASE ( )
 5365: @end example
 5366: 
 5367: Executes the first @i{codei}, where the @i{xi} is equal to @i{x}.  If no
 5368: @i{xi} matches, the optional @i{default-code} is executed. The optional
 5369: default case can be added by simply writing the code after the last
 5370: @code{ENDOF}. It may use @i{x}, which is on top of the stack, but must
 5371: not consume it.  The value @i{x} is consumed by this construction
 5372: (either by an @code{OF} that matches, or by the @code{ENDCASE}, if no OF
 5373: matches).  Example:
 5374: 
 5375: @example
 5376: : num-name ( n -- c-addr u )
 5377:  case
 5378:    0 of s" zero " endof
 5379:    1 of s" one "  endof
 5380:    2 of s" two "  endof
 5381:    \ default case:
 5382:    s" other number" 
 5383:    rot \ get n on top so ENDCASE can drop it
 5384:  endcase ;
 5385: @end example
 5386: 
 5387: You can also use (the non-standard) @code{?of} to use @code{case} as a
 5388: general selection structure for more than two alternatives.
 5389: @code{?Of} takes a flag.  Example:
 5390: 
 5391: @example
 5392: : sgn ( n1 -- n2 )
 5393:     \ sign function
 5394:     case
 5395: 	dup 0< ?of drop -1 endof
 5396: 	dup 0> ?of drop 1 endof
 5397: 	dup \ n1=0 -> n2=0; dup an item, to be consumed by ENDCASE
 5398:     endcase ;
 5399: @end example
 5400: 
 5401: @progstyle
 5402: To keep the code understandable, you should ensure that you change the
 5403: stack in the same way (wrt. number and types of stack items consumed
 5404: and pushed) on all paths through a selection structure.
 5405: 
 5406: @node Simple Loops, Counted Loops, Selection, Control Structures
 5407: @subsection Simple Loops
 5408: @cindex simple loops
 5409: @cindex loops without count 
 5410: 
 5411: @cindex @code{WHILE} loop
 5412: @example
 5413: BEGIN
 5414:   @i{code1}
 5415:   @i{flag}
 5416: WHILE
 5417:   @i{code2}
 5418: REPEAT
 5419: @end example
 5420: 
 5421: @i{code1} is executed and @i{flag} is computed. If it is true,
 5422: @i{code2} is executed and the loop is restarted; If @i{flag} is
 5423: false, execution continues after the @code{REPEAT}.
 5424: 
 5425: @cindex @code{UNTIL} loop
 5426: @example
 5427: BEGIN
 5428:   @i{code}
 5429:   @i{flag}
 5430: UNTIL
 5431: @end example
 5432: 
 5433: @i{code} is executed. The loop is restarted if @code{flag} is false.
 5434: 
 5435: @progstyle
 5436: To keep the code understandable, a complete iteration of the loop should
 5437: not change the number and types of the items on the stacks.
 5438: 
 5439: @cindex endless loop
 5440: @cindex loops, endless
 5441: @example
 5442: BEGIN
 5443:   @i{code}
 5444: AGAIN
 5445: @end example
 5446: 
 5447: This is an endless loop.
 5448: 
 5449: @node Counted Loops, Arbitrary control structures, Simple Loops, Control Structures
 5450: @subsection Counted Loops
 5451: @cindex counted loops
 5452: @cindex loops, counted
 5453: @cindex @code{DO} loops
 5454: 
 5455: The basic counted loop is:
 5456: @example
 5457: @i{limit} @i{start}
 5458: ?DO
 5459:   @i{body}
 5460: LOOP
 5461: @end example
 5462: 
 5463: This performs one iteration for every integer, starting from @i{start}
 5464: and up to, but excluding @i{limit}. The counter, or @i{index}, can be
 5465: accessed with @code{i}. For example, the loop:
 5466: @example
 5467: 10 0 ?DO
 5468:   i .
 5469: LOOP
 5470: @end example
 5471: @noindent
 5472: prints @code{0 1 2 3 4 5 6 7 8 9}
 5473: 
 5474: The index of the innermost loop can be accessed with @code{i}, the index
 5475: of the next loop with @code{j}, and the index of the third loop with
 5476: @code{k}.
 5477: 
 5478: 
 5479: doc-i
 5480: doc-j
 5481: doc-k
 5482: 
 5483: 
 5484: The loop control data are kept on the return stack, so there are some
 5485: restrictions on mixing return stack accesses and counted loop words. In
 5486: particuler, if you put values on the return stack outside the loop, you
 5487: cannot read them inside the loop@footnote{well, not in a way that is
 5488: portable.}. If you put values on the return stack within a loop, you
 5489: have to remove them before the end of the loop and before accessing the
 5490: index of the loop.
 5491: 
 5492: There are several variations on the counted loop:
 5493: 
 5494: @itemize @bullet
 5495: @item
 5496: @code{LEAVE} leaves the innermost counted loop immediately; execution
 5497: continues after the associated @code{LOOP} or @code{NEXT}. For example:
 5498: 
 5499: @example
 5500: 10 0 ?DO  i DUP . 3 = IF LEAVE THEN LOOP
 5501: @end example
 5502: prints @code{0 1 2 3}
 5503: 
 5504: 
 5505: @item
 5506: @code{UNLOOP} prepares for an abnormal loop exit, e.g., via
 5507: @code{EXIT}. @code{UNLOOP} removes the loop control parameters from the
 5508: return stack so @code{EXIT} can get to its return address. For example:
 5509: 
 5510: @example
 5511: : demo 10 0 ?DO i DUP . 3 = IF UNLOOP EXIT THEN LOOP ." Done" ;
 5512: @end example
 5513: prints @code{0 1 2 3}
 5514: 
 5515: 
 5516: @item
 5517: If @i{start} is greater than @i{limit}, a @code{?DO} loop is entered
 5518: (and @code{LOOP} iterates until they become equal by wrap-around
 5519: arithmetic). This behaviour is usually not what you want. Therefore,
 5520: Gforth offers @code{+DO} and @code{U+DO} (as replacements for
 5521: @code{?DO}), which do not enter the loop if @i{start} is greater than
 5522: @i{limit}; @code{+DO} is for signed loop parameters, @code{U+DO} for
 5523: unsigned loop parameters.
 5524: 
 5525: @item
 5526: @code{?DO} can be replaced by @code{DO}. @code{DO} always enters
 5527: the loop, independent of the loop parameters. Do not use @code{DO}, even
 5528: if you know that the loop is entered in any case. Such knowledge tends
 5529: to become invalid during maintenance of a program, and then the
 5530: @code{DO} will make trouble.
 5531: 
 5532: @item
 5533: @code{LOOP} can be replaced with @code{@i{n} +LOOP}; this updates the
 5534: index by @i{n} instead of by 1. The loop is terminated when the border
 5535: between @i{limit-1} and @i{limit} is crossed. E.g.:
 5536: 
 5537: @example
 5538: 4 0 +DO  i .  2 +LOOP
 5539: @end example
 5540: @noindent
 5541: prints @code{0 2}
 5542: 
 5543: @example
 5544: 4 1 +DO  i .  2 +LOOP
 5545: @end example
 5546: @noindent
 5547: prints @code{1 3}
 5548: 
 5549: @item
 5550: @cindex negative increment for counted loops
 5551: @cindex counted loops with negative increment
 5552: The behaviour of @code{@i{n} +LOOP} is peculiar when @i{n} is negative:
 5553: 
 5554: @example
 5555: -1 0 ?DO  i .  -1 +LOOP
 5556: @end example
 5557: @noindent
 5558: prints @code{0 -1}
 5559: 
 5560: @example
 5561: 0 0 ?DO  i .  -1 +LOOP
 5562: @end example
 5563: prints nothing.
 5564: 
 5565: Therefore we recommend avoiding @code{@i{n} +LOOP} with negative
 5566: @i{n}. One alternative is @code{@i{u} -LOOP}, which reduces the
 5567: index by @i{u} each iteration. The loop is terminated when the border
 5568: between @i{limit+1} and @i{limit} is crossed. Gforth also provides
 5569: @code{-DO} and @code{U-DO} for down-counting loops. E.g.:
 5570: 
 5571: @example
 5572: -2 0 -DO  i .  1 -LOOP
 5573: @end example
 5574: @noindent
 5575: prints @code{0 -1}
 5576: 
 5577: @example
 5578: -1 0 -DO  i .  1 -LOOP
 5579: @end example
 5580: @noindent
 5581: prints @code{0}
 5582: 
 5583: @example
 5584: 0 0 -DO  i .  1 -LOOP
 5585: @end example
 5586: @noindent
 5587: prints nothing.
 5588: 
 5589: @end itemize
 5590: 
 5591: Unfortunately, @code{+DO}, @code{U+DO}, @code{-DO}, @code{U-DO} and
 5592: @code{-LOOP} are not defined in ANS Forth. However, an implementation
 5593: for these words that uses only standard words is provided in
 5594: @file{compat/loops.fs}.
 5595: 
 5596: 
 5597: @cindex @code{FOR} loops
 5598: Another counted loop is:
 5599: @example
 5600: @i{n}
 5601: FOR
 5602:   @i{body}
 5603: NEXT
 5604: @end example
 5605: This is the preferred loop of native code compiler writers who are too
 5606: lazy to optimize @code{?DO} loops properly. This loop structure is not
 5607: defined in ANS Forth. In Gforth, this loop iterates @i{n+1} times;
 5608: @code{i} produces values starting with @i{n} and ending with 0. Other
 5609: Forth systems may behave differently, even if they support @code{FOR}
 5610: loops. To avoid problems, don't use @code{FOR} loops.
 5611: 
 5612: @node Arbitrary control structures, Calls and returns, Counted Loops, Control Structures
 5613: @subsection Arbitrary control structures
 5614: @cindex control structures, user-defined
 5615: 
 5616: @cindex control-flow stack
 5617: ANS Forth permits and supports using control structures in a non-nested
 5618: way. Information about incomplete control structures is stored on the
 5619: control-flow stack. This stack may be implemented on the Forth data
 5620: stack, and this is what we have done in Gforth.
 5621: 
 5622: @cindex @code{orig}, control-flow stack item
 5623: @cindex @code{dest}, control-flow stack item
 5624: An @i{orig} entry represents an unresolved forward branch, a @i{dest}
 5625: entry represents a backward branch target. A few words are the basis for
 5626: building any control structure possible (except control structures that
 5627: need storage, like calls, coroutines, and backtracking).
 5628: 
 5629: 
 5630: doc-if
 5631: doc-ahead
 5632: doc-then
 5633: doc-begin
 5634: doc-until
 5635: doc-again
 5636: doc-cs-pick
 5637: doc-cs-roll
 5638: 
 5639: 
 5640: The Standard words @code{CS-PICK} and @code{CS-ROLL} allow you to
 5641: manipulate the control-flow stack in a portable way. Without them, you
 5642: would need to know how many stack items are occupied by a control-flow
 5643: entry (many systems use one cell. In Gforth they currently take three,
 5644: but this may change in the future).
 5645: 
 5646: Some standard control structure words are built from these words:
 5647: 
 5648: 
 5649: doc-else
 5650: doc-while
 5651: doc-repeat
 5652: 
 5653: 
 5654: @noindent
 5655: Gforth adds some more control-structure words:
 5656: 
 5657: 
 5658: doc-endif
 5659: doc-?dup-if
 5660: doc-?dup-0=-if
 5661: 
 5662: 
 5663: @noindent
 5664: Counted loop words constitute a separate group of words:
 5665: 
 5666: 
 5667: doc-?do
 5668: doc-+do
 5669: doc-u+do
 5670: doc--do
 5671: doc-u-do
 5672: doc-do
 5673: doc-for
 5674: doc-loop
 5675: doc-+loop
 5676: doc--loop
 5677: doc-next
 5678: doc-leave
 5679: doc-?leave
 5680: doc-unloop
 5681: doc-done
 5682: 
 5683: 
 5684: The standard does not allow using @code{CS-PICK} and @code{CS-ROLL} on
 5685: @i{do-sys}. Gforth allows it, but it's your job to ensure that for
 5686: every @code{?DO} etc. there is exactly one @code{UNLOOP} on any path
 5687: through the definition (@code{LOOP} etc. compile an @code{UNLOOP} on the
 5688: fall-through path). Also, you have to ensure that all @code{LEAVE}s are
 5689: resolved (by using one of the loop-ending words or @code{DONE}).
 5690: 
 5691: @noindent
 5692: Another group of control structure words are:
 5693: 
 5694: 
 5695: doc-case
 5696: doc-endcase
 5697: doc-of
 5698: doc-?ofx
 5699: doc-endof
 5700: 
 5701: 
 5702: @i{case-sys} and @i{of-sys} cannot be processed using @code{CS-PICK} and
 5703: @code{CS-ROLL}.
 5704: 
 5705: @subsubsection Programming Style
 5706: @cindex control structures programming style
 5707: @cindex programming style, arbitrary control structures
 5708: 
 5709: In order to ensure readability we recommend that you do not create
 5710: arbitrary control structures directly, but define new control structure
 5711: words for the control structure you want and use these words in your
 5712: program. For example, instead of writing:
 5713: 
 5714: @example
 5715: BEGIN
 5716:   ...
 5717: IF [ 1 CS-ROLL ]
 5718:   ...
 5719: AGAIN THEN
 5720: @end example
 5721: 
 5722: @noindent
 5723: we recommend defining control structure words, e.g.,
 5724: 
 5725: @example
 5726: : WHILE ( DEST -- ORIG DEST )
 5727:  POSTPONE IF
 5728:  1 CS-ROLL ; immediate
 5729: 
 5730: : REPEAT ( orig dest -- )
 5731:  POSTPONE AGAIN
 5732:  POSTPONE THEN ; immediate
 5733: @end example
 5734: 
 5735: @noindent
 5736: and then using these to create the control structure:
 5737: 
 5738: @example
 5739: BEGIN
 5740:   ...
 5741: WHILE
 5742:   ...
 5743: REPEAT
 5744: @end example
 5745: 
 5746: That's much easier to read, isn't it? Of course, @code{REPEAT} and
 5747: @code{WHILE} are predefined, so in this example it would not be
 5748: necessary to define them.
 5749: 
 5750: @node Calls and returns, Exception Handling, Arbitrary control structures, Control Structures
 5751: @subsection Calls and returns
 5752: @cindex calling a definition
 5753: @cindex returning from a definition
 5754: 
 5755: @cindex recursive definitions
 5756: A definition can be called simply be writing the name of the definition
 5757: to be called. Normally a definition is invisible during its own
 5758: definition. If you want to write a directly recursive definition, you
 5759: can use @code{recursive} to make the current definition visible, or
 5760: @code{recurse} to call the current definition directly.
 5761: 
 5762: 
 5763: doc-recursive
 5764: doc-recurse
 5765: 
 5766: 
 5767: @comment TODO add example of the two recursion methods
 5768: @quotation
 5769: @progstyle
 5770: I prefer using @code{recursive} to @code{recurse}, because calling the
 5771: definition by name is more descriptive (if the name is well-chosen) than
 5772: the somewhat cryptic @code{recurse}.  E.g., in a quicksort
 5773: implementation, it is much better to read (and think) ``now sort the
 5774: partitions'' than to read ``now do a recursive call''.
 5775: @end quotation
 5776: 
 5777: For mutual recursion, use @code{Defer}red words, like this:
 5778: 
 5779: @example
 5780: Defer foo
 5781: 
 5782: : bar ( ... -- ... )
 5783:  ... foo ... ;
 5784: 
 5785: :noname ( ... -- ... )
 5786:  ... bar ... ;
 5787: IS foo
 5788: @end example
 5789: 
 5790: Deferred words are discussed in more detail in @ref{Deferred Words}.
 5791: 
 5792: The current definition returns control to the calling definition when
 5793: the end of the definition is reached or @code{EXIT} is encountered.
 5794: 
 5795: doc-exit
 5796: doc-;s
 5797: 
 5798: 
 5799: @node Exception Handling,  , Calls and returns, Control Structures
 5800: @subsection Exception Handling
 5801: @cindex exceptions
 5802: 
 5803: @c quit is a very bad idea for error handling, 
 5804: @c because it does not translate into a THROW
 5805: @c it also does not belong into this chapter
 5806: 
 5807: If a word detects an error condition that it cannot handle, it can
 5808: @code{throw} an exception.  In the simplest case, this will terminate
 5809: your program, and report an appropriate error.
 5810: 
 5811: doc-throw
 5812: 
 5813: @code{Throw} consumes a cell-sized error number on the stack. There are
 5814: some predefined error numbers in ANS Forth (see @file{errors.fs}).  In
 5815: Gforth (and most other systems) you can use the iors produced by various
 5816: words as error numbers (e.g., a typical use of @code{allocate} is
 5817: @code{allocate throw}).  Gforth also provides the word @code{exception}
 5818: to define your own error numbers (with decent error reporting); an ANS
 5819: Forth version of this word (but without the error messages) is available
 5820: in @code{compat/except.fs}.  And finally, you can use your own error
 5821: numbers (anything outside the range -4095..0), but won't get nice error
 5822: messages, only numbers.  For example, try:
 5823: 
 5824: @example
 5825: -10 throw                    \ ANS defined
 5826: -267 throw                   \ system defined
 5827: s" my error" exception throw \ user defined
 5828: 7 throw                      \ arbitrary number
 5829: @end example
 5830: 
 5831: doc---exception-exception
 5832: 
 5833: A common idiom to @code{THROW} a specific error if a flag is true is
 5834: this:
 5835: 
 5836: @example
 5837: @code{( flag ) 0<> @i{errno} and throw}
 5838: @end example
 5839: 
 5840: Your program can provide exception handlers to catch exceptions.  An
 5841: exception handler can be used to correct the problem, or to clean up
 5842: some data structures and just throw the exception to the next exception
 5843: handler.  Note that @code{throw} jumps to the dynamically innermost
 5844: exception handler.  The system's exception handler is outermost, and just
 5845: prints an error and restarts command-line interpretation (or, in batch
 5846: mode (i.e., while processing the shell command line), leaves Gforth).
 5847: 
 5848: The ANS Forth way to catch exceptions is @code{catch}:
 5849: 
 5850: doc-catch
 5851: doc-nothrow
 5852: 
 5853: The most common use of exception handlers is to clean up the state when
 5854: an error happens.  E.g.,
 5855: 
 5856: @example
 5857: base @ >r hex \ actually the hex should be inside foo, or we h
 5858: ['] foo catch ( nerror|0 )
 5859: r> base !
 5860: ( nerror|0 ) throw \ pass it on
 5861: @end example
 5862: 
 5863: A use of @code{catch} for handling the error @code{myerror} might look
 5864: like this:
 5865: 
 5866: @example
 5867: ['] foo catch
 5868: CASE
 5869:   myerror OF ... ( do something about it ) nothrow ENDOF
 5870:   dup throw \ default: pass other errors on, do nothing on non-errors
 5871: ENDCASE
 5872: @end example
 5873: 
 5874: Having to wrap the code into a separate word is often cumbersome,
 5875: therefore Gforth provides an alternative syntax:
 5876: 
 5877: @example
 5878: TRY
 5879:   @i{code1}
 5880:   IFERROR
 5881:     @i{code2}
 5882:   THEN
 5883:   @i{code3}
 5884: ENDTRY
 5885: @end example
 5886: 
 5887: This performs @i{code1}.  If @i{code1} completes normally, execution
 5888: continues with @i{code3}.  If there is an exception in @i{code1} or
 5889: before @code{endtry}, the stacks are reset to the depth during
 5890: @code{try}, the throw value is pushed on the data stack, and execution
 5891: constinues at @i{code2}, and finally falls through to @i{code3}.
 5892: 
 5893: doc-try
 5894: doc-endtry
 5895: doc-iferror
 5896: 
 5897: If you don't need @i{code2}, you can write @code{restore} instead of
 5898: @code{iferror then}:
 5899: 
 5900: @example
 5901: TRY
 5902:   @i{code1}
 5903: RESTORE
 5904:   @i{code3}
 5905: ENDTRY
 5906: @end example
 5907: 
 5908: @cindex unwind-protect
 5909: The cleanup example from above in this syntax:
 5910: 
 5911: @example
 5912: base @@ @{ oldbase @}
 5913: TRY
 5914:   hex foo \ now the hex is placed correctly
 5915:   0       \ value for throw
 5916: RESTORE
 5917:   oldbase base !
 5918: ENDTRY
 5919: throw
 5920: @end example
 5921: 
 5922: An additional advantage of this variant is that an exception between
 5923: @code{restore} and @code{endtry} (e.g., from the user pressing
 5924: @kbd{Ctrl-C}) restarts the execution of the code after @code{restore},
 5925: so the base will be restored under all circumstances.
 5926: 
 5927: However, you have to ensure that this code does not cause an exception
 5928: itself, otherwise the @code{iferror}/@code{restore} code will loop.
 5929: Moreover, you should also make sure that the stack contents needed by
 5930: the @code{iferror}/@code{restore} code exist everywhere between
 5931: @code{try} and @code{endtry}; in our example this is achived by
 5932: putting the data in a local before the @code{try} (you cannot use the
 5933: return stack because the exception frame (@i{sys1}) is in the way
 5934: there).
 5935: 
 5936: This kind of usage corresponds to Lisp's @code{unwind-protect}.
 5937: 
 5938: @cindex @code{recover} (old Gforth versions)
 5939: If you do not want this exception-restarting behaviour, you achieve
 5940: this as follows:
 5941: 
 5942: @example
 5943: TRY
 5944:   @i{code1}
 5945: ENDTRY-IFERROR
 5946:   @i{code2}
 5947: THEN
 5948: @end example
 5949: 
 5950: If there is an exception in @i{code1}, then @i{code2} is executed,
 5951: otherwise execution continues behind the @code{then} (or in a possible
 5952: @code{else} branch).  This corresponds to the construct
 5953: 
 5954: @example
 5955: TRY
 5956:   @i{code1}
 5957: RECOVER
 5958:   @i{code2}
 5959: ENDTRY
 5960: @end example
 5961: 
 5962: in Gforth before version 0.7.  So you can directly replace
 5963: @code{recover}-using code; however, we recommend that you check if it
 5964: would not be better to use one of the other @code{try} variants while
 5965: you are at it.
 5966: 
 5967: To ease the transition, Gforth provides two compatibility files:
 5968: @file{endtry-iferror.fs} provides the @code{try ... endtry-iferror
 5969: ... then} syntax (but not @code{iferror} or @code{restore}) for old
 5970: systems; @file{recover-endtry.fs} provides the @code{try ... recover
 5971: ... endtry} syntax on new systems, so you can use that file as a
 5972: stopgap to run old programs.  Both files work on any system (they just
 5973: do nothing if the system already has the syntax it implements), so you
 5974: can unconditionally @code{require} one of these files, even if you use
 5975: a mix old and new systems.
 5976: 
 5977: doc-restore
 5978: doc-endtry-iferror
 5979: 
 5980: Here's the error handling example:
 5981: 
 5982: @example
 5983: TRY
 5984:   foo
 5985: ENDTRY-IFERROR
 5986:   CASE
 5987:     myerror OF ... ( do something about it ) nothrow ENDOF
 5988:     throw \ pass other errors on
 5989:   ENDCASE
 5990: THEN
 5991: @end example
 5992: 
 5993: @progstyle
 5994: As usual, you should ensure that the stack depth is statically known at
 5995: the end: either after the @code{throw} for passing on errors, or after
 5996: the @code{ENDTRY} (or, if you use @code{catch}, after the end of the
 5997: selection construct for handling the error).
 5998: 
 5999: There are two alternatives to @code{throw}: @code{Abort"} is conditional
 6000: and you can provide an error message.  @code{Abort} just produces an
 6001: ``Aborted'' error.
 6002: 
 6003: The problem with these words is that exception handlers cannot
 6004: differentiate between different @code{abort"}s; they just look like
 6005: @code{-2 throw} to them (the error message cannot be accessed by
 6006: standard programs).  Similar @code{abort} looks like @code{-1 throw} to
 6007: exception handlers.
 6008: 
 6009: doc-abort"
 6010: doc-abort
 6011: 
 6012: 
 6013: 
 6014: @c -------------------------------------------------------------
 6015: @node Defining Words, Interpretation and Compilation Semantics, Control Structures, Words
 6016: @section Defining Words
 6017: @cindex defining words
 6018: 
 6019: Defining words are used to extend Forth by creating new entries in the dictionary.
 6020: 
 6021: @menu
 6022: * CREATE::                      
 6023: * Variables::                   Variables and user variables
 6024: * Constants::                   
 6025: * Values::                      Initialised variables
 6026: * Colon Definitions::           
 6027: * Anonymous Definitions::       Definitions without names
 6028: * Supplying names::             Passing definition names as strings
 6029: * User-defined Defining Words::  
 6030: * Deferred Words::              Allow forward references
 6031: * Aliases::                     
 6032: @end menu
 6033: 
 6034: @node CREATE, Variables, Defining Words, Defining Words
 6035: @subsection @code{CREATE}
 6036: @cindex simple defining words
 6037: @cindex defining words, simple
 6038: 
 6039: Defining words are used to create new entries in the dictionary. The
 6040: simplest defining word is @code{CREATE}. @code{CREATE} is used like
 6041: this:
 6042: 
 6043: @example
 6044: CREATE new-word1
 6045: @end example
 6046: 
 6047: @code{CREATE} is a parsing word, i.e., it takes an argument from the
 6048: input stream (@code{new-word1} in our example).  It generates a
 6049: dictionary entry for @code{new-word1}. When @code{new-word1} is
 6050: executed, all that it does is leave an address on the stack. The address
 6051: represents the value of the data space pointer (@code{HERE}) at the time
 6052: that @code{new-word1} was defined. Therefore, @code{CREATE} is a way of
 6053: associating a name with the address of a region of memory.
 6054: 
 6055: doc-create
 6056: 
 6057: Note that in ANS Forth guarantees only for @code{create} that its body
 6058: is in dictionary data space (i.e., where @code{here}, @code{allot}
 6059: etc. work, @pxref{Dictionary allocation}).  Also, in ANS Forth only
 6060: @code{create}d words can be modified with @code{does>}
 6061: (@pxref{User-defined Defining Words}).  And in ANS Forth @code{>body}
 6062: can only be applied to @code{create}d words.
 6063: 
 6064: By extending this example to reserve some memory in data space, we end
 6065: up with something like a @i{variable}. Here are two different ways to do
 6066: it:
 6067: 
 6068: @example
 6069: CREATE new-word2 1 cells allot  \ reserve 1 cell - initial value undefined
 6070: CREATE new-word3 4 ,            \ reserve 1 cell and initialise it (to 4)
 6071: @end example
 6072: 
 6073: The variable can be examined and modified using @code{@@} (``fetch'') and
 6074: @code{!} (``store'') like this:
 6075: 
 6076: @example
 6077: new-word2 @@ .      \ get address, fetch from it and display
 6078: 1234 new-word2 !   \ new value, get address, store to it
 6079: @end example
 6080: 
 6081: @cindex arrays
 6082: A similar mechanism can be used to create arrays. For example, an
 6083: 80-character text input buffer:
 6084: 
 6085: @example
 6086: CREATE text-buf 80 chars allot
 6087: 
 6088: text-buf 0 chars + c@@ \ the 1st character (offset 0)
 6089: text-buf 3 chars + c@@ \ the 4th character (offset 3)
 6090: @end example
 6091: 
 6092: You can build arbitrarily complex data structures by allocating
 6093: appropriate areas of memory. For further discussions of this, and to
 6094: learn about some Gforth tools that make it easier,
 6095: @xref{Structures}.
 6096: 
 6097: 
 6098: @node Variables, Constants, CREATE, Defining Words
 6099: @subsection Variables
 6100: @cindex variables
 6101: 
 6102: The previous section showed how a sequence of commands could be used to
 6103: generate a variable.  As a final refinement, the whole code sequence can
 6104: be wrapped up in a defining word (pre-empting the subject of the next
 6105: section), making it easier to create new variables:
 6106: 
 6107: @example
 6108: : myvariableX ( "name" -- a-addr ) CREATE 1 cells allot ;
 6109: : myvariable0 ( "name" -- a-addr ) CREATE 0 , ;
 6110: 
 6111: myvariableX foo \ variable foo starts off with an unknown value
 6112: myvariable0 joe \ whilst joe is initialised to 0
 6113: 
 6114: 45 3 * foo !   \ set foo to 135
 6115: 1234 joe !     \ set joe to 1234
 6116: 3 joe +!       \ increment joe by 3.. to 1237
 6117: @end example
 6118: 
 6119: Not surprisingly, there is no need to define @code{myvariable}, since
 6120: Forth already has a definition @code{Variable}. ANS Forth does not
 6121: guarantee that a @code{Variable} is initialised when it is created
 6122: (i.e., it may behave like @code{myvariableX}). In contrast, Gforth's
 6123: @code{Variable} initialises the variable to 0 (i.e., it behaves exactly
 6124: like @code{myvariable0}). Forth also provides @code{2Variable} and
 6125: @code{fvariable} for double and floating-point variables, respectively
 6126: -- they are initialised to 0. and 0e in Gforth. If you use a @code{Variable} to
 6127: store a boolean, you can use @code{on} and @code{off} to toggle its
 6128: state.
 6129: 
 6130: doc-variable
 6131: doc-2variable
 6132: doc-fvariable
 6133: 
 6134: @cindex user variables
 6135: @cindex user space
 6136: The defining word @code{User} behaves in the same way as @code{Variable}.
 6137: The difference is that it reserves space in @i{user (data) space} rather
 6138: than normal data space. In a Forth system that has a multi-tasker, each
 6139: task has its own set of user variables.
 6140: 
 6141: doc-user
 6142: @c doc-udp
 6143: @c doc-uallot
 6144: 
 6145: @comment TODO is that stuff about user variables strictly correct? Is it
 6146: @comment just terminal tasks that have user variables?
 6147: @comment should document tasker.fs (with some examples) elsewhere
 6148: @comment in this manual, then expand on user space and user variables.
 6149: 
 6150: @node Constants, Values, Variables, Defining Words
 6151: @subsection Constants
 6152: @cindex constants
 6153: 
 6154: @code{Constant} allows you to declare a fixed value and refer to it by
 6155: name. For example:
 6156: 
 6157: @example
 6158: 12 Constant INCHES-PER-FOOT
 6159: 3E+08 fconstant SPEED-O-LIGHT
 6160: @end example
 6161: 
 6162: A @code{Variable} can be both read and written, so its run-time
 6163: behaviour is to supply an address through which its current value can be
 6164: manipulated. In contrast, the value of a @code{Constant} cannot be
 6165: changed once it has been declared@footnote{Well, often it can be -- but
 6166: not in a Standard, portable way. It's safer to use a @code{Value} (read
 6167: on).} so it's not necessary to supply the address -- it is more
 6168: efficient to return the value of the constant directly. That's exactly
 6169: what happens; the run-time effect of a constant is to put its value on
 6170: the top of the stack (You can find one
 6171: way of implementing @code{Constant} in @ref{User-defined Defining Words}).
 6172: 
 6173: Forth also provides @code{2Constant} and @code{fconstant} for defining
 6174: double and floating-point constants, respectively.
 6175: 
 6176: doc-constant
 6177: doc-2constant
 6178: doc-fconstant
 6179: 
 6180: @c that's too deep, and it's not necessarily true for all ANS Forths. - anton
 6181: @c nac-> How could that not be true in an ANS Forth? You can't define a
 6182: @c constant, use it and then delete the definition of the constant..
 6183: 
 6184: @c anton->An ANS Forth system can compile a constant to a literal; On
 6185: @c decompilation you would see only the number, just as if it had been used
 6186: @c in the first place.  The word will stay, of course, but it will only be
 6187: @c used by the text interpreter (no run-time duties, except when it is 
 6188: @c POSTPONEd or somesuch).
 6189: 
 6190: @c nac:
 6191: @c I agree that it's rather deep, but IMO it is an important difference
 6192: @c relative to other programming languages.. often it's annoying: it
 6193: @c certainly changes my programming style relative to C.
 6194: 
 6195: @c anton: In what way?
 6196: 
 6197: Constants in Forth behave differently from their equivalents in other
 6198: programming languages. In other languages, a constant (such as an EQU in
 6199: assembler or a #define in C) only exists at compile-time; in the
 6200: executable program the constant has been translated into an absolute
 6201: number and, unless you are using a symbolic debugger, it's impossible to
 6202: know what abstract thing that number represents. In Forth a constant has
 6203: an entry in the header space and remains there after the code that uses
 6204: it has been defined. In fact, it must remain in the dictionary since it
 6205: has run-time duties to perform. For example:
 6206: 
 6207: @example
 6208: 12 Constant INCHES-PER-FOOT
 6209: : FEET-TO-INCHES ( n1 -- n2 ) INCHES-PER-FOOT * ;
 6210: @end example
 6211: 
 6212: @cindex in-lining of constants
 6213: When @code{FEET-TO-INCHES} is executed, it will in turn execute the xt
 6214: associated with the constant @code{INCHES-PER-FOOT}. If you use
 6215: @code{see} to decompile the definition of @code{FEET-TO-INCHES}, you can
 6216: see that it makes a call to @code{INCHES-PER-FOOT}. Some Forth compilers
 6217: attempt to optimise constants by in-lining them where they are used. You
 6218: can force Gforth to in-line a constant like this:
 6219: 
 6220: @example
 6221: : FEET-TO-INCHES ( n1 -- n2 ) [ INCHES-PER-FOOT ] LITERAL * ;
 6222: @end example
 6223: 
 6224: If you use @code{see} to decompile @i{this} version of
 6225: @code{FEET-TO-INCHES}, you can see that @code{INCHES-PER-FOOT} is no
 6226: longer present. To understand how this works, read
 6227: @ref{Interpret/Compile states}, and @ref{Literals}.
 6228: 
 6229: In-lining constants in this way might improve execution time
 6230: fractionally, and can ensure that a constant is now only referenced at
 6231: compile-time. However, the definition of the constant still remains in
 6232: the dictionary. Some Forth compilers provide a mechanism for controlling
 6233: a second dictionary for holding transient words such that this second
 6234: dictionary can be deleted later in order to recover memory
 6235: space. However, there is no standard way of doing this.
 6236: 
 6237: 
 6238: @node Values, Colon Definitions, Constants, Defining Words
 6239: @subsection Values
 6240: @cindex values
 6241: 
 6242: A @code{Value} behaves like a @code{Constant}, but it can be changed.
 6243: @code{TO} is a parsing word that changes a @code{Values}.  In Gforth
 6244: (not in ANS Forth) you can access (and change) a @code{value} also with
 6245: @code{>body}.
 6246: 
 6247: Here are some
 6248: examples:
 6249: 
 6250: @example
 6251: 12 Value APPLES     \ Define APPLES with an initial value of 12
 6252: 34 TO APPLES        \ Change the value of APPLES. TO is a parsing word
 6253: 1 ' APPLES >body +! \ Increment APPLES.  Non-standard usage.
 6254: APPLES              \ puts 35 on the top of the stack.
 6255: @end example
 6256: 
 6257: doc-value
 6258: doc-to
 6259: 
 6260: 
 6261: 
 6262: @node Colon Definitions, Anonymous Definitions, Values, Defining Words
 6263: @subsection Colon Definitions
 6264: @cindex colon definitions
 6265: 
 6266: @example
 6267: : name ( ... -- ... )
 6268:     word1 word2 word3 ;
 6269: @end example
 6270: 
 6271: @noindent
 6272: Creates a word called @code{name} that, upon execution, executes
 6273: @code{word1 word2 word3}. @code{name} is a @dfn{(colon) definition}.
 6274: 
 6275: The explanation above is somewhat superficial. For simple examples of
 6276: colon definitions see @ref{Your first definition}.  For an in-depth
 6277: discussion of some of the issues involved, @xref{Interpretation and
 6278: Compilation Semantics}.
 6279: 
 6280: doc-:
 6281: doc-;
 6282: 
 6283: 
 6284: @node Anonymous Definitions, Supplying names, Colon Definitions, Defining Words
 6285: @subsection Anonymous Definitions
 6286: @cindex colon definitions
 6287: @cindex defining words without name
 6288: 
 6289: Sometimes you want to define an @dfn{anonymous word}; a word without a
 6290: name. You can do this with:
 6291: 
 6292: doc-:noname
 6293: 
 6294: This leaves the execution token for the word on the stack after the
 6295: closing @code{;}. Here's an example in which a deferred word is
 6296: initialised with an @code{xt} from an anonymous colon definition:
 6297: 
 6298: @example
 6299: Defer deferred
 6300: :noname ( ... -- ... )
 6301:   ... ;
 6302: IS deferred
 6303: @end example
 6304: 
 6305: @noindent
 6306: Gforth provides an alternative way of doing this, using two separate
 6307: words:
 6308: 
 6309: doc-noname
 6310: @cindex execution token of last defined word
 6311: doc-latestxt
 6312: 
 6313: @noindent
 6314: The previous example can be rewritten using @code{noname} and
 6315: @code{latestxt}:
 6316: 
 6317: @example
 6318: Defer deferred
 6319: noname : ( ... -- ... )
 6320:   ... ;
 6321: latestxt IS deferred
 6322: @end example
 6323: 
 6324: @noindent
 6325: @code{noname} works with any defining word, not just @code{:}.
 6326: 
 6327: @code{latestxt} also works when the last word was not defined as
 6328: @code{noname}.  It does not work for combined words, though.  It also has
 6329: the useful property that is is valid as soon as the header for a
 6330: definition has been built. Thus:
 6331: 
 6332: @example
 6333: latestxt . : foo [ latestxt . ] ; ' foo .
 6334: @end example
 6335: 
 6336: @noindent
 6337: prints 3 numbers; the last two are the same.
 6338: 
 6339: @node Supplying names, User-defined Defining Words, Anonymous Definitions, Defining Words
 6340: @subsection Supplying the name of a defined word
 6341: @cindex names for defined words
 6342: @cindex defining words, name given in a string
 6343: 
 6344: By default, a defining word takes the name for the defined word from the
 6345: input stream. Sometimes you want to supply the name from a string. You
 6346: can do this with:
 6347: 
 6348: doc-nextname
 6349: 
 6350: For example:
 6351: 
 6352: @example
 6353: s" foo" nextname create
 6354: @end example
 6355: 
 6356: @noindent
 6357: is equivalent to:
 6358: 
 6359: @example
 6360: create foo
 6361: @end example
 6362: 
 6363: @noindent
 6364: @code{nextname} works with any defining word.
 6365: 
 6366: 
 6367: @node User-defined Defining Words, Deferred Words, Supplying names, Defining Words
 6368: @subsection User-defined Defining Words
 6369: @cindex user-defined defining words
 6370: @cindex defining words, user-defined
 6371: 
 6372: You can create a new defining word by wrapping defining-time code around
 6373: an existing defining word and putting the sequence in a colon
 6374: definition. 
 6375: 
 6376: @c anton: This example is very complex and leads in a quite different
 6377: @c direction from the CREATE-DOES> stuff that follows.  It should probably
 6378: @c be done elsewhere, or as a subsubsection of this subsection (or as a
 6379: @c subsection of Defining Words)
 6380: 
 6381: For example, suppose that you have a word @code{stats} that
 6382: gathers statistics about colon definitions given the @i{xt} of the
 6383: definition, and you want every colon definition in your application to
 6384: make a call to @code{stats}. You can define and use a new version of
 6385: @code{:} like this:
 6386: 
 6387: @example
 6388: : stats ( xt -- ) DUP ." (Gathering statistics for " . ." )"
 6389:   ... ;  \ other code
 6390: 
 6391: : my: : latestxt postpone literal ['] stats compile, ;
 6392: 
 6393: my: foo + - ;
 6394: @end example
 6395: 
 6396: When @code{foo} is defined using @code{my:} these steps occur:
 6397: 
 6398: @itemize @bullet
 6399: @item
 6400: @code{my:} is executed.
 6401: @item
 6402: The @code{:} within the definition (the one between @code{my:} and
 6403: @code{latestxt}) is executed, and does just what it always does; it parses
 6404: the input stream for a name, builds a dictionary header for the name
 6405: @code{foo} and switches @code{state} from interpret to compile.
 6406: @item
 6407: The word @code{latestxt} is executed. It puts the @i{xt} for the word that is
 6408: being defined -- @code{foo} -- onto the stack.
 6409: @item
 6410: The code that was produced by @code{postpone literal} is executed; this
 6411: causes the value on the stack to be compiled as a literal in the code
 6412: area of @code{foo}.
 6413: @item
 6414: The code @code{['] stats} compiles a literal into the definition of
 6415: @code{my:}. When @code{compile,} is executed, that literal -- the
 6416: execution token for @code{stats} -- is layed down in the code area of
 6417: @code{foo} , following the literal@footnote{Strictly speaking, the
 6418: mechanism that @code{compile,} uses to convert an @i{xt} into something
 6419: in the code area is implementation-dependent. A threaded implementation
 6420: might spit out the execution token directly whilst another
 6421: implementation might spit out a native code sequence.}.
 6422: @item
 6423: At this point, the execution of @code{my:} is complete, and control
 6424: returns to the text interpreter. The text interpreter is in compile
 6425: state, so subsequent text @code{+ -} is compiled into the definition of
 6426: @code{foo} and the @code{;} terminates the definition as always.
 6427: @end itemize
 6428: 
 6429: You can use @code{see} to decompile a word that was defined using
 6430: @code{my:} and see how it is different from a normal @code{:}
 6431: definition. For example:
 6432: 
 6433: @example
 6434: : bar + - ;  \ like foo but using : rather than my:
 6435: see bar
 6436: : bar
 6437:   + - ;
 6438: see foo
 6439: : foo
 6440:   107645672 stats + - ;
 6441: 
 6442: \ use ' foo . to show that 107645672 is the xt for foo
 6443: @end example
 6444: 
 6445: You can use techniques like this to make new defining words in terms of
 6446: @i{any} existing defining word.
 6447: 
 6448: 
 6449: @cindex defining defining words
 6450: @cindex @code{CREATE} ... @code{DOES>}
 6451: If you want the words defined with your defining words to behave
 6452: differently from words defined with standard defining words, you can
 6453: write your defining word like this:
 6454: 
 6455: @example
 6456: : def-word ( "name" -- )
 6457:     CREATE @i{code1}
 6458: DOES> ( ... -- ... )
 6459:     @i{code2} ;
 6460: 
 6461: def-word name
 6462: @end example
 6463: 
 6464: @cindex child words
 6465: This fragment defines a @dfn{defining word} @code{def-word} and then
 6466: executes it.  When @code{def-word} executes, it @code{CREATE}s a new
 6467: word, @code{name}, and executes the code @i{code1}. The code @i{code2}
 6468: is not executed at this time. The word @code{name} is sometimes called a
 6469: @dfn{child} of @code{def-word}.
 6470: 
 6471: When you execute @code{name}, the address of the body of @code{name} is
 6472: put on the data stack and @i{code2} is executed (the address of the body
 6473: of @code{name} is the address @code{HERE} returns immediately after the
 6474: @code{CREATE}, i.e., the address a @code{create}d word returns by
 6475: default).
 6476: 
 6477: @c anton:
 6478: @c www.dictionary.com says:
 6479: @c at·a·vism: 1.The reappearance of a characteristic in an organism after
 6480: @c several generations of absence, usually caused by the chance
 6481: @c recombination of genes.  2.An individual or a part that exhibits
 6482: @c atavism. Also called throwback.  3.The return of a trait or recurrence
 6483: @c of previous behavior after a period of absence.
 6484: @c
 6485: @c Doesn't seem to fit.
 6486: 
 6487: @c @cindex atavism in child words
 6488: You can use @code{def-word} to define a set of child words that behave
 6489: similarly; they all have a common run-time behaviour determined by
 6490: @i{code2}. Typically, the @i{code1} sequence builds a data area in the
 6491: body of the child word. The structure of the data is common to all
 6492: children of @code{def-word}, but the data values are specific -- and
 6493: private -- to each child word. When a child word is executed, the
 6494: address of its private data area is passed as a parameter on TOS to be
 6495: used and manipulated@footnote{It is legitimate both to read and write to
 6496: this data area.} by @i{code2}.
 6497: 
 6498: The two fragments of code that make up the defining words act (are
 6499: executed) at two completely separate times:
 6500: 
 6501: @itemize @bullet
 6502: @item
 6503: At @i{define time}, the defining word executes @i{code1} to generate a
 6504: child word
 6505: @item
 6506: At @i{child execution time}, when a child word is invoked, @i{code2}
 6507: is executed, using parameters (data) that are private and specific to
 6508: the child word.
 6509: @end itemize
 6510: 
 6511: Another way of understanding the behaviour of @code{def-word} and
 6512: @code{name} is to say that, if you make the following definitions:
 6513: @example
 6514: : def-word1 ( "name" -- )
 6515:     CREATE @i{code1} ;
 6516: 
 6517: : action1 ( ... -- ... )
 6518:     @i{code2} ;
 6519: 
 6520: def-word1 name1
 6521: @end example
 6522: 
 6523: @noindent
 6524: Then using @code{name1 action1} is equivalent to using @code{name}.
 6525: 
 6526: The classic example is that you can define @code{CONSTANT} in this way:
 6527: 
 6528: @example
 6529: : CONSTANT ( w "name" -- )
 6530:     CREATE ,
 6531: DOES> ( -- w )
 6532:     @@ ;
 6533: @end example
 6534: 
 6535: @comment There is a beautiful description of how this works and what
 6536: @comment it does in the Forthwrite 100th edition.. as well as an elegant
 6537: @comment commentary on the Counting Fruits problem.
 6538: 
 6539: When you create a constant with @code{5 CONSTANT five}, a set of
 6540: define-time actions take place; first a new word @code{five} is created,
 6541: then the value 5 is laid down in the body of @code{five} with
 6542: @code{,}. When @code{five} is executed, the address of the body is put on
 6543: the stack, and @code{@@} retrieves the value 5. The word @code{five} has
 6544: no code of its own; it simply contains a data field and a pointer to the
 6545: code that follows @code{DOES>} in its defining word. That makes words
 6546: created in this way very compact.
 6547: 
 6548: The final example in this section is intended to remind you that space
 6549: reserved in @code{CREATE}d words is @i{data} space and therefore can be
 6550: both read and written by a Standard program@footnote{Exercise: use this
 6551: example as a starting point for your own implementation of @code{Value}
 6552: and @code{TO} -- if you get stuck, investigate the behaviour of @code{'} and
 6553: @code{[']}.}:
 6554: 
 6555: @example
 6556: : foo ( "name" -- )
 6557:     CREATE -1 ,
 6558: DOES> ( -- )
 6559:     @@ . ;
 6560: 
 6561: foo first-word
 6562: foo second-word
 6563: 
 6564: 123 ' first-word >BODY !
 6565: @end example
 6566: 
 6567: If @code{first-word} had been a @code{CREATE}d word, we could simply
 6568: have executed it to get the address of its data field. However, since it
 6569: was defined to have @code{DOES>} actions, its execution semantics are to
 6570: perform those @code{DOES>} actions. To get the address of its data field
 6571: it's necessary to use @code{'} to get its xt, then @code{>BODY} to
 6572: translate the xt into the address of the data field.  When you execute
 6573: @code{first-word}, it will display @code{123}. When you execute
 6574: @code{second-word} it will display @code{-1}.
 6575: 
 6576: @cindex stack effect of @code{DOES>}-parts
 6577: @cindex @code{DOES>}-parts, stack effect
 6578: In the examples above the stack comment after the @code{DOES>} specifies
 6579: the stack effect of the defined words, not the stack effect of the
 6580: following code (the following code expects the address of the body on
 6581: the top of stack, which is not reflected in the stack comment). This is
 6582: the convention that I use and recommend (it clashes a bit with using
 6583: locals declarations for stack effect specification, though).
 6584: 
 6585: @menu
 6586: * CREATE..DOES> applications::  
 6587: * CREATE..DOES> details::       
 6588: * Advanced does> usage example::  
 6589: * Const-does>::                 
 6590: @end menu
 6591: 
 6592: @node CREATE..DOES> applications, CREATE..DOES> details, User-defined Defining Words, User-defined Defining Words
 6593: @subsubsection Applications of @code{CREATE..DOES>}
 6594: @cindex @code{CREATE} ... @code{DOES>}, applications
 6595: 
 6596: You may wonder how to use this feature. Here are some usage patterns:
 6597: 
 6598: @cindex factoring similar colon definitions
 6599: When you see a sequence of code occurring several times, and you can
 6600: identify a meaning, you will factor it out as a colon definition. When
 6601: you see similar colon definitions, you can factor them using
 6602: @code{CREATE..DOES>}. E.g., an assembler usually defines several words
 6603: that look very similar:
 6604: @example
 6605: : ori, ( reg-target reg-source n -- )
 6606:     0 asm-reg-reg-imm ;
 6607: : andi, ( reg-target reg-source n -- )
 6608:     1 asm-reg-reg-imm ;
 6609: @end example
 6610: 
 6611: @noindent
 6612: This could be factored with:
 6613: @example
 6614: : reg-reg-imm ( op-code -- )
 6615:     CREATE ,
 6616: DOES> ( reg-target reg-source n -- )
 6617:     @@ asm-reg-reg-imm ;
 6618: 
 6619: 0 reg-reg-imm ori,
 6620: 1 reg-reg-imm andi,
 6621: @end example
 6622: 
 6623: @cindex currying
 6624: Another view of @code{CREATE..DOES>} is to consider it as a crude way to
 6625: supply a part of the parameters for a word (known as @dfn{currying} in
 6626: the functional language community). E.g., @code{+} needs two
 6627: parameters. Creating versions of @code{+} with one parameter fixed can
 6628: be done like this:
 6629: 
 6630: @example
 6631: : curry+ ( n1 "name" -- )
 6632:     CREATE ,
 6633: DOES> ( n2 -- n1+n2 )
 6634:     @@ + ;
 6635: 
 6636:  3 curry+ 3+
 6637: -2 curry+ 2-
 6638: @end example
 6639: 
 6640: 
 6641: @node CREATE..DOES> details, Advanced does> usage example, CREATE..DOES> applications, User-defined Defining Words
 6642: @subsubsection The gory details of @code{CREATE..DOES>}
 6643: @cindex @code{CREATE} ... @code{DOES>}, details
 6644: 
 6645: doc-does>
 6646: 
 6647: @cindex @code{DOES>} in a separate definition
 6648: This means that you need not use @code{CREATE} and @code{DOES>} in the
 6649: same definition; you can put the @code{DOES>}-part in a separate
 6650: definition. This allows us to, e.g., select among different @code{DOES>}-parts:
 6651: @example
 6652: : does1 
 6653: DOES> ( ... -- ... )
 6654:     ... ;
 6655: 
 6656: : does2
 6657: DOES> ( ... -- ... )
 6658:     ... ;
 6659: 
 6660: : def-word ( ... -- ... )
 6661:     create ...
 6662:     IF
 6663:        does1
 6664:     ELSE
 6665:        does2
 6666:     ENDIF ;
 6667: @end example
 6668: 
 6669: In this example, the selection of whether to use @code{does1} or
 6670: @code{does2} is made at definition-time; at the time that the child word is
 6671: @code{CREATE}d.
 6672: 
 6673: @cindex @code{DOES>} in interpretation state
 6674: In a standard program you can apply a @code{DOES>}-part only if the last
 6675: word was defined with @code{CREATE}. In Gforth, the @code{DOES>}-part
 6676: will override the behaviour of the last word defined in any case. In a
 6677: standard program, you can use @code{DOES>} only in a colon
 6678: definition. In Gforth, you can also use it in interpretation state, in a
 6679: kind of one-shot mode; for example:
 6680: @example
 6681: CREATE name ( ... -- ... )
 6682:   @i{initialization}
 6683: DOES>
 6684:   @i{code} ;
 6685: @end example
 6686: 
 6687: @noindent
 6688: is equivalent to the standard:
 6689: @example
 6690: :noname
 6691: DOES>
 6692:     @i{code} ;
 6693: CREATE name EXECUTE ( ... -- ... )
 6694:     @i{initialization}
 6695: @end example
 6696: 
 6697: doc->body
 6698: 
 6699: @node Advanced does> usage example, Const-does>, CREATE..DOES> details, User-defined Defining Words
 6700: @subsubsection Advanced does> usage example
 6701: 
 6702: The MIPS disassembler (@file{arch/mips/disasm.fs}) contains many words
 6703: for disassembling instructions, that follow a very repetetive scheme:
 6704: 
 6705: @example
 6706: :noname @var{disasm-operands} s" @var{inst-name}" type ;
 6707: @var{entry-num} cells @var{table} + !
 6708: @end example
 6709: 
 6710: Of course, this inspires the idea to factor out the commonalities to
 6711: allow a definition like
 6712: 
 6713: @example
 6714: @var{disasm-operands} @var{entry-num} @var{table} define-inst @var{inst-name}
 6715: @end example
 6716: 
 6717: The parameters @var{disasm-operands} and @var{table} are usually
 6718: correlated.  Moreover, before I wrote the disassembler, there already
 6719: existed code that defines instructions like this:
 6720: 
 6721: @example
 6722: @var{entry-num} @var{inst-format} @var{inst-name}
 6723: @end example
 6724: 
 6725: This code comes from the assembler and resides in
 6726: @file{arch/mips/insts.fs}.
 6727: 
 6728: So I had to define the @var{inst-format} words that performed the scheme
 6729: above when executed.  At first I chose to use run-time code-generation:
 6730: 
 6731: @example
 6732: : @var{inst-format} ( entry-num "name" -- ; compiled code: addr w -- )
 6733:   :noname Postpone @var{disasm-operands}
 6734:   name Postpone sliteral Postpone type Postpone ;
 6735:   swap cells @var{table} + ! ;
 6736: @end example
 6737: 
 6738: Note that this supplies the other two parameters of the scheme above.
 6739: 
 6740: An alternative would have been to write this using
 6741: @code{create}/@code{does>}:
 6742: 
 6743: @example
 6744: : @var{inst-format} ( entry-num "name" -- )
 6745:   here name string, ( entry-num c-addr ) \ parse and save "name"
 6746:   noname create , ( entry-num )
 6747:   latestxt swap cells @var{table} + !
 6748: does> ( addr w -- )
 6749:   \ disassemble instruction w at addr
 6750:   @@ >r 
 6751:   @var{disasm-operands}
 6752:   r> count type ;
 6753: @end example
 6754: 
 6755: Somehow the first solution is simpler, mainly because it's simpler to
 6756: shift a string from definition-time to use-time with @code{sliteral}
 6757: than with @code{string,} and friends.
 6758: 
 6759: I wrote a lot of words following this scheme and soon thought about
 6760: factoring out the commonalities among them.  Note that this uses a
 6761: two-level defining word, i.e., a word that defines ordinary defining
 6762: words.
 6763: 
 6764: This time a solution involving @code{postpone} and friends seemed more
 6765: difficult (try it as an exercise), so I decided to use a
 6766: @code{create}/@code{does>} word; since I was already at it, I also used
 6767: @code{create}/@code{does>} for the lower level (try using
 6768: @code{postpone} etc. as an exercise), resulting in the following
 6769: definition:
 6770: 
 6771: @example
 6772: : define-format ( disasm-xt table-xt -- )
 6773:     \ define an instruction format that uses disasm-xt for
 6774:     \ disassembling and enters the defined instructions into table
 6775:     \ table-xt
 6776:     create 2,
 6777: does> ( u "inst" -- )
 6778:     \ defines an anonymous word for disassembling instruction inst,
 6779:     \ and enters it as u-th entry into table-xt
 6780:     2@@ swap here name string, ( u table-xt disasm-xt c-addr ) \ remember string
 6781:     noname create 2,      \ define anonymous word
 6782:     execute latestxt swap ! \ enter xt of defined word into table-xt
 6783: does> ( addr w -- )
 6784:     \ disassemble instruction w at addr
 6785:     2@@ >r ( addr w disasm-xt R: c-addr )
 6786:     execute ( R: c-addr ) \ disassemble operands
 6787:     r> count type ; \ print name 
 6788: @end example
 6789: 
 6790: Note that the tables here (in contrast to above) do the @code{cells +}
 6791: by themselves (that's why you have to pass an xt).  This word is used in
 6792: the following way:
 6793: 
 6794: @example
 6795: ' @var{disasm-operands} ' @var{table} define-format @var{inst-format}
 6796: @end example
 6797: 
 6798: As shown above, the defined instruction format is then used like this:
 6799: 
 6800: @example
 6801: @var{entry-num} @var{inst-format} @var{inst-name}
 6802: @end example
 6803: 
 6804: In terms of currying, this kind of two-level defining word provides the
 6805: parameters in three stages: first @var{disasm-operands} and @var{table},
 6806: then @var{entry-num} and @var{inst-name}, finally @code{addr w}, i.e.,
 6807: the instruction to be disassembled.  
 6808: 
 6809: Of course this did not quite fit all the instruction format names used
 6810: in @file{insts.fs}, so I had to define a few wrappers that conditioned
 6811: the parameters into the right form.
 6812: 
 6813: If you have trouble following this section, don't worry.  First, this is
 6814: involved and takes time (and probably some playing around) to
 6815: understand; second, this is the first two-level
 6816: @code{create}/@code{does>} word I have written in seventeen years of
 6817: Forth; and if I did not have @file{insts.fs} to start with, I may well
 6818: have elected to use just a one-level defining word (with some repeating
 6819: of parameters when using the defining word). So it is not necessary to
 6820: understand this, but it may improve your understanding of Forth.
 6821: 
 6822: 
 6823: @node Const-does>,  , Advanced does> usage example, User-defined Defining Words
 6824: @subsubsection @code{Const-does>}
 6825: 
 6826: A frequent use of @code{create}...@code{does>} is for transferring some
 6827: values from definition-time to run-time.  Gforth supports this use with
 6828: 
 6829: doc-const-does>
 6830: 
 6831: A typical use of this word is:
 6832: 
 6833: @example
 6834: : curry+ ( n1 "name" -- )
 6835: 1 0 CONST-DOES> ( n2 -- n1+n2 )
 6836:     + ;
 6837: 
 6838: 3 curry+ 3+
 6839: @end example
 6840: 
 6841: Here the @code{1 0} means that 1 cell and 0 floats are transferred from
 6842: definition to run-time.
 6843: 
 6844: The advantages of using @code{const-does>} are:
 6845: 
 6846: @itemize
 6847: 
 6848: @item
 6849: You don't have to deal with storing and retrieving the values, i.e.,
 6850: your program becomes more writable and readable.
 6851: 
 6852: @item
 6853: When using @code{does>}, you have to introduce a @code{@@} that cannot
 6854: be optimized away (because you could change the data using
 6855: @code{>body}...@code{!}); @code{const-does>} avoids this problem.
 6856: 
 6857: @end itemize
 6858: 
 6859: An ANS Forth implementation of @code{const-does>} is available in
 6860: @file{compat/const-does.fs}.
 6861: 
 6862: 
 6863: @node Deferred Words, Aliases, User-defined Defining Words, Defining Words
 6864: @subsection Deferred Words
 6865: @cindex deferred words
 6866: 
 6867: The defining word @code{Defer} allows you to define a word by name
 6868: without defining its behaviour; the definition of its behaviour is
 6869: deferred. Here are two situation where this can be useful:
 6870: 
 6871: @itemize @bullet
 6872: @item
 6873: Where you want to allow the behaviour of a word to be altered later, and
 6874: for all precompiled references to the word to change when its behaviour
 6875: is changed.
 6876: @item
 6877: For mutual recursion; @xref{Calls and returns}.
 6878: @end itemize
 6879: 
 6880: In the following example, @code{foo} always invokes the version of
 6881: @code{greet} that prints ``@code{Good morning}'' whilst @code{bar}
 6882: always invokes the version that prints ``@code{Hello}''. There is no way
 6883: of getting @code{foo} to use the later version without re-ordering the
 6884: source code and recompiling it.
 6885: 
 6886: @example
 6887: : greet ." Good morning" ;
 6888: : foo ... greet ... ;
 6889: : greet ." Hello" ;
 6890: : bar ... greet ... ;
 6891: @end example
 6892: 
 6893: This problem can be solved by defining @code{greet} as a @code{Defer}red
 6894: word. The behaviour of a @code{Defer}red word can be defined and
 6895: redefined at any time by using @code{IS} to associate the xt of a
 6896: previously-defined word with it. The previous example becomes:
 6897: 
 6898: @example
 6899: Defer greet ( -- )
 6900: : foo ... greet ... ;
 6901: : bar ... greet ... ;
 6902: : greet1 ( -- ) ." Good morning" ;
 6903: : greet2 ( -- ) ." Hello" ;
 6904: ' greet2 IS greet  \ make greet behave like greet2
 6905: @end example
 6906: 
 6907: @progstyle
 6908: You should write a stack comment for every deferred word, and put only
 6909: XTs into deferred words that conform to this stack effect.  Otherwise
 6910: it's too difficult to use the deferred word.
 6911: 
 6912: A deferred word can be used to improve the statistics-gathering example
 6913: from @ref{User-defined Defining Words}; rather than edit the
 6914: application's source code to change every @code{:} to a @code{my:}, do
 6915: this:
 6916: 
 6917: @example
 6918: : real: : ;     \ retain access to the original
 6919: defer :         \ redefine as a deferred word
 6920: ' my: IS :      \ use special version of :
 6921: \
 6922: \ load application here
 6923: \
 6924: ' real: IS :    \ go back to the original
 6925: @end example
 6926: 
 6927: 
 6928: One thing to note is that @code{IS} has special compilation semantics,
 6929: such that it parses the name at compile time (like @code{TO}):
 6930: 
 6931: @example
 6932: : set-greet ( xt -- )
 6933:   IS greet ;
 6934: 
 6935: ' greet1 set-greet
 6936: @end example
 6937: 
 6938: In situations where @code{IS} does not fit, use @code{defer!} instead.
 6939: 
 6940: A deferred word can only inherit execution semantics from the xt
 6941: (because that is all that an xt can represent -- for more discussion of
 6942: this @pxref{Tokens for Words}); by default it will have default
 6943: interpretation and compilation semantics deriving from this execution
 6944: semantics.  However, you can change the interpretation and compilation
 6945: semantics of the deferred word in the usual ways:
 6946: 
 6947: @example
 6948: : bar .... ; immediate
 6949: Defer fred immediate
 6950: Defer jim
 6951: 
 6952: ' bar IS jim  \ jim has default semantics
 6953: ' bar IS fred \ fred is immediate
 6954: @end example
 6955: 
 6956: doc-defer
 6957: doc-defer!
 6958: doc-is
 6959: doc-defer@
 6960: doc-action-of
 6961: @comment TODO document these: what's defers [is]
 6962: doc-defers
 6963: 
 6964: @c Use @code{words-deferred} to see a list of deferred words.
 6965: 
 6966: Definitions of these words (except @code{defers}) in ANS Forth are
 6967: provided in @file{compat/defer.fs}.
 6968: 
 6969: 
 6970: @node Aliases,  , Deferred Words, Defining Words
 6971: @subsection Aliases
 6972: @cindex aliases
 6973: 
 6974: The defining word @code{Alias} allows you to define a word by name that
 6975: has the same behaviour as some other word. Here are two situation where
 6976: this can be useful:
 6977: 
 6978: @itemize @bullet
 6979: @item
 6980: When you want access to a word's definition from a different word list
 6981: (for an example of this, see the definition of the @code{Root} word list
 6982: in the Gforth source).
 6983: @item
 6984: When you want to create a synonym; a definition that can be known by
 6985: either of two names (for example, @code{THEN} and @code{ENDIF} are
 6986: aliases).
 6987: @end itemize
 6988: 
 6989: Like deferred words, an alias has default compilation and interpretation
 6990: semantics at the beginning (not the modifications of the other word),
 6991: but you can change them in the usual ways (@code{immediate},
 6992: @code{compile-only}). For example:
 6993: 
 6994: @example
 6995: : foo ... ; immediate
 6996: 
 6997: ' foo Alias bar \ bar is not an immediate word
 6998: ' foo Alias fooby immediate \ fooby is an immediate word
 6999: @end example
 7000: 
 7001: Words that are aliases have the same xt, different headers in the
 7002: dictionary, and consequently different name tokens (@pxref{Tokens for
 7003: Words}) and possibly different immediate flags.  An alias can only have
 7004: default or immediate compilation semantics; you can define aliases for
 7005: combined words with @code{interpret/compile:} -- see @ref{Combined words}.
 7006: 
 7007: doc-alias
 7008: 
 7009: 
 7010: @node Interpretation and Compilation Semantics, Tokens for Words, Defining Words, Words
 7011: @section Interpretation and Compilation Semantics
 7012: @cindex semantics, interpretation and compilation
 7013: 
 7014: @c !! state and ' are used without explanation
 7015: @c example for immediate/compile-only? or is the tutorial enough
 7016: 
 7017: @cindex interpretation semantics
 7018: The @dfn{interpretation semantics} of a (named) word are what the text
 7019: interpreter does when it encounters the word in interpret state. It also
 7020: appears in some other contexts, e.g., the execution token returned by
 7021: @code{' @i{word}} identifies the interpretation semantics of @i{word}
 7022: (in other words, @code{' @i{word} execute} is equivalent to
 7023: interpret-state text interpretation of @code{@i{word}}).
 7024: 
 7025: @cindex compilation semantics
 7026: The @dfn{compilation semantics} of a (named) word are what the text
 7027: interpreter does when it encounters the word in compile state. It also
 7028: appears in other contexts, e.g, @code{POSTPONE @i{word}}
 7029: compiles@footnote{In standard terminology, ``appends to the current
 7030: definition''.} the compilation semantics of @i{word}.
 7031: 
 7032: @cindex execution semantics
 7033: The standard also talks about @dfn{execution semantics}. They are used
 7034: only for defining the interpretation and compilation semantics of many
 7035: words. By default, the interpretation semantics of a word are to
 7036: @code{execute} its execution semantics, and the compilation semantics of
 7037: a word are to @code{compile,} its execution semantics.@footnote{In
 7038: standard terminology: The default interpretation semantics are its
 7039: execution semantics; the default compilation semantics are to append its
 7040: execution semantics to the execution semantics of the current
 7041: definition.}
 7042: 
 7043: Unnamed words (@pxref{Anonymous Definitions}) cannot be encountered by
 7044: the text interpreter, ticked, or @code{postpone}d, so they have no
 7045: interpretation or compilation semantics.  Their behaviour is represented
 7046: by their XT (@pxref{Tokens for Words}), and we call it execution
 7047: semantics, too.
 7048: 
 7049: @comment TODO expand, make it co-operate with new sections on text interpreter.
 7050: 
 7051: @cindex immediate words
 7052: @cindex compile-only words
 7053: You can change the semantics of the most-recently defined word:
 7054: 
 7055: 
 7056: doc-immediate
 7057: doc-compile-only
 7058: doc-restrict
 7059: 
 7060: By convention, words with non-default compilation semantics (e.g.,
 7061: immediate words) often have names surrounded with brackets (e.g.,
 7062: @code{[']}, @pxref{Execution token}).
 7063: 
 7064: Note that ticking (@code{'}) a compile-only word gives an error
 7065: (``Interpreting a compile-only word'').
 7066: 
 7067: @menu
 7068: * Combined words::              
 7069: @end menu
 7070: 
 7071: 
 7072: @node Combined words,  , Interpretation and Compilation Semantics, Interpretation and Compilation Semantics
 7073: @subsection Combined Words
 7074: @cindex combined words
 7075: 
 7076: Gforth allows you to define @dfn{combined words} -- words that have an
 7077: arbitrary combination of interpretation and compilation semantics.
 7078: 
 7079: doc-interpret/compile:
 7080: 
 7081: This feature was introduced for implementing @code{TO} and @code{S"}. I
 7082: recommend that you do not define such words, as cute as they may be:
 7083: they make it hard to get at both parts of the word in some contexts.
 7084: E.g., assume you want to get an execution token for the compilation
 7085: part. Instead, define two words, one that embodies the interpretation
 7086: part, and one that embodies the compilation part.  Once you have done
 7087: that, you can define a combined word with @code{interpret/compile:} for
 7088: the convenience of your users.
 7089: 
 7090: You might try to use this feature to provide an optimizing
 7091: implementation of the default compilation semantics of a word. For
 7092: example, by defining:
 7093: @example
 7094: :noname
 7095:    foo bar ;
 7096: :noname
 7097:    POSTPONE foo POSTPONE bar ;
 7098: interpret/compile: opti-foobar
 7099: @end example
 7100: 
 7101: @noindent
 7102: as an optimizing version of:
 7103: 
 7104: @example
 7105: : foobar
 7106:     foo bar ;
 7107: @end example
 7108: 
 7109: Unfortunately, this does not work correctly with @code{[compile]},
 7110: because @code{[compile]} assumes that the compilation semantics of all
 7111: @code{interpret/compile:} words are non-default. I.e., @code{[compile]
 7112: opti-foobar} would compile compilation semantics, whereas
 7113: @code{[compile] foobar} would compile interpretation semantics.
 7114: 
 7115: @cindex state-smart words (are a bad idea)
 7116: @anchor{state-smartness}
 7117: Some people try to use @dfn{state-smart} words to emulate the feature provided
 7118: by @code{interpret/compile:} (words are state-smart if they check
 7119: @code{STATE} during execution). E.g., they would try to code
 7120: @code{foobar} like this:
 7121: 
 7122: @example
 7123: : foobar
 7124:   STATE @@
 7125:   IF ( compilation state )
 7126:     POSTPONE foo POSTPONE bar
 7127:   ELSE
 7128:     foo bar
 7129:   ENDIF ; immediate
 7130: @end example
 7131: 
 7132: Although this works if @code{foobar} is only processed by the text
 7133: interpreter, it does not work in other contexts (like @code{'} or
 7134: @code{POSTPONE}). E.g., @code{' foobar} will produce an execution token
 7135: for a state-smart word, not for the interpretation semantics of the
 7136: original @code{foobar}; when you execute this execution token (directly
 7137: with @code{EXECUTE} or indirectly through @code{COMPILE,}) in compile
 7138: state, the result will not be what you expected (i.e., it will not
 7139: perform @code{foo bar}). State-smart words are a bad idea. Simply don't
 7140: write them@footnote{For a more detailed discussion of this topic, see
 7141: M. Anton Ertl,
 7142: @cite{@uref{http://www.complang.tuwien.ac.at/papers/ertl98.ps.gz,@code{State}-smartness---Why
 7143: it is Evil and How to Exorcise it}}, EuroForth '98.}!
 7144: 
 7145: @cindex defining words with arbitrary semantics combinations
 7146: It is also possible to write defining words that define words with
 7147: arbitrary combinations of interpretation and compilation semantics. In
 7148: general, they look like this:
 7149: 
 7150: @example
 7151: : def-word
 7152:     create-interpret/compile
 7153:     @i{code1}
 7154: interpretation>
 7155:     @i{code2}
 7156: <interpretation
 7157: compilation>
 7158:     @i{code3}
 7159: <compilation ;
 7160: @end example
 7161: 
 7162: For a @i{word} defined with @code{def-word}, the interpretation
 7163: semantics are to push the address of the body of @i{word} and perform
 7164: @i{code2}, and the compilation semantics are to push the address of
 7165: the body of @i{word} and perform @i{code3}. E.g., @code{constant}
 7166: can also be defined like this (except that the defined constants don't
 7167: behave correctly when @code{[compile]}d):
 7168: 
 7169: @example
 7170: : constant ( n "name" -- )
 7171:     create-interpret/compile
 7172:     ,
 7173: interpretation> ( -- n )
 7174:     @@
 7175: <interpretation
 7176: compilation> ( compilation. -- ; run-time. -- n )
 7177:     @@ postpone literal
 7178: <compilation ;
 7179: @end example
 7180: 
 7181: 
 7182: doc-create-interpret/compile
 7183: doc-interpretation>
 7184: doc-<interpretation
 7185: doc-compilation>
 7186: doc-<compilation
 7187: 
 7188: 
 7189: Words defined with @code{interpret/compile:} and
 7190: @code{create-interpret/compile} have an extended header structure that
 7191: differs from other words; however, unless you try to access them with
 7192: plain address arithmetic, you should not notice this. Words for
 7193: accessing the header structure usually know how to deal with this; e.g.,
 7194: @code{'} @i{word} @code{>body} also gives you the body of a word created
 7195: with @code{create-interpret/compile}.
 7196: 
 7197: 
 7198: @c -------------------------------------------------------------
 7199: @node Tokens for Words, Compiling words, Interpretation and Compilation Semantics, Words
 7200: @section Tokens for Words
 7201: @cindex tokens for words
 7202: 
 7203: This section describes the creation and use of tokens that represent
 7204: words.
 7205: 
 7206: @menu
 7207: * Execution token::             represents execution/interpretation semantics
 7208: * Compilation token::           represents compilation semantics
 7209: * Name token::                  represents named words
 7210: @end menu
 7211: 
 7212: @node Execution token, Compilation token, Tokens for Words, Tokens for Words
 7213: @subsection Execution token
 7214: 
 7215: @cindex xt
 7216: @cindex execution token
 7217: An @dfn{execution token} (@i{XT}) represents some behaviour of a word.
 7218: You can use @code{execute} to invoke this behaviour.
 7219: 
 7220: @cindex tick (')
 7221: You can use @code{'} to get an execution token that represents the
 7222: interpretation semantics of a named word:
 7223: 
 7224: @example
 7225: 5 ' .   ( n xt ) 
 7226: execute ( )      \ execute the xt (i.e., ".")
 7227: @end example
 7228: 
 7229: doc-'
 7230: 
 7231: @code{'} parses at run-time; there is also a word @code{[']} that parses
 7232: when it is compiled, and compiles the resulting XT:
 7233: 
 7234: @example
 7235: : foo ['] . execute ;
 7236: 5 foo
 7237: : bar ' execute ; \ by contrast,
 7238: 5 bar .           \ ' parses "." when bar executes
 7239: @end example
 7240: 
 7241: doc-[']
 7242: 
 7243: If you want the execution token of @i{word}, write @code{['] @i{word}}
 7244: in compiled code and @code{' @i{word}} in interpreted code.  Gforth's
 7245: @code{'} and @code{[']} behave somewhat unusually by complaining about
 7246: compile-only words (because these words have no interpretation
 7247: semantics).  You might get what you want by using @code{COMP' @i{word}
 7248: DROP} or @code{[COMP'] @i{word} DROP} (for details @pxref{Compilation
 7249: token}).
 7250: 
 7251: Another way to get an XT is @code{:noname} or @code{latestxt}
 7252: (@pxref{Anonymous Definitions}).  For anonymous words this gives an xt
 7253: for the only behaviour the word has (the execution semantics).  For
 7254: named words, @code{latestxt} produces an XT for the same behaviour it
 7255: would produce if the word was defined anonymously.
 7256: 
 7257: @example
 7258: :noname ." hello" ;
 7259: execute
 7260: @end example
 7261: 
 7262: An XT occupies one cell and can be manipulated like any other cell.
 7263: 
 7264: @cindex code field address
 7265: @cindex CFA
 7266: In ANS Forth the XT is just an abstract data type (i.e., defined by the
 7267: operations that produce or consume it).  For old hands: In Gforth, the
 7268: XT is implemented as a code field address (CFA).
 7269: 
 7270: doc-execute
 7271: doc-perform
 7272: 
 7273: @node Compilation token, Name token, Execution token, Tokens for Words
 7274: @subsection Compilation token
 7275: 
 7276: @cindex compilation token
 7277: @cindex CT (compilation token)
 7278: Gforth represents the compilation semantics of a named word by a
 7279: @dfn{compilation token} consisting of two cells: @i{w xt}. The top cell
 7280: @i{xt} is an execution token. The compilation semantics represented by
 7281: the compilation token can be performed with @code{execute}, which
 7282: consumes the whole compilation token, with an additional stack effect
 7283: determined by the represented compilation semantics.
 7284: 
 7285: At present, the @i{w} part of a compilation token is an execution token,
 7286: and the @i{xt} part represents either @code{execute} or
 7287: @code{compile,}@footnote{Depending upon the compilation semantics of the
 7288: word. If the word has default compilation semantics, the @i{xt} will
 7289: represent @code{compile,}. Otherwise (e.g., for immediate words), the
 7290: @i{xt} will represent @code{execute}.}. However, don't rely on that
 7291: knowledge, unless necessary; future versions of Gforth may introduce
 7292: unusual compilation tokens (e.g., a compilation token that represents
 7293: the compilation semantics of a literal).
 7294: 
 7295: You can perform the compilation semantics represented by the compilation
 7296: token with @code{execute}.  You can compile the compilation semantics
 7297: with @code{postpone,}. I.e., @code{COMP' @i{word} postpone,} is
 7298: equivalent to @code{postpone @i{word}}.
 7299: 
 7300: doc-[comp']
 7301: doc-comp'
 7302: doc-postpone,
 7303: 
 7304: @node Name token,  , Compilation token, Tokens for Words
 7305: @subsection Name token
 7306: 
 7307: @cindex name token
 7308: Gforth represents named words by the @dfn{name token}, (@i{nt}).  Name
 7309: token is an abstract data type that occurs as argument or result of the
 7310: words below.
 7311: 
 7312: @c !! put this elswhere?
 7313: @cindex name field address
 7314: @cindex NFA
 7315: The closest thing to the nt in older Forth systems is the name field
 7316: address (NFA), but there are significant differences: in older Forth
 7317: systems each word had a unique NFA, LFA, CFA and PFA (in this order, or
 7318: LFA, NFA, CFA, PFA) and there were words for getting from one to the
 7319: next.  In contrast, in Gforth 0@dots{}n nts correspond to one xt; there
 7320: is a link field in the structure identified by the name token, but
 7321: searching usually uses a hash table external to these structures; the
 7322: name in Gforth has a cell-wide count-and-flags field, and the nt is not
 7323: implemented as the address of that count field.
 7324: 
 7325: doc-find-name
 7326: doc-latest
 7327: doc->name
 7328: doc-name>int
 7329: doc-name?int
 7330: doc-name>comp
 7331: doc-name>string
 7332: doc-id.
 7333: doc-.name
 7334: doc-.id
 7335: 
 7336: @c ----------------------------------------------------------
 7337: @node Compiling words, The Text Interpreter, Tokens for Words, Words
 7338: @section Compiling words
 7339: @cindex compiling words
 7340: @cindex macros
 7341: 
 7342: In contrast to most other languages, Forth has no strict boundary
 7343: between compilation and run-time.  E.g., you can run arbitrary code
 7344: between defining words (or for computing data used by defining words
 7345: like @code{constant}). Moreover, @code{Immediate} (@pxref{Interpretation
 7346: and Compilation Semantics} and @code{[}...@code{]} (see below) allow
 7347: running arbitrary code while compiling a colon definition (exception:
 7348: you must not allot dictionary space).
 7349: 
 7350: @menu
 7351: * Literals::                    Compiling data values
 7352: * Macros::                      Compiling words
 7353: @end menu
 7354: 
 7355: @node Literals, Macros, Compiling words, Compiling words
 7356: @subsection Literals
 7357: @cindex Literals
 7358: 
 7359: The simplest and most frequent example is to compute a literal during
 7360: compilation.  E.g., the following definition prints an array of strings,
 7361: one string per line:
 7362: 
 7363: @example
 7364: : .strings ( addr u -- ) \ gforth
 7365:     2* cells bounds U+DO
 7366: 	cr i 2@@ type
 7367:     2 cells +LOOP ;  
 7368: @end example
 7369: 
 7370: With a simple-minded compiler like Gforth's, this computes @code{2
 7371: cells} on every loop iteration.  You can compute this value once and for
 7372: all at compile time and compile it into the definition like this:
 7373: 
 7374: @example
 7375: : .strings ( addr u -- ) \ gforth
 7376:     2* cells bounds U+DO
 7377: 	cr i 2@@ type
 7378:     [ 2 cells ] literal +LOOP ;  
 7379: @end example
 7380: 
 7381: @code{[} switches the text interpreter to interpret state (you will get
 7382: an @code{ok} prompt if you type this example interactively and insert a
 7383: newline between @code{[} and @code{]}), so it performs the
 7384: interpretation semantics of @code{2 cells}; this computes a number.
 7385: @code{]} switches the text interpreter back into compile state.  It then
 7386: performs @code{Literal}'s compilation semantics, which are to compile
 7387: this number into the current word.  You can decompile the word with
 7388: @code{see .strings} to see the effect on the compiled code.
 7389: 
 7390: You can also optimize the @code{2* cells} into @code{[ 2 cells ] literal
 7391: *} in this way.
 7392: 
 7393: doc-[
 7394: doc-]
 7395: doc-literal
 7396: doc-]L
 7397: 
 7398: There are also words for compiling other data types than single cells as
 7399: literals:
 7400: 
 7401: doc-2literal
 7402: doc-fliteral
 7403: doc-sliteral
 7404: 
 7405: @cindex colon-sys, passing data across @code{:}
 7406: @cindex @code{:}, passing data across
 7407: You might be tempted to pass data from outside a colon definition to the
 7408: inside on the data stack.  This does not work, because @code{:} puhes a
 7409: colon-sys, making stuff below unaccessible.  E.g., this does not work:
 7410: 
 7411: @example
 7412: 5 : foo literal ; \ error: "unstructured"
 7413: @end example
 7414: 
 7415: Instead, you have to pass the value in some other way, e.g., through a
 7416: variable:
 7417: 
 7418: @example
 7419: variable temp
 7420: 5 temp !
 7421: : foo [ temp @@ ] literal ;
 7422: @end example
 7423: 
 7424: 
 7425: @node Macros,  , Literals, Compiling words
 7426: @subsection Macros
 7427: @cindex Macros
 7428: @cindex compiling compilation semantics
 7429: 
 7430: @code{Literal} and friends compile data values into the current
 7431: definition.  You can also write words that compile other words into the
 7432: current definition.  E.g.,
 7433: 
 7434: @example
 7435: : compile-+ ( -- ) \ compiled code: ( n1 n2 -- n )
 7436:   POSTPONE + ;
 7437: 
 7438: : foo ( n1 n2 -- n )
 7439:   [ compile-+ ] ;
 7440: 1 2 foo .
 7441: @end example
 7442: 
 7443: This is equivalent to @code{: foo + ;} (@code{see foo} to check this).
 7444: What happens in this example?  @code{Postpone} compiles the compilation
 7445: semantics of @code{+} into @code{compile-+}; later the text interpreter
 7446: executes @code{compile-+} and thus the compilation semantics of +, which
 7447: compile (the execution semantics of) @code{+} into
 7448: @code{foo}.@footnote{A recent RFI answer requires that compiling words
 7449: should only be executed in compile state, so this example is not
 7450: guaranteed to work on all standard systems, but on any decent system it
 7451: will work.}
 7452: 
 7453: doc-postpone
 7454: 
 7455: Compiling words like @code{compile-+} are usually immediate (or similar)
 7456: so you do not have to switch to interpret state to execute them;
 7457: modifying the last example accordingly produces:
 7458: 
 7459: @example
 7460: : [compile-+] ( compilation: --; interpretation: -- )
 7461:   \ compiled code: ( n1 n2 -- n )
 7462:   POSTPONE + ; immediate
 7463: 
 7464: : foo ( n1 n2 -- n )
 7465:   [compile-+] ;
 7466: 1 2 foo .
 7467: @end example
 7468: 
 7469: You will occassionally find the need to POSTPONE several words;
 7470: putting POSTPONE before each such word is cumbersome, so Gforth
 7471: provides a more convenient syntax: @code{]] ... [[}.  This
 7472: allows us to write @code{[compile-+]} as:
 7473: 
 7474: @example
 7475: : [compile-+] ( compilation: --; interpretation: -- )
 7476:   ]] + [[ ; immediate
 7477: @end example
 7478: 
 7479: doc-]]
 7480: doc-[[
 7481: 
 7482: The unusual direction of the brackets indicates their function:
 7483: @code{]]} switches from compilation to postponing (i.e., compilation
 7484: of compilation), just like @code{]} switches from immediate execution
 7485: (interpretation) to compilation.  Conversely, @code{[[} switches from
 7486: postponing to compilation, ananlogous to @code{[} which switches from
 7487: compilation to immediate execution.
 7488: 
 7489: The real advantage of @code{]] }...@code{ [[} becomes apparent when
 7490: there are many words to POSTPONE.  E.g., the word
 7491: @code{compile-map-array} (@pxref{Advanced macros Tutorial}) can be
 7492: written much shorter as follows:
 7493: 
 7494: @example
 7495: : compile-map-array ( compilation: xt -- ; run-time: ... addr u -- ... )
 7496: \ at run-time, execute xt ( ... x -- ... ) for each element of the
 7497: \ array beginning at addr and containing u elements
 7498:   @{ xt @}
 7499:   ]] cells over + swap ?do
 7500:     i @@ [[ xt compile, 
 7501:   1 cells ]]L +loop [[ ;
 7502: @end example
 7503: 
 7504: This example also uses @code{]]L} as a shortcut for @code{]] literal}.
 7505: There are also other shortcuts
 7506: 
 7507: doc-]]L
 7508: doc-]]2L
 7509: doc-]]FL
 7510: doc-]]SL
 7511: 
 7512: Note that parsing words don't parse at postpone time; if you want to
 7513: provide the parsed string right away, you have to switch back to
 7514: compilation:
 7515: 
 7516: @example
 7517: ]] ... [[ s" some string" ]]2L ... [[
 7518: ]] ... [[ ['] + ]]L ... [[
 7519: @end example
 7520: 
 7521: Definitions of @code{]]} and friends in ANS Forth are provided in
 7522: @file{compat/macros.fs}.
 7523: 
 7524: Immediate compiling words are similar to macros in other languages (in
 7525: particular, Lisp).  The important differences to macros in, e.g., C are:
 7526: 
 7527: @itemize @bullet
 7528: 
 7529: @item
 7530: You use the same language for defining and processing macros, not a
 7531: separate preprocessing language and processor.
 7532: 
 7533: @item
 7534: Consequently, the full power of Forth is available in macro definitions.
 7535: E.g., you can perform arbitrarily complex computations, or generate
 7536: different code conditionally or in a loop (e.g., @pxref{Advanced macros
 7537: Tutorial}).  This power is very useful when writing a parser generators
 7538: or other code-generating software.
 7539: 
 7540: @item
 7541: Macros defined using @code{postpone} etc. deal with the language at a
 7542: higher level than strings; name binding happens at macro definition
 7543: time, so you can avoid the pitfalls of name collisions that can happen
 7544: in C macros.  Of course, Forth is a liberal language and also allows to
 7545: shoot yourself in the foot with text-interpreted macros like
 7546: 
 7547: @example
 7548: : [compile-+] s" +" evaluate ; immediate
 7549: @end example
 7550: 
 7551: Apart from binding the name at macro use time, using @code{evaluate}
 7552: also makes your definition @code{state}-smart (@pxref{state-smartness}).
 7553: @end itemize
 7554: 
 7555: You may want the macro to compile a number into a word.  The word to do
 7556: it is @code{literal}, but you have to @code{postpone} it, so its
 7557: compilation semantics take effect when the macro is executed, not when
 7558: it is compiled:
 7559: 
 7560: @example
 7561: : [compile-5] ( -- ) \ compiled code: ( -- n )
 7562:   5 POSTPONE literal ; immediate
 7563: 
 7564: : foo [compile-5] ;
 7565: foo .
 7566: @end example
 7567: 
 7568: You may want to pass parameters to a macro, that the macro should
 7569: compile into the current definition.  If the parameter is a number, then
 7570: you can use @code{postpone literal} (similar for other values).
 7571: 
 7572: If you want to pass a word that is to be compiled, the usual way is to
 7573: pass an execution token and @code{compile,} it:
 7574: 
 7575: @example
 7576: : twice1 ( xt -- ) \ compiled code: ... -- ...
 7577:   dup compile, compile, ;
 7578: 
 7579: : 2+ ( n1 -- n2 )
 7580:   [ ' 1+ twice1 ] ;
 7581: @end example
 7582: 
 7583: doc-compile,
 7584: 
 7585: An alternative available in Gforth, that allows you to pass compile-only
 7586: words as parameters is to use the compilation token (@pxref{Compilation
 7587: token}).  The same example in this technique:
 7588: 
 7589: @example
 7590: : twice ( ... ct -- ... ) \ compiled code: ... -- ...
 7591:   2dup 2>r execute 2r> execute ;
 7592: 
 7593: : 2+ ( n1 -- n2 )
 7594:   [ comp' 1+ twice ] ;
 7595: @end example
 7596: 
 7597: In the example above @code{2>r} and @code{2r>} ensure that @code{twice}
 7598: works even if the executed compilation semantics has an effect on the
 7599: data stack.
 7600: 
 7601: You can also define complete definitions with these words; this provides
 7602: an alternative to using @code{does>} (@pxref{User-defined Defining
 7603: Words}).  E.g., instead of
 7604: 
 7605: @example
 7606: : curry+ ( n1 "name" -- )
 7607:     CREATE ,
 7608: DOES> ( n2 -- n1+n2 )
 7609:     @@ + ;
 7610: @end example
 7611: 
 7612: you could define
 7613: 
 7614: @example
 7615: : curry+ ( n1 "name" -- )
 7616:   \ name execution: ( n2 -- n1+n2 )
 7617:   >r : r> POSTPONE literal POSTPONE + POSTPONE ; ;
 7618: 
 7619: -3 curry+ 3-
 7620: see 3-
 7621: @end example
 7622: 
 7623: The sequence @code{>r : r>} is necessary, because @code{:} puts a
 7624: colon-sys on the data stack that makes everything below it unaccessible.
 7625: 
 7626: This way of writing defining words is sometimes more, sometimes less
 7627: convenient than using @code{does>} (@pxref{Advanced does> usage
 7628: example}).  One advantage of this method is that it can be optimized
 7629: better, because the compiler knows that the value compiled with
 7630: @code{literal} is fixed, whereas the data associated with a
 7631: @code{create}d word can be changed.
 7632: 
 7633: @c doc-[compile] !! not properly documented
 7634: 
 7635: @c ----------------------------------------------------------
 7636: @node The Text Interpreter, The Input Stream, Compiling words, Words
 7637: @section  The Text Interpreter
 7638: @cindex interpreter - outer
 7639: @cindex text interpreter
 7640: @cindex outer interpreter
 7641: 
 7642: @c Should we really describe all these ugly details?  IMO the text
 7643: @c interpreter should be much cleaner, but that may not be possible within
 7644: @c ANS Forth. - anton
 7645: @c nac-> I wanted to explain how it works to show how you can exploit
 7646: @c it in your own programs. When I was writing a cross-compiler, figuring out
 7647: @c some of these gory details was very helpful to me. None of the textbooks
 7648: @c I've seen cover it, and the most modern Forth textbook -- Forth Inc's,
 7649: @c seems to positively avoid going into too much detail for some of
 7650: @c the internals.
 7651: 
 7652: @c anton: ok.  I wonder, though, if this is the right place; for some stuff
 7653: @c it is; for the ugly details, I would prefer another place.  I wonder
 7654: @c whether we should have a chapter before "Words" that describes some
 7655: @c basic concepts referred to in words, and a chapter after "Words" that
 7656: @c describes implementation details.
 7657: 
 7658: The text interpreter@footnote{This is an expanded version of the
 7659: material in @ref{Introducing the Text Interpreter}.} is an endless loop
 7660: that processes input from the current input device. It is also called
 7661: the outer interpreter, in contrast to the inner interpreter
 7662: (@pxref{Engine}) which executes the compiled Forth code on interpretive
 7663: implementations.
 7664: 
 7665: @cindex interpret state
 7666: @cindex compile state
 7667: The text interpreter operates in one of two states: @dfn{interpret
 7668: state} and @dfn{compile state}. The current state is defined by the
 7669: aptly-named variable @code{state}.
 7670: 
 7671: This section starts by describing how the text interpreter behaves when
 7672: it is in interpret state, processing input from the user input device --
 7673: the keyboard. This is the mode that a Forth system is in after it starts
 7674: up.
 7675: 
 7676: @cindex input buffer
 7677: @cindex terminal input buffer
 7678: The text interpreter works from an area of memory called the @dfn{input
 7679: buffer}@footnote{When the text interpreter is processing input from the
 7680: keyboard, this area of memory is called the @dfn{terminal input buffer}
 7681: (TIB) and is addressed by the (obsolescent) words @code{TIB} and
 7682: @code{#TIB}.}, which stores your keyboard input when you press the
 7683: @key{RET} key. Starting at the beginning of the input buffer, it skips
 7684: leading spaces (called @dfn{delimiters}) then parses a string (a
 7685: sequence of non-space characters) until it reaches either a space
 7686: character or the end of the buffer. Having parsed a string, it makes two
 7687: attempts to process it:
 7688: 
 7689: @cindex dictionary
 7690: @itemize @bullet
 7691: @item
 7692: It looks for the string in a @dfn{dictionary} of definitions. If the
 7693: string is found, the string names a @dfn{definition} (also known as a
 7694: @dfn{word}) and the dictionary search returns information that allows
 7695: the text interpreter to perform the word's @dfn{interpretation
 7696: semantics}. In most cases, this simply means that the word will be
 7697: executed.
 7698: @item
 7699: If the string is not found in the dictionary, the text interpreter
 7700: attempts to treat it as a number, using the rules described in
 7701: @ref{Number Conversion}. If the string represents a legal number in the
 7702: current radix, the number is pushed onto a parameter stack (the data
 7703: stack for integers, the floating-point stack for floating-point
 7704: numbers).
 7705: @end itemize
 7706: 
 7707: If both attempts fail, or if the word is found in the dictionary but has
 7708: no interpretation semantics@footnote{This happens if the word was
 7709: defined as @code{COMPILE-ONLY}.} the text interpreter discards the
 7710: remainder of the input buffer, issues an error message and waits for
 7711: more input. If one of the attempts succeeds, the text interpreter
 7712: repeats the parsing process until the whole of the input buffer has been
 7713: processed, at which point it prints the status message ``@code{ ok}''
 7714: and waits for more input.
 7715: 
 7716: @c anton: this should be in the input stream subsection (or below it)
 7717: 
 7718: @cindex parse area
 7719: The text interpreter keeps track of its position in the input buffer by
 7720: updating a variable called @code{>IN} (pronounced ``to-in''). The value
 7721: of @code{>IN} starts out as 0, indicating an offset of 0 from the start
 7722: of the input buffer. The region from offset @code{>IN @@} to the end of
 7723: the input buffer is called the @dfn{parse area}@footnote{In other words,
 7724: the text interpreter processes the contents of the input buffer by
 7725: parsing strings from the parse area until the parse area is empty.}.
 7726: This example shows how @code{>IN} changes as the text interpreter parses
 7727: the input buffer:
 7728: 
 7729: @example
 7730: : remaining >IN @@ SOURCE 2 PICK - -ROT + SWAP
 7731:   CR ." ->" TYPE ." <-" ; IMMEDIATE 
 7732: 
 7733: 1 2 3 remaining + remaining . 
 7734: 
 7735: : foo 1 2 3 remaining SWAP remaining ;
 7736: @end example
 7737: 
 7738: @noindent
 7739: The result is:
 7740: 
 7741: @example
 7742: ->+ remaining .<-
 7743: ->.<-5  ok
 7744: 
 7745: ->SWAP remaining ;-<
 7746: ->;<-  ok
 7747: @end example
 7748: 
 7749: @cindex parsing words
 7750: The value of @code{>IN} can also be modified by a word in the input
 7751: buffer that is executed by the text interpreter.  This means that a word
 7752: can ``trick'' the text interpreter into either skipping a section of the
 7753: input buffer@footnote{This is how parsing words work.} or into parsing a
 7754: section twice. For example:
 7755: 
 7756: @example
 7757: : lat ." <<foo>>" ;
 7758: : flat ." <<bar>>" >IN DUP @@ 3 - SWAP ! ;
 7759: @end example
 7760: 
 7761: @noindent
 7762: When @code{flat} is executed, this output is produced@footnote{Exercise
 7763: for the reader: what would happen if the @code{3} were replaced with
 7764: @code{4}?}:
 7765: 
 7766: @example
 7767: <<bar>><<foo>>
 7768: @end example
 7769: 
 7770: This technique can be used to work around some of the interoperability
 7771: problems of parsing words.  Of course, it's better to avoid parsing
 7772: words where possible.
 7773: 
 7774: @noindent
 7775: Two important notes about the behaviour of the text interpreter:
 7776: 
 7777: @itemize @bullet
 7778: @item
 7779: It processes each input string to completion before parsing additional
 7780: characters from the input buffer.
 7781: @item
 7782: It treats the input buffer as a read-only region (and so must your code).
 7783: @end itemize
 7784: 
 7785: @noindent
 7786: When the text interpreter is in compile state, its behaviour changes in
 7787: these ways:
 7788: 
 7789: @itemize @bullet
 7790: @item
 7791: If a parsed string is found in the dictionary, the text interpreter will
 7792: perform the word's @dfn{compilation semantics}. In most cases, this
 7793: simply means that the execution semantics of the word will be appended
 7794: to the current definition.
 7795: @item
 7796: When a number is encountered, it is compiled into the current definition
 7797: (as a literal) rather than being pushed onto a parameter stack.
 7798: @item
 7799: If an error occurs, @code{state} is modified to put the text interpreter
 7800: back into interpret state.
 7801: @item
 7802: Each time a line is entered from the keyboard, Gforth prints
 7803: ``@code{ compiled}'' rather than `` @code{ok}''.
 7804: @end itemize
 7805: 
 7806: @cindex text interpreter - input sources
 7807: When the text interpreter is using an input device other than the
 7808: keyboard, its behaviour changes in these ways:
 7809: 
 7810: @itemize @bullet
 7811: @item
 7812: When the parse area is empty, the text interpreter attempts to refill
 7813: the input buffer from the input source. When the input source is
 7814: exhausted, the input source is set back to the previous input source.
 7815: @item
 7816: It doesn't print out ``@code{ ok}'' or ``@code{ compiled}'' messages each
 7817: time the parse area is emptied.
 7818: @item
 7819: If an error occurs, the input source is set back to the user input
 7820: device.
 7821: @end itemize
 7822: 
 7823: You can read about this in more detail in @ref{Input Sources}.
 7824: 
 7825: doc->in
 7826: doc-source
 7827: 
 7828: doc-tib
 7829: doc-#tib
 7830: 
 7831: 
 7832: @menu
 7833: * Input Sources::               
 7834: * Number Conversion::           
 7835: * Interpret/Compile states::    
 7836: * Interpreter Directives::      
 7837: @end menu
 7838: 
 7839: @node Input Sources, Number Conversion, The Text Interpreter, The Text Interpreter
 7840: @subsection Input Sources
 7841: @cindex input sources
 7842: @cindex text interpreter - input sources
 7843: 
 7844: By default, the text interpreter processes input from the user input
 7845: device (the keyboard) when Forth starts up. The text interpreter can
 7846: process input from any of these sources:
 7847: 
 7848: @itemize @bullet
 7849: @item
 7850: The user input device -- the keyboard.
 7851: @item
 7852: A file, using the words described in @ref{Forth source files}.
 7853: @item
 7854: A block, using the words described in @ref{Blocks}.
 7855: @item
 7856: A text string, using @code{evaluate}.
 7857: @end itemize
 7858: 
 7859: A program can identify the current input device from the values of
 7860: @code{source-id} and @code{blk}.
 7861: 
 7862: 
 7863: doc-source-id
 7864: doc-blk
 7865: 
 7866: doc-save-input
 7867: doc-restore-input
 7868: 
 7869: doc-evaluate
 7870: doc-query
 7871: 
 7872: 
 7873: 
 7874: @node Number Conversion, Interpret/Compile states, Input Sources, The Text Interpreter
 7875: @subsection Number Conversion
 7876: @cindex number conversion
 7877: @cindex double-cell numbers, input format
 7878: @cindex input format for double-cell numbers
 7879: @cindex single-cell numbers, input format
 7880: @cindex input format for single-cell numbers
 7881: @cindex floating-point numbers, input format
 7882: @cindex input format for floating-point numbers
 7883: 
 7884: This section describes the rules that the text interpreter uses when it
 7885: tries to convert a string into a number.
 7886: 
 7887: Let <digit> represent any character that is a legal digit in the current
 7888: number base@footnote{For example, 0-9 when the number base is decimal or
 7889: 0-9, A-F when the number base is hexadecimal.}.
 7890: 
 7891: Let <decimal digit> represent any character in the range 0-9.
 7892: 
 7893: Let @{@i{a b}@} represent the @i{optional} presence of any of the characters
 7894: in the braces (@i{a} or @i{b} or neither).
 7895: 
 7896: Let * represent any number of instances of the previous character
 7897: (including none).
 7898: 
 7899: Let any other character represent itself.
 7900: 
 7901: @noindent
 7902: Now, the conversion rules are:
 7903: 
 7904: @itemize @bullet
 7905: @item
 7906: A string of the form <digit><digit>* is treated as a single-precision
 7907: (cell-sized) positive integer. Examples are 0 123 6784532 32343212343456 42
 7908: @item
 7909: A string of the form -<digit><digit>* is treated as a single-precision
 7910: (cell-sized) negative integer, and is represented using 2's-complement
 7911: arithmetic. Examples are -45 -5681 -0
 7912: @item
 7913: A string of the form <digit><digit>*.<digit>* is treated as a double-precision
 7914: (double-cell-sized) positive integer. Examples are 3465. 3.465 34.65
 7915: (all three of these represent the same number).
 7916: @item
 7917: A string of the form -<digit><digit>*.<digit>* is treated as a
 7918: double-precision (double-cell-sized) negative integer, and is
 7919: represented using 2's-complement arithmetic. Examples are -3465. -3.465
 7920: -34.65 (all three of these represent the same number).
 7921: @item
 7922: A string of the form @{+ -@}<decimal digit>@{.@}<decimal digit>*@{e
 7923: E@}@{+ -@}<decimal digit><decimal digit>* is treated as a floating-point
 7924: number. Examples are 1e 1e0 1.e 1.e0 +1e+0 (which all represent the same
 7925: number) +12.E-4
 7926: @end itemize
 7927: 
 7928: By default, the number base used for integer number conversion is
 7929: given by the contents of the variable @code{base}.  Note that a lot of
 7930: confusion can result from unexpected values of @code{base}.  If you
 7931: change @code{base} anywhere, make sure to save the old value and
 7932: restore it afterwards; better yet, use @code{base-execute}, which does
 7933: this for you.  In general I recommend keeping @code{base} decimal, and
 7934: using the prefixes described below for the popular non-decimal bases.
 7935: 
 7936: doc-dpl
 7937: doc-base-execute
 7938: doc-base
 7939: doc-hex
 7940: doc-decimal
 7941: 
 7942: @cindex '-prefix for character strings
 7943: @cindex &-prefix for decimal numbers
 7944: @cindex #-prefix for decimal numbers
 7945: @cindex %-prefix for binary numbers
 7946: @cindex $-prefix for hexadecimal numbers
 7947: @cindex 0x-prefix for hexadecimal numbers
 7948: Gforth allows you to override the value of @code{base} by using a
 7949: prefix@footnote{Some Forth implementations provide a similar scheme by
 7950: implementing @code{$} etc. as parsing words that process the subsequent
 7951: number in the input stream and push it onto the stack. For example, see
 7952: @cite{Number Conversion and Literals}, by Wil Baden; Forth Dimensions
 7953: 20(3) pages 26--27. In such implementations, unlike in Gforth, a space
 7954: is required between the prefix and the number.} before the first digit
 7955: of an (integer) number. The following prefixes are supported:
 7956: 
 7957: @itemize @bullet
 7958: @item
 7959: @code{&} -- decimal
 7960: @item
 7961: @code{#} -- decimal
 7962: @item
 7963: @code{%} -- binary
 7964: @item
 7965: @code{$} -- hexadecimal
 7966: @item
 7967: @code{0x} -- hexadecimal, if base<33.
 7968: @item
 7969: @code{'} -- numeric value (e.g., ASCII code) of next character; an
 7970: optional @code{'} may be present after the character.
 7971: @end itemize
 7972: 
 7973: Here are some examples, with the equivalent decimal number shown after
 7974: in braces:
 7975: 
 7976: -$41 (-65), %1001101 (205), %1001.0001 (145 - a double-precision number),
 7977: 'A (65),
 7978: -'a' (-97),
 7979: &905 (905), $abc (2478), $ABC (2478).
 7980: 
 7981: @cindex number conversion - traps for the unwary
 7982: @noindent
 7983: Number conversion has a number of traps for the unwary:
 7984: 
 7985: @itemize @bullet
 7986: @item
 7987: You cannot determine the current number base using the code sequence
 7988: @code{base @@ .} -- the number base is always 10 in the current number
 7989: base. Instead, use something like @code{base @@ dec.}
 7990: @item
 7991: If the number base is set to a value greater than 14 (for example,
 7992: hexadecimal), the number 123E4 is ambiguous; the conversion rules allow
 7993: it to be intepreted as either a single-precision integer or a
 7994: floating-point number (Gforth treats it as an integer). The ambiguity
 7995: can be resolved by explicitly stating the sign of the mantissa and/or
 7996: exponent: 123E+4 or +123E4 -- if the number base is decimal, no
 7997: ambiguity arises; either representation will be treated as a
 7998: floating-point number.
 7999: @item
 8000: There is a word @code{bin} but it does @i{not} set the number base!
 8001: It is used to specify file types.
 8002: @item
 8003: ANS Forth requires the @code{.} of a double-precision number to be the
 8004: final character in the string.  Gforth allows the @code{.} to be
 8005: anywhere after the first digit.
 8006: @item
 8007: The number conversion process does not check for overflow.
 8008: @item
 8009: In an ANS Forth program @code{base} is required to be decimal when
 8010: converting floating-point numbers.  In Gforth, number conversion to
 8011: floating-point numbers always uses base &10, irrespective of the value
 8012: of @code{base}.
 8013: @end itemize
 8014: 
 8015: You can read numbers into your programs with the words described in
 8016: @ref{Line input and conversion}.
 8017: 
 8018: @node Interpret/Compile states, Interpreter Directives, Number Conversion, The Text Interpreter
 8019: @subsection Interpret/Compile states
 8020: @cindex Interpret/Compile states
 8021: 
 8022: A standard program is not permitted to change @code{state}
 8023: explicitly. However, it can change @code{state} implicitly, using the
 8024: words @code{[} and @code{]}. When @code{[} is executed it switches
 8025: @code{state} to interpret state, and therefore the text interpreter
 8026: starts interpreting. When @code{]} is executed it switches @code{state}
 8027: to compile state and therefore the text interpreter starts
 8028: compiling. The most common usage for these words is for switching into
 8029: interpret state and back from within a colon definition; this technique
 8030: can be used to compile a literal (for an example, @pxref{Literals}) or
 8031: for conditional compilation (for an example, @pxref{Interpreter
 8032: Directives}).
 8033: 
 8034: 
 8035: @c This is a bad example: It's non-standard, and it's not necessary.
 8036: @c However, I can't think of a good example for switching into compile
 8037: @c state when there is no current word (@code{state}-smart words are not a
 8038: @c good reason).  So maybe we should use an example for switching into
 8039: @c interpret @code{state} in a colon def. - anton
 8040: @c nac-> I agree. I started out by putting in the example, then realised
 8041: @c that it was non-ANS, so wrote more words around it. I hope this
 8042: @c re-written version is acceptable to you. I do want to keep the example
 8043: @c as it is helpful for showing what is and what is not portable, particularly
 8044: @c where it outlaws a style in common use.
 8045: 
 8046: @c anton: it's more important to show what's portable.  After we have done
 8047: @c that, we can also show what's not.  In any case, I have written a
 8048: @c section Compiling Words which also deals with [ ].
 8049: 
 8050: @c  !! The following example does not work in Gforth 0.5.9 or later.
 8051: 
 8052: @c  @code{[} and @code{]} also give you the ability to switch into compile
 8053: @c  state and back, but we cannot think of any useful Standard application
 8054: @c  for this ability. Pre-ANS Forth textbooks have examples like this:
 8055: 
 8056: @c  @example
 8057: @c  : AA ." this is A" ;
 8058: @c  : BB ." this is B" ;
 8059: @c  : CC ." this is C" ;
 8060: 
 8061: @c  create table ] aa bb cc [
 8062: 
 8063: @c  : go ( n -- ) \ n is offset into table.. 0 for 1st entry
 8064: @c    cells table + @@ execute ;
 8065: @c  @end example
 8066: 
 8067: @c  This example builds a jump table; @code{0 go} will display ``@code{this
 8068: @c  is A}''. Using @code{[} and @code{]} in this example is equivalent to
 8069: @c  defining @code{table} like this:
 8070: 
 8071: @c  @example
 8072: @c  create table ' aa COMPILE, ' bb COMPILE, ' cc COMPILE,
 8073: @c  @end example
 8074: 
 8075: @c  The problem with this code is that the definition of @code{table} is not
 8076: @c  portable -- it @i{compile}s execution tokens into code space. Whilst it
 8077: @c  @i{may} work on systems where code space and data space co-incide, the
 8078: @c  Standard only allows data space to be assigned for a @code{CREATE}d
 8079: @c  word. In addition, the Standard only allows @code{@@} to access data
 8080: @c  space, whilst this example is using it to access code space. The only
 8081: @c  portable, Standard way to build this table is to build it in data space,
 8082: @c  like this:
 8083: 
 8084: @c  @example
 8085: @c  create table ' aa , ' bb , ' cc ,
 8086: @c  @end example
 8087: 
 8088: @c  doc-state
 8089: 
 8090: 
 8091: @node Interpreter Directives,  , Interpret/Compile states, The Text Interpreter
 8092: @subsection Interpreter Directives
 8093: @cindex interpreter directives
 8094: @cindex conditional compilation
 8095: 
 8096: These words are usually used in interpret state; typically to control
 8097: which parts of a source file are processed by the text
 8098: interpreter. There are only a few ANS Forth Standard words, but Gforth
 8099: supplements these with a rich set of immediate control structure words
 8100: to compensate for the fact that the non-immediate versions can only be
 8101: used in compile state (@pxref{Control Structures}). Typical usages:
 8102: 
 8103: @example
 8104: FALSE Constant HAVE-ASSEMBLER
 8105: .
 8106: .
 8107: HAVE-ASSEMBLER [IF]
 8108: : ASSEMBLER-FEATURE
 8109:   ...
 8110: ;
 8111: [ENDIF]
 8112: .
 8113: .
 8114: : SEE
 8115:   ... \ general-purpose SEE code
 8116:   [ HAVE-ASSEMBLER [IF] ]
 8117:   ... \ assembler-specific SEE code
 8118:   [ [ENDIF] ]
 8119: ;
 8120: @end example
 8121: 
 8122: 
 8123: doc-[IF]
 8124: doc-[ELSE]
 8125: doc-[THEN]
 8126: doc-[ENDIF]
 8127: 
 8128: doc-[IFDEF]
 8129: doc-[IFUNDEF]
 8130: 
 8131: doc-[?DO]
 8132: doc-[DO]
 8133: doc-[FOR]
 8134: doc-[LOOP]
 8135: doc-[+LOOP]
 8136: doc-[NEXT]
 8137: 
 8138: doc-[BEGIN]
 8139: doc-[UNTIL]
 8140: doc-[AGAIN]
 8141: doc-[WHILE]
 8142: doc-[REPEAT]
 8143: 
 8144: 
 8145: @c -------------------------------------------------------------
 8146: @node The Input Stream, Word Lists, The Text Interpreter, Words
 8147: @section The Input Stream
 8148: @cindex input stream
 8149: 
 8150: @c !! integrate this better with the "Text Interpreter" section
 8151: The text interpreter reads from the input stream, which can come from
 8152: several sources (@pxref{Input Sources}).  Some words, in particular
 8153: defining words, but also words like @code{'}, read parameters from the
 8154: input stream instead of from the stack.
 8155: 
 8156: Such words are called parsing words, because they parse the input
 8157: stream.  Parsing words are hard to use in other words, because it is
 8158: hard to pass program-generated parameters through the input stream.
 8159: They also usually have an unintuitive combination of interpretation and
 8160: compilation semantics when implemented naively, leading to various
 8161: approaches that try to produce a more intuitive behaviour
 8162: (@pxref{Combined words}).
 8163: 
 8164: It should be obvious by now that parsing words are a bad idea.  If you
 8165: want to implement a parsing word for convenience, also provide a factor
 8166: of the word that does not parse, but takes the parameters on the stack.
 8167: To implement the parsing word on top if it, you can use the following
 8168: words:
 8169: 
 8170: @c anton: these belong in the input stream section
 8171: doc-parse
 8172: doc-parse-name
 8173: doc-parse-word
 8174: doc-name
 8175: doc-word
 8176: doc-refill
 8177: 
 8178: Conversely, if you have the bad luck (or lack of foresight) to have to
 8179: deal with parsing words without having such factors, how do you pass a
 8180: string that is not in the input stream to it?
 8181: 
 8182: doc-execute-parsing
 8183: 
 8184: A definition of this word in ANS Forth is provided in
 8185: @file{compat/execute-parsing.fs}.
 8186: 
 8187: If you want to run a parsing word on a file, the following word should
 8188: help:
 8189: 
 8190: doc-execute-parsing-file
 8191: 
 8192: @c -------------------------------------------------------------
 8193: @node Word Lists, Environmental Queries, The Input Stream, Words
 8194: @section Word Lists
 8195: @cindex word lists
 8196: @cindex header space
 8197: 
 8198: A wordlist is a list of named words; you can add new words and look up
 8199: words by name (and you can remove words in a restricted way with
 8200: markers).  Every named (and @code{reveal}ed) word is in one wordlist.
 8201: 
 8202: @cindex search order stack
 8203: The text interpreter searches the wordlists present in the search order
 8204: (a stack of wordlists), from the top to the bottom.  Within each
 8205: wordlist, the search starts conceptually at the newest word; i.e., if
 8206: two words in a wordlist have the same name, the newer word is found.
 8207: 
 8208: @cindex compilation word list
 8209: New words are added to the @dfn{compilation wordlist} (aka current
 8210: wordlist).
 8211: 
 8212: @cindex wid
 8213: A word list is identified by a cell-sized word list identifier (@i{wid})
 8214: in much the same way as a file is identified by a file handle. The
 8215: numerical value of the wid has no (portable) meaning, and might change
 8216: from session to session.
 8217: 
 8218: The ANS Forth ``Search order'' word set is intended to provide a set of
 8219: low-level tools that allow various different schemes to be
 8220: implemented. Gforth also provides @code{vocabulary}, a traditional Forth
 8221: word.  @file{compat/vocabulary.fs} provides an implementation in ANS
 8222: Forth.
 8223: 
 8224: @comment TODO: locals section refers to here, saying that every word list (aka
 8225: @comment vocabulary) has its own methods for searching etc. Need to document that.
 8226: @c anton: but better in a separate subsection on wordlist internals
 8227: 
 8228: @comment TODO: document markers, reveal, tables, mappedwordlist
 8229: 
 8230: @comment the gforthman- prefix is used to pick out the true definition of a
 8231: @comment word from the source files, rather than some alias.
 8232: 
 8233: doc-forth-wordlist
 8234: doc-definitions
 8235: doc-get-current
 8236: doc-set-current
 8237: doc-get-order
 8238: doc-set-order
 8239: doc-wordlist
 8240: doc-table
 8241: doc->order
 8242: doc-previous
 8243: doc-also
 8244: doc-forth
 8245: doc-only
 8246: doc-order
 8247: 
 8248: doc-find
 8249: doc-search-wordlist
 8250: 
 8251: doc-words
 8252: doc-vlist
 8253: @c doc-words-deferred
 8254: 
 8255: @c doc-mappedwordlist @c map-structure undefined, implemantation-specific
 8256: doc-root
 8257: doc-vocabulary
 8258: doc-seal
 8259: doc-vocs
 8260: doc-current
 8261: doc-context
 8262: 
 8263: 
 8264: @menu
 8265: * Vocabularies::                
 8266: * Why use word lists?::         
 8267: * Word list example::           
 8268: @end menu
 8269: 
 8270: @node Vocabularies, Why use word lists?, Word Lists, Word Lists
 8271: @subsection Vocabularies
 8272: @cindex Vocabularies, detailed explanation
 8273: 
 8274: Here is an example of creating and using a new wordlist using ANS
 8275: Forth words:
 8276: 
 8277: @example
 8278: wordlist constant my-new-words-wordlist
 8279: : my-new-words get-order nip my-new-words-wordlist swap set-order ;
 8280: 
 8281: \ add it to the search order
 8282: also my-new-words
 8283: 
 8284: \ alternatively, add it to the search order and make it
 8285: \ the compilation word list
 8286: also my-new-words definitions
 8287: \ type "order" to see the problem
 8288: @end example
 8289: 
 8290: The problem with this example is that @code{order} has no way to
 8291: associate the name @code{my-new-words} with the wid of the word list (in
 8292: Gforth, @code{order} and @code{vocs} will display @code{???}  for a wid
 8293: that has no associated name). There is no Standard way of associating a
 8294: name with a wid.
 8295: 
 8296: In Gforth, this example can be re-coded using @code{vocabulary}, which
 8297: associates a name with a wid:
 8298: 
 8299: @example
 8300: vocabulary my-new-words
 8301: 
 8302: \ add it to the search order
 8303: also my-new-words
 8304: 
 8305: \ alternatively, add it to the search order and make it
 8306: \ the compilation word list
 8307: my-new-words definitions
 8308: \ type "order" to see that the problem is solved
 8309: @end example
 8310: 
 8311: 
 8312: @node Why use word lists?, Word list example, Vocabularies, Word Lists
 8313: @subsection Why use word lists?
 8314: @cindex word lists - why use them?
 8315: 
 8316: Here are some reasons why people use wordlists:
 8317: 
 8318: @itemize @bullet
 8319: 
 8320: @c anton: Gforth's hashing implementation makes the search speed
 8321: @c independent from the number of words.  But it is linear with the number
 8322: @c of wordlists that have to be searched, so in effect using more wordlists
 8323: @c actually slows down compilation.
 8324: 
 8325: @c @item
 8326: @c To improve compilation speed by reducing the number of header space
 8327: @c entries that must be searched. This is achieved by creating a new
 8328: @c word list that contains all of the definitions that are used in the
 8329: @c definition of a Forth system but which would not usually be used by
 8330: @c programs running on that system. That word list would be on the search
 8331: @c list when the Forth system was compiled but would be removed from the
 8332: @c search list for normal operation. This can be a useful technique for
 8333: @c low-performance systems (for example, 8-bit processors in embedded
 8334: @c systems) but is unlikely to be necessary in high-performance desktop
 8335: @c systems.
 8336: 
 8337: @item
 8338: To prevent a set of words from being used outside the context in which
 8339: they are valid. Two classic examples of this are an integrated editor
 8340: (all of the edit commands are defined in a separate word list; the
 8341: search order is set to the editor word list when the editor is invoked;
 8342: the old search order is restored when the editor is terminated) and an
 8343: integrated assembler (the op-codes for the machine are defined in a
 8344: separate word list which is used when a @code{CODE} word is defined).
 8345: 
 8346: @item
 8347: To organize the words of an application or library into a user-visible
 8348: set (in @code{forth-wordlist} or some other common wordlist) and a set
 8349: of helper words used just for the implementation (hidden in a separate
 8350: wordlist).  This keeps @code{words}' output smaller, separates
 8351: implementation and interface, and reduces the chance of name conflicts
 8352: within the common wordlist.
 8353: 
 8354: @item
 8355: To prevent a name-space clash between multiple definitions with the same
 8356: name. For example, when building a cross-compiler you might have a word
 8357: @code{IF} that generates conditional code for your target system. By
 8358: placing this definition in a different word list you can control whether
 8359: the host system's @code{IF} or the target system's @code{IF} get used in
 8360: any particular context by controlling the order of the word lists on the
 8361: search order stack.
 8362: 
 8363: @end itemize
 8364: 
 8365: The downsides of using wordlists are:
 8366: 
 8367: @itemize
 8368: 
 8369: @item
 8370: Debugging becomes more cumbersome.
 8371: 
 8372: @item
 8373: Name conflicts worked around with wordlists are still there, and you
 8374: have to arrange the search order carefully to get the desired results;
 8375: if you forget to do that, you get hard-to-find errors (as in any case
 8376: where you read the code differently from the compiler; @code{see} can
 8377: help seeing which of several possible words the name resolves to in such
 8378: cases).  @code{See} displays just the name of the words, not what
 8379: wordlist they belong to, so it might be misleading.  Using unique names
 8380: is a better approach to avoid name conflicts.
 8381: 
 8382: @item
 8383: You have to explicitly undo any changes to the search order.  In many
 8384: cases it would be more convenient if this happened implicitly.  Gforth
 8385: currently does not provide such a feature, but it may do so in the
 8386: future.
 8387: @end itemize
 8388: 
 8389: 
 8390: @node Word list example,  , Why use word lists?, Word Lists
 8391: @subsection Word list example
 8392: @cindex word lists - example
 8393: 
 8394: The following example is from the
 8395: @uref{http://www.complang.tuwien.ac.at/forth/garbage-collection.zip,
 8396: garbage collector} and uses wordlists to separate public words from
 8397: helper words:
 8398: 
 8399: @example
 8400: get-current ( wid )
 8401: vocabulary garbage-collector also garbage-collector definitions
 8402: ... \ define helper words
 8403: ( wid ) set-current \ restore original (i.e., public) compilation wordlist
 8404: ... \ define the public (i.e., API) words
 8405:     \ they can refer to the helper words
 8406: previous \ restore original search order (helper words become invisible)
 8407: @end example
 8408: 
 8409: @c -------------------------------------------------------------
 8410: @node Environmental Queries, Files, Word Lists, Words
 8411: @section Environmental Queries
 8412: @cindex environmental queries
 8413: 
 8414: ANS Forth introduced the idea of ``environmental queries'' as a way
 8415: for a program running on a system to determine certain characteristics of the system.
 8416: The Standard specifies a number of strings that might be recognised by a system.
 8417: 
 8418: The Standard requires that the header space used for environmental queries
 8419: be distinct from the header space used for definitions.
 8420: 
 8421: Typically, environmental queries are supported by creating a set of
 8422: definitions in a word list that is @i{only} used during environmental
 8423: queries; that is what Gforth does. There is no Standard way of adding
 8424: definitions to the set of recognised environmental queries, but any
 8425: implementation that supports the loading of optional word sets must have
 8426: some mechanism for doing this (after loading the word set, the
 8427: associated environmental query string must return @code{true}). In
 8428: Gforth, the word list used to honour environmental queries can be
 8429: manipulated just like any other word list.
 8430: 
 8431: 
 8432: doc-environment?
 8433: doc-environment-wordlist
 8434: 
 8435: doc-gforth
 8436: doc-os-class
 8437: 
 8438: 
 8439: Note that, whilst the documentation for (e.g.) @code{gforth} shows it
 8440: returning two items on the stack, querying it using @code{environment?}
 8441: will return an additional item; the @code{true} flag that shows that the
 8442: string was recognised.
 8443: 
 8444: @comment TODO Document the standard strings or note where they are documented herein
 8445: 
 8446: Here are some examples of using environmental queries:
 8447: 
 8448: @example
 8449: s" address-unit-bits" environment? 0=
 8450: [IF]
 8451:      cr .( environmental attribute address-units-bits unknown... ) cr
 8452: [ELSE]
 8453:      drop \ ensure balanced stack effect
 8454: [THEN]
 8455: 
 8456: \ this might occur in the prelude of a standard program that uses THROW
 8457: s" exception" environment? [IF]
 8458:    0= [IF]
 8459:       : throw abort" exception thrown" ;
 8460:    [THEN]
 8461: [ELSE] \ we don't know, so make sure
 8462:    : throw abort" exception thrown" ;
 8463: [THEN]
 8464: 
 8465: s" gforth" environment? [IF] .( Gforth version ) TYPE
 8466:                         [ELSE] .( Not Gforth..) [THEN]
 8467: 
 8468: \ a program using v*
 8469: s" gforth" environment? [IF]
 8470:   s" 0.5.0" compare 0< [IF] \ v* is a primitive since 0.5.0
 8471:    : v* ( f_addr1 nstride1 f_addr2 nstride2 ucount -- r )
 8472:      >r swap 2swap swap 0e r> 0 ?DO
 8473:        dup f@@ over + 2swap dup f@@ f* f+ over + 2swap
 8474:      LOOP
 8475:      2drop 2drop ; 
 8476:   [THEN]
 8477: [ELSE] \ 
 8478:   : v* ( f_addr1 nstride1 f_addr2 nstride2 ucount -- r )
 8479:   ...
 8480: [THEN]
 8481: @end example
 8482: 
 8483: Here is an example of adding a definition to the environment word list:
 8484: 
 8485: @example
 8486: get-current environment-wordlist set-current
 8487: true constant block
 8488: true constant block-ext
 8489: set-current
 8490: @end example
 8491: 
 8492: You can see what definitions are in the environment word list like this:
 8493: 
 8494: @example
 8495: environment-wordlist >order words previous
 8496: @end example
 8497: 
 8498: 
 8499: @c -------------------------------------------------------------
 8500: @node Files, Blocks, Environmental Queries, Words
 8501: @section Files
 8502: @cindex files
 8503: @cindex I/O - file-handling
 8504: 
 8505: Gforth provides facilities for accessing files that are stored in the
 8506: host operating system's file-system. Files that are processed by Gforth
 8507: can be divided into two categories:
 8508: 
 8509: @itemize @bullet
 8510: @item
 8511: Files that are processed by the Text Interpreter (@dfn{Forth source files}).
 8512: @item
 8513: Files that are processed by some other program (@dfn{general files}).
 8514: @end itemize
 8515: 
 8516: @menu
 8517: * Forth source files::          
 8518: * General files::               
 8519: * Redirection::                 
 8520: * Search Paths::                
 8521: @end menu
 8522: 
 8523: @c -------------------------------------------------------------
 8524: @node Forth source files, General files, Files, Files
 8525: @subsection Forth source files
 8526: @cindex including files
 8527: @cindex Forth source files
 8528: 
 8529: The simplest way to interpret the contents of a file is to use one of
 8530: these two formats:
 8531: 
 8532: @example
 8533: include mysource.fs
 8534: s" mysource.fs" included
 8535: @end example
 8536: 
 8537: You usually want to include a file only if it is not included already
 8538: (by, say, another source file). In that case, you can use one of these
 8539: three formats:
 8540: 
 8541: @example
 8542: require mysource.fs
 8543: needs mysource.fs
 8544: s" mysource.fs" required
 8545: @end example
 8546: 
 8547: @cindex stack effect of included files
 8548: @cindex including files, stack effect
 8549: It is good practice to write your source files such that interpreting them
 8550: does not change the stack. Source files designed in this way can be used with
 8551: @code{required} and friends without complications. For example:
 8552: 
 8553: @example
 8554: 1024 require foo.fs drop
 8555: @end example
 8556: 
 8557: Here you want to pass the argument 1024 (e.g., a buffer size) to
 8558: @file{foo.fs}.  Interpreting @file{foo.fs} has the stack effect ( n -- n
 8559: ), which allows its use with @code{require}.  Of course with such
 8560: parameters to required files, you have to ensure that the first
 8561: @code{require} fits for all uses (i.e., @code{require} it early in the
 8562: master load file).
 8563: 
 8564: doc-include-file
 8565: doc-included
 8566: doc-included?
 8567: doc-include
 8568: doc-required
 8569: doc-require
 8570: doc-needs
 8571: @c doc-init-included-files @c internal
 8572: doc-sourcefilename
 8573: doc-sourceline#
 8574: 
 8575: A definition in ANS Forth for @code{required} is provided in
 8576: @file{compat/required.fs}.
 8577: 
 8578: @c -------------------------------------------------------------
 8579: @node General files, Redirection, Forth source files, Files
 8580: @subsection General files
 8581: @cindex general files
 8582: @cindex file-handling
 8583: 
 8584: Files are opened/created by name and type. The following file access
 8585: methods (FAMs) are recognised:
 8586: 
 8587: @cindex fam (file access method)
 8588: doc-r/o
 8589: doc-r/w
 8590: doc-w/o
 8591: doc-bin
 8592: 
 8593: 
 8594: When a file is opened/created, it returns a file identifier,
 8595: @i{wfileid} that is used for all other file commands. All file
 8596: commands also return a status value, @i{wior}, that is 0 for a
 8597: successful operation and an implementation-defined non-zero value in the
 8598: case of an error.
 8599: 
 8600: 
 8601: doc-open-file
 8602: doc-create-file
 8603: 
 8604: doc-close-file
 8605: doc-delete-file
 8606: doc-rename-file
 8607: doc-read-file
 8608: doc-read-line
 8609: doc-key-file
 8610: doc-key?-file
 8611: doc-write-file
 8612: doc-write-line
 8613: doc-emit-file
 8614: doc-flush-file
 8615: 
 8616: doc-file-status
 8617: doc-file-position
 8618: doc-reposition-file
 8619: doc-file-size
 8620: doc-resize-file
 8621: 
 8622: doc-slurp-file
 8623: doc-slurp-fid
 8624: doc-stdin
 8625: doc-stdout
 8626: doc-stderr
 8627: 
 8628: @c ---------------------------------------------------------
 8629: @node Redirection, Search Paths, General files, Files
 8630: @subsection Redirection
 8631: @cindex Redirection
 8632: @cindex Input Redirection
 8633: @cindex Output Redirection
 8634: 
 8635: You can redirect the output of @code{type} and @code{emit} and all the
 8636: words that use them (all output words that don't have an explicit
 8637: target file) to an arbitrary file with the @code{outfile-execute},
 8638: used like this:
 8639: 
 8640: @example
 8641: : some-warning ( n -- )
 8642:     cr ." warning# " . ;
 8643: 
 8644: : print-some-warning ( n -- )
 8645:     ['] some-warning stderr outfile-execute ;
 8646: @end example
 8647: 
 8648: After @code{some-warning} is executed, the original output direction
 8649: is restored; this construct is safe against exceptions.  Similarly,
 8650: there is @code{infile-execute} for redirecting the input of @code{key}
 8651: and its users (any input word that does not take a file explicitly).
 8652: 
 8653: doc-outfile-execute
 8654: doc-infile-execute
 8655: 
 8656: If you do not want to redirect the input or output to a file, you can
 8657: also make use of the fact that @code{key}, @code{emit} and @code{type}
 8658: are deferred words (@pxref{Deferred Words}).  However, in that case
 8659: you have to worry about the restoration and the protection against
 8660: exceptions yourself; also, note that for redirecting the output in
 8661: this way, you have to redirect both @code{emit} and @code{type}.
 8662: 
 8663: @c ---------------------------------------------------------
 8664: @node Search Paths,  , Redirection, Files
 8665: @subsection Search Paths
 8666: @cindex path for @code{included}
 8667: @cindex file search path
 8668: @cindex @code{include} search path
 8669: @cindex search path for files
 8670: 
 8671: If you specify an absolute filename (i.e., a filename starting with
 8672: @file{/} or @file{~}, or with @file{:} in the second position (as in
 8673: @samp{C:...})) for @code{included} and friends, that file is included
 8674: just as you would expect.
 8675: 
 8676: If the filename starts with @file{./}, this refers to the directory that
 8677: the present file was @code{included} from.  This allows files to include
 8678: other files relative to their own position (irrespective of the current
 8679: working directory or the absolute position).  This feature is essential
 8680: for libraries consisting of several files, where a file may include
 8681: other files from the library.  It corresponds to @code{#include "..."}
 8682: in C. If the current input source is not a file, @file{.} refers to the
 8683: directory of the innermost file being included, or, if there is no file
 8684: being included, to the current working directory.
 8685: 
 8686: For relative filenames (not starting with @file{./}), Gforth uses a
 8687: search path similar to Forth's search order (@pxref{Word Lists}). It
 8688: tries to find the given filename in the directories present in the path,
 8689: and includes the first one it finds. There are separate search paths for
 8690: Forth source files and general files.  If the search path contains the
 8691: directory @file{.}, this refers to the directory of the current file, or
 8692: the working directory, as if the file had been specified with @file{./}.
 8693: 
 8694: Use @file{~+} to refer to the current working directory (as in the
 8695: @code{bash}).
 8696: 
 8697: @c anton: fold the following subsubsections into this subsection?
 8698: 
 8699: @menu
 8700: * Source Search Paths::         
 8701: * General Search Paths::        
 8702: @end menu
 8703: 
 8704: @c ---------------------------------------------------------
 8705: @node Source Search Paths, General Search Paths, Search Paths, Search Paths
 8706: @subsubsection Source Search Paths
 8707: @cindex search path control, source files
 8708: 
 8709: The search path is initialized when you start Gforth (@pxref{Invoking
 8710: Gforth}). You can display it and change it using @code{fpath} in
 8711: combination with the general path handling words.
 8712: 
 8713: doc-fpath
 8714: @c the functionality of the following words is easily available through
 8715: @c   fpath and the general path words.  The may go away.
 8716: @c doc-.fpath
 8717: @c doc-fpath+
 8718: @c doc-fpath=
 8719: @c doc-open-fpath-file
 8720: 
 8721: @noindent
 8722: Here is an example of using @code{fpath} and @code{require}:
 8723: 
 8724: @example
 8725: fpath path= /usr/lib/forth/|./
 8726: require timer.fs
 8727: @end example
 8728: 
 8729: 
 8730: @c ---------------------------------------------------------
 8731: @node General Search Paths,  , Source Search Paths, Search Paths
 8732: @subsubsection General Search Paths
 8733: @cindex search path control, source files
 8734: 
 8735: Your application may need to search files in several directories, like
 8736: @code{included} does. To facilitate this, Gforth allows you to define
 8737: and use your own search paths, by providing generic equivalents of the
 8738: Forth search path words:
 8739: 
 8740: doc-open-path-file
 8741: doc-path-allot
 8742: doc-clear-path
 8743: doc-also-path
 8744: doc-.path
 8745: doc-path+
 8746: doc-path=
 8747: 
 8748: @c anton: better define a word for it, say "path-allot ( ucount -- path-addr )
 8749: 
 8750: Here's an example of creating an empty search path:
 8751: @c
 8752: @example
 8753: create mypath 500 path-allot \ maximum length 500 chars (is checked)
 8754: @end example
 8755: 
 8756: @c -------------------------------------------------------------
 8757: @node Blocks, Other I/O, Files, Words
 8758: @section Blocks
 8759: @cindex I/O - blocks
 8760: @cindex blocks
 8761: 
 8762: When you run Gforth on a modern desk-top computer, it runs under the
 8763: control of an operating system which provides certain services.  One of
 8764: these services is @var{file services}, which allows Forth source code
 8765: and data to be stored in files and read into Gforth (@pxref{Files}).
 8766: 
 8767: Traditionally, Forth has been an important programming language on
 8768: systems where it has interfaced directly to the underlying hardware with
 8769: no intervening operating system. Forth provides a mechanism, called
 8770: @dfn{blocks}, for accessing mass storage on such systems.
 8771: 
 8772: A block is a 1024-byte data area, which can be used to hold data or
 8773: Forth source code. No structure is imposed on the contents of the
 8774: block. A block is identified by its number; blocks are numbered
 8775: contiguously from 1 to an implementation-defined maximum.
 8776: 
 8777: A typical system that used blocks but no operating system might use a
 8778: single floppy-disk drive for mass storage, with the disks formatted to
 8779: provide 256-byte sectors. Blocks would be implemented by assigning the
 8780: first four sectors of the disk to block 1, the second four sectors to
 8781: block 2 and so on, up to the limit of the capacity of the disk. The disk
 8782: would not contain any file system information, just the set of blocks.
 8783: 
 8784: @cindex blocks file
 8785: On systems that do provide file services, blocks are typically
 8786: implemented by storing a sequence of blocks within a single @dfn{blocks
 8787: file}.  The size of the blocks file will be an exact multiple of 1024
 8788: bytes, corresponding to the number of blocks it contains. This is the
 8789: mechanism that Gforth uses.
 8790: 
 8791: @cindex @file{blocks.fb}
 8792: Only one blocks file can be open at a time. If you use block words without
 8793: having specified a blocks file, Gforth defaults to the blocks file
 8794: @file{blocks.fb}. Gforth uses the Forth search path when attempting to
 8795: locate a blocks file (@pxref{Source Search Paths}).
 8796: 
 8797: @cindex block buffers
 8798: When you read and write blocks under program control, Gforth uses a
 8799: number of @dfn{block buffers} as intermediate storage. These buffers are
 8800: not used when you use @code{load} to interpret the contents of a block.
 8801: 
 8802: The behaviour of the block buffers is analagous to that of a cache.
 8803: Each block buffer has three states:
 8804: 
 8805: @itemize @bullet
 8806: @item
 8807: Unassigned
 8808: @item
 8809: Assigned-clean
 8810: @item
 8811: Assigned-dirty
 8812: @end itemize
 8813: 
 8814: Initially, all block buffers are @i{unassigned}. In order to access a
 8815: block, the block (specified by its block number) must be assigned to a
 8816: block buffer.
 8817: 
 8818: The assignment of a block to a block buffer is performed by @code{block}
 8819: or @code{buffer}. Use @code{block} when you wish to modify the existing
 8820: contents of a block. Use @code{buffer} when you don't care about the
 8821: existing contents of the block@footnote{The ANS Forth definition of
 8822: @code{buffer} is intended not to cause disk I/O; if the data associated
 8823: with the particular block is already stored in a block buffer due to an
 8824: earlier @code{block} command, @code{buffer} will return that block
 8825: buffer and the existing contents of the block will be
 8826: available. Otherwise, @code{buffer} will simply assign a new, empty
 8827: block buffer for the block.}.
 8828: 
 8829: Once a block has been assigned to a block buffer using @code{block} or
 8830: @code{buffer}, that block buffer becomes the @i{current block
 8831: buffer}. Data may only be manipulated (read or written) within the
 8832: current block buffer.
 8833: 
 8834: When the contents of the current block buffer has been modified it is
 8835: necessary, @emph{before calling @code{block} or @code{buffer} again}, to
 8836: either abandon the changes (by doing nothing) or mark the block as
 8837: changed (assigned-dirty), using @code{update}. Using @code{update} does
 8838: not change the blocks file; it simply changes a block buffer's state to
 8839: @i{assigned-dirty}.  The block will be written implicitly when it's
 8840: buffer is needed for another block, or explicitly by @code{flush} or
 8841: @code{save-buffers}.
 8842: 
 8843: word @code{Flush} writes all @i{assigned-dirty} blocks back to the
 8844: blocks file on disk. Leaving Gforth with @code{bye} also performs a
 8845: @code{flush}.
 8846: 
 8847: In Gforth, @code{block} and @code{buffer} use a @i{direct-mapped}
 8848: algorithm to assign a block buffer to a block. That means that any
 8849: particular block can only be assigned to one specific block buffer,
 8850: called (for the particular operation) the @i{victim buffer}. If the
 8851: victim buffer is @i{unassigned} or @i{assigned-clean} it is allocated to
 8852: the new block immediately. If it is @i{assigned-dirty} its current
 8853: contents are written back to the blocks file on disk before it is
 8854: allocated to the new block.
 8855: 
 8856: Although no structure is imposed on the contents of a block, it is
 8857: traditional to display the contents as 16 lines each of 64 characters.  A
 8858: block provides a single, continuous stream of input (for example, it
 8859: acts as a single parse area) -- there are no end-of-line characters
 8860: within a block, and no end-of-file character at the end of a
 8861: block. There are two consequences of this:
 8862: 
 8863: @itemize @bullet
 8864: @item
 8865: The last character of one line wraps straight into the first character
 8866: of the following line
 8867: @item
 8868: The word @code{\} -- comment to end of line -- requires special
 8869: treatment; in the context of a block it causes all characters until the
 8870: end of the current 64-character ``line'' to be ignored.
 8871: @end itemize
 8872: 
 8873: In Gforth, when you use @code{block} with a non-existent block number,
 8874: the current blocks file will be extended to the appropriate size and the
 8875: block buffer will be initialised with spaces.
 8876: 
 8877: Gforth includes a simple block editor (type @code{use blocked.fb 0 list}
 8878: for details) but doesn't encourage the use of blocks; the mechanism is
 8879: only provided for backward compatibility -- ANS Forth requires blocks to
 8880: be available when files are.
 8881: 
 8882: Common techniques that are used when working with blocks include:
 8883: 
 8884: @itemize @bullet
 8885: @item
 8886: A screen editor that allows you to edit blocks without leaving the Forth
 8887: environment.
 8888: @item
 8889: Shadow screens; where every code block has an associated block
 8890: containing comments (for example: code in odd block numbers, comments in
 8891: even block numbers). Typically, the block editor provides a convenient
 8892: mechanism to toggle between code and comments.
 8893: @item
 8894: Load blocks; a single block (typically block 1) contains a number of
 8895: @code{thru} commands which @code{load} the whole of the application.
 8896: @end itemize
 8897: 
 8898: See Frank Sergeant's Pygmy Forth to see just how well blocks can be
 8899: integrated into a Forth programming environment.
 8900: 
 8901: @comment TODO what about errors on open-blocks?
 8902: 
 8903: doc-open-blocks
 8904: doc-use
 8905: doc-block-offset
 8906: doc-get-block-fid
 8907: doc-block-position
 8908: 
 8909: doc-list
 8910: doc-scr
 8911: 
 8912: doc-block
 8913: doc-buffer
 8914: 
 8915: doc-empty-buffers
 8916: doc-empty-buffer
 8917: doc-update
 8918: doc-updated?
 8919: doc-save-buffers
 8920: doc-save-buffer
 8921: doc-flush
 8922: 
 8923: doc-load
 8924: doc-thru
 8925: doc-+load
 8926: doc-+thru
 8927: doc---gforthman--->
 8928: doc-block-included
 8929: 
 8930: 
 8931: @c -------------------------------------------------------------
 8932: @node Other I/O, OS command line arguments, Blocks, Words
 8933: @section Other I/O
 8934: @cindex I/O - keyboard and display
 8935: 
 8936: @menu
 8937: * Simple numeric output::       Predefined formats
 8938: * Formatted numeric output::    Formatted (pictured) output
 8939: * String Formats::              How Forth stores strings in memory
 8940: * Displaying characters and strings::  Other stuff
 8941: * String words::                Gforth's little string library
 8942: * Terminal output::             Cursor positioning etc.
 8943: * Single-key input::            
 8944: * Line input and conversion::   
 8945: * Pipes::                       How to create your own pipes
 8946: * Xchars and Unicode::          Non-ASCII characters
 8947: @end menu
 8948: 
 8949: @node Simple numeric output, Formatted numeric output, Other I/O, Other I/O
 8950: @subsection Simple numeric output
 8951: @cindex numeric output - simple/free-format
 8952: 
 8953: The simplest output functions are those that display numbers from the
 8954: data or floating-point stacks. Floating-point output is always displayed
 8955: using base 10. Numbers displayed from the data stack use the value stored
 8956: in @code{base}.
 8957: 
 8958: 
 8959: doc-.
 8960: doc-dec.
 8961: doc-hex.
 8962: doc-u.
 8963: doc-.r
 8964: doc-u.r
 8965: doc-d.
 8966: doc-ud.
 8967: doc-d.r
 8968: doc-ud.r
 8969: doc-f.
 8970: doc-fe.
 8971: doc-fs.
 8972: doc-f.rdp
 8973: 
 8974: Examples of printing the number 1234.5678E23 in the different floating-point output
 8975: formats are shown below:
 8976: 
 8977: @example
 8978: f. 123456779999999000000000000.
 8979: fe. 123.456779999999E24
 8980: fs. 1.23456779999999E26
 8981: @end example
 8982: 
 8983: 
 8984: @node Formatted numeric output, String Formats, Simple numeric output, Other I/O
 8985: @subsection Formatted numeric output
 8986: @cindex formatted numeric output
 8987: @cindex pictured numeric output
 8988: @cindex numeric output - formatted
 8989: 
 8990: Forth traditionally uses a technique called @dfn{pictured numeric
 8991: output} for formatted printing of integers.  In this technique, digits
 8992: are extracted from the number (using the current output radix defined by
 8993: @code{base}), converted to ASCII codes and appended to a string that is
 8994: built in a scratch-pad area of memory (@pxref{core-idef,
 8995: Implementation-defined options, Implementation-defined
 8996: options}). Arbitrary characters can be appended to the string during the
 8997: extraction process. The completed string is specified by an address
 8998: and length and can be manipulated (@code{TYPE}ed, copied, modified)
 8999: under program control.
 9000: 
 9001: All of the integer output words described in the previous section
 9002: (@pxref{Simple numeric output}) are implemented in Gforth using pictured
 9003: numeric output.
 9004: 
 9005: Three important things to remember about pictured numeric output:
 9006: 
 9007: @itemize @bullet
 9008: @item
 9009: It always operates on double-precision numbers; to display a
 9010: single-precision number, convert it first (for ways of doing this
 9011: @pxref{Double precision}).
 9012: @item
 9013: It always treats the double-precision number as though it were
 9014: unsigned. The examples below show ways of printing signed numbers.
 9015: @item
 9016: The string is built up from right to left; least significant digit first.
 9017: @end itemize
 9018: 
 9019: 
 9020: doc-<#
 9021: doc-<<#
 9022: doc-#
 9023: doc-#s
 9024: doc-hold
 9025: doc-sign
 9026: doc-#>
 9027: doc-#>>
 9028: 
 9029: doc-represent
 9030: doc-f>str-rdp
 9031: doc-f>buf-rdp
 9032: 
 9033: 
 9034: @noindent
 9035: Here are some examples of using pictured numeric output:
 9036: 
 9037: @example
 9038: : my-u. ( u -- )
 9039:   \ Simplest use of pns.. behaves like Standard u. 
 9040:   0              \ convert to unsigned double
 9041:   <<#            \ start conversion
 9042:   #s             \ convert all digits
 9043:   #>             \ complete conversion
 9044:   TYPE SPACE     \ display, with trailing space
 9045:   #>> ;          \ release hold area
 9046: 
 9047: : cents-only ( u -- )
 9048:   0              \ convert to unsigned double
 9049:   <<#            \ start conversion
 9050:   # #            \ convert two least-significant digits
 9051:   #>             \ complete conversion, discard other digits
 9052:   TYPE SPACE     \ display, with trailing space
 9053:   #>> ;          \ release hold area
 9054: 
 9055: : dollars-and-cents ( u -- )
 9056:   0              \ convert to unsigned double
 9057:   <<#            \ start conversion
 9058:   # #            \ convert two least-significant digits
 9059:   [char] . hold  \ insert decimal point
 9060:   #s             \ convert remaining digits
 9061:   [char] $ hold  \ append currency symbol
 9062:   #>             \ complete conversion
 9063:   TYPE SPACE     \ display, with trailing space
 9064:   #>> ;          \ release hold area
 9065: 
 9066: : my-. ( n -- )
 9067:   \ handling negatives.. behaves like Standard .
 9068:   s>d            \ convert to signed double
 9069:   swap over dabs \ leave sign byte followed by unsigned double
 9070:   <<#            \ start conversion
 9071:   #s             \ convert all digits
 9072:   rot sign       \ get at sign byte, append "-" if needed
 9073:   #>             \ complete conversion
 9074:   TYPE SPACE     \ display, with trailing space
 9075:   #>> ;          \ release hold area
 9076: 
 9077: : account. ( n -- )
 9078:   \ accountants don't like minus signs, they use parentheses
 9079:   \ for negative numbers
 9080:   s>d            \ convert to signed double
 9081:   swap over dabs \ leave sign byte followed by unsigned double
 9082:   <<#            \ start conversion
 9083:   2 pick         \ get copy of sign byte
 9084:   0< IF [char] ) hold THEN \ right-most character of output
 9085:   #s             \ convert all digits
 9086:   rot            \ get at sign byte
 9087:   0< IF [char] ( hold THEN
 9088:   #>             \ complete conversion
 9089:   TYPE SPACE     \ display, with trailing space
 9090:   #>> ;          \ release hold area
 9091: 
 9092: @end example
 9093: 
 9094: Here are some examples of using these words:
 9095: 
 9096: @example
 9097: 1 my-u. 1
 9098: hex -1 my-u. decimal FFFFFFFF
 9099: 1 cents-only 01
 9100: 1234 cents-only 34
 9101: 2 dollars-and-cents $0.02
 9102: 1234 dollars-and-cents $12.34
 9103: 123 my-. 123
 9104: -123 my. -123
 9105: 123 account. 123
 9106: -456 account. (456)
 9107: @end example
 9108: 
 9109: 
 9110: @node String Formats, Displaying characters and strings, Formatted numeric output, Other I/O
 9111: @subsection String Formats
 9112: @cindex strings - see character strings
 9113: @cindex character strings - formats
 9114: @cindex I/O - see character strings
 9115: @cindex counted strings
 9116: 
 9117: @c anton: this does not really belong here; maybe the memory section,
 9118: @c  or the principles chapter
 9119: 
 9120: Forth commonly uses two different methods for representing character
 9121: strings:
 9122: 
 9123: @itemize @bullet
 9124: @item
 9125: @cindex address of counted string
 9126: @cindex counted string
 9127: As a @dfn{counted string}, represented by a @i{c-addr}. The char
 9128: addressed by @i{c-addr} contains a character-count, @i{n}, of the
 9129: string and the string occupies the subsequent @i{n} char addresses in
 9130: memory.
 9131: @item
 9132: As cell pair on the stack; @i{c-addr u}, where @i{u} is the length
 9133: of the string in characters, and @i{c-addr} is the address of the
 9134: first byte of the string.
 9135: @end itemize
 9136: 
 9137: ANS Forth encourages the use of the second format when representing
 9138: strings.
 9139: 
 9140: 
 9141: doc-count
 9142: 
 9143: 
 9144: For words that move, copy and search for strings see @ref{Memory
 9145: Blocks}. For words that display characters and strings see
 9146: @ref{Displaying characters and strings}.
 9147: 
 9148: @node Displaying characters and strings, String words, String Formats, Other I/O
 9149: @subsection Displaying characters and strings
 9150: @cindex characters - compiling and displaying
 9151: @cindex character strings - compiling and displaying
 9152: 
 9153: This section starts with a glossary of Forth words and ends with a set
 9154: of examples.
 9155: 
 9156: doc-bl
 9157: doc-space
 9158: doc-spaces
 9159: doc-emit
 9160: doc-toupper
 9161: doc-."
 9162: doc-.(
 9163: doc-.\"
 9164: doc-type
 9165: doc-typewhite
 9166: doc-cr
 9167: @cindex cursor control
 9168: doc-s"
 9169: doc-s\"
 9170: doc-c"
 9171: doc-char
 9172: doc-[char]
 9173: 
 9174: 
 9175: @noindent
 9176: As an example, consider the following text, stored in a file @file{test.fs}:
 9177: 
 9178: @example
 9179: .( text-1)
 9180: : my-word
 9181:   ." text-2" cr
 9182:   .( text-3)
 9183: ;
 9184: 
 9185: ." text-4"
 9186: 
 9187: : my-char
 9188:   [char] ALPHABET emit
 9189:   char emit
 9190: ;
 9191: @end example
 9192: 
 9193: When you load this code into Gforth, the following output is generated:
 9194: 
 9195: @example
 9196: @kbd{include test.fs @key{RET}} text-1text-3text-4 ok
 9197: @end example
 9198: 
 9199: @itemize @bullet
 9200: @item
 9201: Messages @code{text-1} and @code{text-3} are displayed because @code{.(} 
 9202: is an immediate word; it behaves in the same way whether it is used inside
 9203: or outside a colon definition.
 9204: @item
 9205: Message @code{text-4} is displayed because of Gforth's added interpretation
 9206: semantics for @code{."}.
 9207: @item
 9208: Message @code{text-2} is @i{not} displayed, because the text interpreter
 9209: performs the compilation semantics for @code{."} within the definition of
 9210: @code{my-word}.
 9211: @end itemize
 9212: 
 9213: Here are some examples of executing @code{my-word} and @code{my-char}:
 9214: 
 9215: @example
 9216: @kbd{my-word @key{RET}} text-2
 9217:  ok
 9218: @kbd{my-char fred @key{RET}} Af ok
 9219: @kbd{my-char jim @key{RET}} Aj ok
 9220: @end example
 9221: 
 9222: @itemize @bullet
 9223: @item
 9224: Message @code{text-2} is displayed because of the run-time behaviour of
 9225: @code{."}.
 9226: @item
 9227: @code{[char]} compiles the ``A'' from ``ALPHABET'' and puts its display code
 9228: on the stack at run-time. @code{emit} always displays the character
 9229: when @code{my-char} is executed.
 9230: @item
 9231: @code{char} parses a string at run-time and the second @code{emit} displays
 9232: the first character of the string.
 9233: @item
 9234: If you type @code{see my-char} you can see that @code{[char]} discarded
 9235: the text ``LPHABET'' and only compiled the display code for ``A'' into the
 9236: definition of @code{my-char}.
 9237: @end itemize
 9238: 
 9239: @node String words, Terminal output, Displaying characters and strings, Other I/O
 9240: @subsection String words
 9241: @cindex string words
 9242: 
 9243: The following string library stores strings in ordinary variables,
 9244: which then contain a pointer to a counted string stored allocated from
 9245: the heap.  Instead of a count byte, there's a whole count cell,
 9246: sufficient for all normal use.  The string library originates from
 9247: bigFORTH.
 9248: 
 9249: doc-delete
 9250: doc-insert
 9251: doc-$!
 9252: doc-$@
 9253: doc-$@len
 9254: doc-$!len
 9255: doc-$del
 9256: doc-$ins
 9257: doc-$+!
 9258: doc-$off
 9259: doc-$init
 9260: doc-$split
 9261: doc-$iter
 9262: 
 9263: @node Terminal output, Single-key input, String words, Other I/O
 9264: @subsection Terminal output
 9265: @cindex output to terminal
 9266: @cindex terminal output
 9267: 
 9268: If you are outputting to a terminal, you may want to control the
 9269: positioning of the cursor:
 9270: @cindex cursor positioning
 9271: 
 9272: doc-at-xy
 9273: 
 9274: In order to know where to position the cursor, it is often helpful to
 9275: know the size of the screen:
 9276: @cindex terminal size 
 9277: 
 9278: doc-form
 9279: 
 9280: And sometimes you want to use:
 9281: @cindex clear screen
 9282: 
 9283: doc-page
 9284: 
 9285: Note that on non-terminals you should use @code{12 emit}, not
 9286: @code{page}, to get a form feed.
 9287: 
 9288: 
 9289: @node Single-key input, Line input and conversion, Terminal output, Other I/O
 9290: @subsection Single-key input
 9291: @cindex single-key input
 9292: @cindex input, single-key
 9293: 
 9294: If you want to get a single printable character, you can use
 9295: @code{key}; to check whether a character is available for @code{key},
 9296: you can use @code{key?}.
 9297: 
 9298: doc-key
 9299: doc-key?
 9300: 
 9301: If you want to process a mix of printable and non-printable
 9302: characters, you can do that with @code{ekey} and friends.  @code{Ekey}
 9303: produces a keyboard event that you have to convert into a character
 9304: with @code{ekey>char} or into a key identifier with @code{ekey>fkey}.
 9305: 
 9306: Typical code for using EKEY looks like this:
 9307: 
 9308: @example
 9309: ekey ekey>char if ( c )
 9310:   ... \ do something with the character
 9311: else ekey>fkey if ( key-id )
 9312:   case
 9313:     k-up                                  of ... endof
 9314:     k-f1                                  of ... endof
 9315:     k-left k-shift-mask or k-ctrl-mask or of ... endof
 9316:     ...
 9317:   endcase
 9318: else ( keyboard-event )
 9319:   drop \ just ignore an unknown keyboard event type
 9320: then then
 9321: @end example
 9322: 
 9323: doc-ekey
 9324: doc-ekey>char
 9325: doc-ekey>fkey
 9326: doc-ekey?
 9327: 
 9328: The key identifiers for cursor keys are:
 9329: 
 9330: doc-k-left
 9331: doc-k-right
 9332: doc-k-up
 9333: doc-k-down
 9334: doc-k-home
 9335: doc-k-end
 9336: doc-k-prior
 9337: doc-k-next
 9338: doc-k-insert
 9339: doc-k-delete
 9340: 
 9341: The key identifiers for function keys (aka keypad keys) are:
 9342: 
 9343: doc-k-f1
 9344: doc-k-f2
 9345: doc-k-f3
 9346: doc-k-f4
 9347: doc-k-f5
 9348: doc-k-f6
 9349: doc-k-f7
 9350: doc-k-f8
 9351: doc-k-f9
 9352: doc-k-f10
 9353: doc-k-f11
 9354: doc-k-f12
 9355: 
 9356: Note that @code{k-f11} and @code{k-f12} are not as widely available.
 9357: 
 9358: You can combine these key identifiers with masks for various shift keys:
 9359: 
 9360: doc-k-shift-mask
 9361: doc-k-ctrl-mask
 9362: doc-k-alt-mask
 9363: 
 9364: Note that, even if a Forth system has @code{ekey>fkey} and the key
 9365: identifier words, the keys are not necessarily available or it may not
 9366: necessarily be able to report all the keys and all the possible
 9367: combinations with shift masks.  Therefore, write your programs in such
 9368: a way that they are still useful even if the keys and key combinations
 9369: cannot be pressed or are not recognized.
 9370: 
 9371: Examples: Older keyboards often do not have an F11 and F12 key.  If
 9372: you run Gforth in an xterm, the xterm catches a number of combinations
 9373: (e.g., @key{Shift-Up}), and never passes it to Gforth.  Finally,
 9374: Gforth currently does not recognize and report combinations with
 9375: multiple shift keys (so the @key{shift-ctrl-left} case in the example
 9376: above would never be entered).
 9377: 
 9378: Gforth recognizes various keys available on ANSI terminals (in MS-DOS
 9379: you need the ANSI.SYS driver to get that behaviour); it works by
 9380: recognizing the escape sequences that ANSI terminals send when such a
 9381: key is pressed.  If you have a terminal that sends other escape
 9382: sequences, you will not get useful results on Gforth.  Other Forth
 9383: systems may work in a different way.
 9384: 
 9385: Gforth also provides a few words for outputting names of function
 9386: keys:
 9387: 
 9388: doc-fkey.
 9389: doc-simple-fkey-string
 9390: 
 9391: 
 9392: @node  Line input and conversion, Pipes, Single-key input, Other I/O
 9393: @subsection Line input and conversion
 9394: @cindex line input from terminal
 9395: @cindex input, linewise from terminal
 9396: @cindex convertin strings to numbers
 9397: @cindex I/O - see input
 9398: 
 9399: For ways of storing character strings in memory see @ref{String Formats}.
 9400: 
 9401: @comment TODO examples for >number >float accept key key? pad parse word refill
 9402: @comment then index them
 9403: 
 9404: Words for inputting one line from the keyboard:
 9405: 
 9406: doc-accept
 9407: doc-edit-line
 9408: 
 9409: Conversion words:
 9410: 
 9411: doc-s>number?
 9412: doc-s>unumber?
 9413: doc->number
 9414: doc->float
 9415: 
 9416: 
 9417: @comment obsolescent words..
 9418: Obsolescent input and conversion words:
 9419: 
 9420: doc-convert
 9421: doc-expect
 9422: doc-span
 9423: 
 9424: 
 9425: @node Pipes, Xchars and Unicode, Line input and conversion, Other I/O
 9426: @subsection Pipes
 9427: @cindex pipes, creating your own
 9428: 
 9429: In addition to using Gforth in pipes created by other processes
 9430: (@pxref{Gforth in pipes}), you can create your own pipe with
 9431: @code{open-pipe}, and read from or write to it.
 9432: 
 9433: doc-open-pipe
 9434: doc-close-pipe
 9435: 
 9436: If you write to a pipe, Gforth can throw a @code{broken-pipe-error}; if
 9437: you don't catch this exception, Gforth will catch it and exit, usually
 9438: silently (@pxref{Gforth in pipes}).  Since you probably do not want
 9439: this, you should wrap a @code{catch} or @code{try} block around the code
 9440: from @code{open-pipe} to @code{close-pipe}, so you can deal with the
 9441: problem yourself, and then return to regular processing.
 9442: 
 9443: doc-broken-pipe-error
 9444: 
 9445: @node Xchars and Unicode,  , Pipes, Other I/O
 9446: @subsection Xchars and Unicode
 9447: 
 9448: ASCII is only appropriate for the English language. Most western
 9449: languages however fit somewhat into the Forth frame, since a byte is
 9450: sufficient to encode the few special characters in each (though not
 9451: always the same encoding can be used; latin-1 is most widely used,
 9452: though). For other languages, different char-sets have to be used,
 9453: several of them variable-width. Most prominent representant is
 9454: UTF-8. Let's call these extended characters xchars. The primitive
 9455: fixed-size characters stored as bytes are called pchars in this
 9456: section.
 9457: 
 9458: The xchar words add a few data types:
 9459: 
 9460: @itemize
 9461: 
 9462: @item
 9463: @var{xc} is an extended char (xchar) on the stack. It occupies one cell,
 9464: and is a subset of unsigned cell. Note: UTF-8 can not store more that
 9465: 31 bits; on 16 bit systems, only the UCS16 subset of the UTF-8
 9466: character set can be used.
 9467: 
 9468: @item
 9469: @var{xc-addr} is the address of an xchar in memory. Alignment
 9470: requirements are the same as @var{c-addr}. The memory representation of an
 9471: xchar differs from the stack representation, and depends on the
 9472: encoding used. An xchar may use a variable number of pchars in memory.
 9473: 
 9474: @item
 9475: @var{xc-addr} @var{u} is a buffer of xchars in memory, starting at
 9476: @var{xc-addr}, @var{u} pchars long.
 9477: 
 9478: @end itemize
 9479: 
 9480: doc-xc-size
 9481: doc-x-size
 9482: doc-xc@+
 9483: doc-xc!+?
 9484: doc-xchar+
 9485: doc-xchar-
 9486: doc-+x/string
 9487: doc-x\string-
 9488: doc--trailing-garbage
 9489: doc-x-width
 9490: doc-xkey
 9491: doc-xemit
 9492: 
 9493: There's a new environment query
 9494: 
 9495: doc-xchar-encoding
 9496: 
 9497: @node OS command line arguments, Locals, Other I/O, Words
 9498: @section OS command line arguments
 9499: @cindex OS command line arguments
 9500: @cindex command line arguments, OS
 9501: @cindex arguments, OS command line
 9502: 
 9503: The usual way to pass arguments to Gforth programs on the command line
 9504: is via the @option{-e} option, e.g.
 9505: 
 9506: @example
 9507: gforth -e "123 456" foo.fs -e bye
 9508: @end example
 9509: 
 9510: However, you may want to interpret the command-line arguments directly.
 9511: In that case, you can access the (image-specific) command-line arguments
 9512: through @code{next-arg}:
 9513: 
 9514: doc-next-arg
 9515: 
 9516: Here's an example program @file{echo.fs} for @code{next-arg}:
 9517: 
 9518: @example
 9519: : echo ( -- )
 9520:     begin
 9521: 	next-arg 2dup 0 0 d<> while
 9522: 	    type space
 9523:     repeat
 9524:     2drop ;
 9525: 
 9526: echo cr bye
 9527: @end example
 9528: 
 9529: This can be invoked with
 9530: 
 9531: @example
 9532: gforth echo.fs hello world
 9533: @end example
 9534: 
 9535: and it will print
 9536: 
 9537: @example
 9538: hello world
 9539: @end example
 9540: 
 9541: The next lower level of dealing with the OS command line are the
 9542: following words:
 9543: 
 9544: doc-arg
 9545: doc-shift-args
 9546: 
 9547: Finally, at the lowest level Gforth provides the following words:
 9548: 
 9549: doc-argc
 9550: doc-argv
 9551: 
 9552: @c -------------------------------------------------------------
 9553: @node Locals, Structures, OS command line arguments, Words
 9554: @section Locals
 9555: @cindex locals
 9556: 
 9557: Local variables can make Forth programming more enjoyable and Forth
 9558: programs easier to read. Unfortunately, the locals of ANS Forth are
 9559: laden with restrictions. Therefore, we provide not only the ANS Forth
 9560: locals wordset, but also our own, more powerful locals wordset (we
 9561: implemented the ANS Forth locals wordset through our locals wordset).
 9562: 
 9563: The ideas in this section have also been published in M. Anton Ertl,
 9564: @cite{@uref{http://www.complang.tuwien.ac.at/papers/ertl94l.ps.gz,
 9565: Automatic Scoping of Local Variables}}, EuroForth '94.
 9566: 
 9567: @menu
 9568: * Gforth locals::               
 9569: * ANS Forth locals::            
 9570: @end menu
 9571: 
 9572: @node Gforth locals, ANS Forth locals, Locals, Locals
 9573: @subsection Gforth locals
 9574: @cindex Gforth locals
 9575: @cindex locals, Gforth style
 9576: 
 9577: Locals can be defined with
 9578: 
 9579: @example
 9580: @{ local1 local2 ... -- comment @}
 9581: @end example
 9582: or
 9583: @example
 9584: @{ local1 local2 ... @}
 9585: @end example
 9586: 
 9587: E.g.,
 9588: @example
 9589: : max @{ n1 n2 -- n3 @}
 9590:  n1 n2 > if
 9591:    n1
 9592:  else
 9593:    n2
 9594:  endif ;
 9595: @end example
 9596: 
 9597: The similarity of locals definitions with stack comments is intended. A
 9598: locals definition often replaces the stack comment of a word. The order
 9599: of the locals corresponds to the order in a stack comment and everything
 9600: after the @code{--} is really a comment.
 9601: 
 9602: This similarity has one disadvantage: It is too easy to confuse locals
 9603: declarations with stack comments, causing bugs and making them hard to
 9604: find. However, this problem can be avoided by appropriate coding
 9605: conventions: Do not use both notations in the same program. If you do,
 9606: they should be distinguished using additional means, e.g. by position.
 9607: 
 9608: @cindex types of locals
 9609: @cindex locals types
 9610: The name of the local may be preceded by a type specifier, e.g.,
 9611: @code{F:} for a floating point value:
 9612: 
 9613: @example
 9614: : CX* @{ F: Ar F: Ai F: Br F: Bi -- Cr Ci @}
 9615: \ complex multiplication
 9616:  Ar Br f* Ai Bi f* f-
 9617:  Ar Bi f* Ai Br f* f+ ;
 9618: @end example
 9619: 
 9620: @cindex flavours of locals
 9621: @cindex locals flavours
 9622: @cindex value-flavoured locals
 9623: @cindex variable-flavoured locals
 9624: Gforth currently supports cells (@code{W:}, @code{W^}), doubles
 9625: (@code{D:}, @code{D^}), floats (@code{F:}, @code{F^}) and characters
 9626: (@code{C:}, @code{C^}) in two flavours: a value-flavoured local (defined
 9627: with @code{W:}, @code{D:} etc.) produces its value and can be changed
 9628: with @code{TO}. A variable-flavoured local (defined with @code{W^} etc.)
 9629: produces its address (which becomes invalid when the variable's scope is
 9630: left). E.g., the standard word @code{emit} can be defined in terms of
 9631: @code{type} like this:
 9632: 
 9633: @example
 9634: : emit @{ C^ char* -- @}
 9635:     char* 1 type ;
 9636: @end example
 9637: 
 9638: @cindex default type of locals
 9639: @cindex locals, default type
 9640: A local without type specifier is a @code{W:} local. Both flavours of
 9641: locals are initialized with values from the data or FP stack.
 9642: 
 9643: Currently there is no way to define locals with user-defined data
 9644: structures, but we are working on it.
 9645: 
 9646: Gforth allows defining locals everywhere in a colon definition. This
 9647: poses the following questions:
 9648: 
 9649: @menu
 9650: * Where are locals visible by name?::  
 9651: * How long do locals live?::    
 9652: * Locals programming style::    
 9653: * Locals implementation::       
 9654: @end menu
 9655: 
 9656: @node Where are locals visible by name?, How long do locals live?, Gforth locals, Gforth locals
 9657: @subsubsection Where are locals visible by name?
 9658: @cindex locals visibility
 9659: @cindex visibility of locals
 9660: @cindex scope of locals
 9661: 
 9662: Basically, the answer is that locals are visible where you would expect
 9663: it in block-structured languages, and sometimes a little longer. If you
 9664: want to restrict the scope of a local, enclose its definition in
 9665: @code{SCOPE}...@code{ENDSCOPE}.
 9666: 
 9667: 
 9668: doc-scope
 9669: doc-endscope
 9670: 
 9671: 
 9672: These words behave like control structure words, so you can use them
 9673: with @code{CS-PICK} and @code{CS-ROLL} to restrict the scope in
 9674: arbitrary ways.
 9675: 
 9676: If you want a more exact answer to the visibility question, here's the
 9677: basic principle: A local is visible in all places that can only be
 9678: reached through the definition of the local@footnote{In compiler
 9679: construction terminology, all places dominated by the definition of the
 9680: local.}. In other words, it is not visible in places that can be reached
 9681: without going through the definition of the local. E.g., locals defined
 9682: in @code{IF}...@code{ENDIF} are visible until the @code{ENDIF}, locals
 9683: defined in @code{BEGIN}...@code{UNTIL} are visible after the
 9684: @code{UNTIL} (until, e.g., a subsequent @code{ENDSCOPE}).
 9685: 
 9686: The reasoning behind this solution is: We want to have the locals
 9687: visible as long as it is meaningful. The user can always make the
 9688: visibility shorter by using explicit scoping. In a place that can
 9689: only be reached through the definition of a local, the meaning of a
 9690: local name is clear. In other places it is not: How is the local
 9691: initialized at the control flow path that does not contain the
 9692: definition? Which local is meant, if the same name is defined twice in
 9693: two independent control flow paths?
 9694: 
 9695: This should be enough detail for nearly all users, so you can skip the
 9696: rest of this section. If you really must know all the gory details and
 9697: options, read on.
 9698: 
 9699: In order to implement this rule, the compiler has to know which places
 9700: are unreachable. It knows this automatically after @code{AHEAD},
 9701: @code{AGAIN}, @code{EXIT} and @code{LEAVE}; in other cases (e.g., after
 9702: most @code{THROW}s), you can use the word @code{UNREACHABLE} to tell the
 9703: compiler that the control flow never reaches that place. If
 9704: @code{UNREACHABLE} is not used where it could, the only consequence is
 9705: that the visibility of some locals is more limited than the rule above
 9706: says. If @code{UNREACHABLE} is used where it should not (i.e., if you
 9707: lie to the compiler), buggy code will be produced.
 9708: 
 9709: 
 9710: doc-unreachable
 9711: 
 9712: 
 9713: Another problem with this rule is that at @code{BEGIN}, the compiler
 9714: does not know which locals will be visible on the incoming
 9715: back-edge. All problems discussed in the following are due to this
 9716: ignorance of the compiler (we discuss the problems using @code{BEGIN}
 9717: loops as examples; the discussion also applies to @code{?DO} and other
 9718: loops). Perhaps the most insidious example is:
 9719: @example
 9720: AHEAD
 9721: BEGIN
 9722:   x
 9723: [ 1 CS-ROLL ] THEN
 9724:   @{ x @}
 9725:   ...
 9726: UNTIL
 9727: @end example
 9728: 
 9729: This should be legal according to the visibility rule. The use of
 9730: @code{x} can only be reached through the definition; but that appears
 9731: textually below the use.
 9732: 
 9733: From this example it is clear that the visibility rules cannot be fully
 9734: implemented without major headaches. Our implementation treats common
 9735: cases as advertised and the exceptions are treated in a safe way: The
 9736: compiler makes a reasonable guess about the locals visible after a
 9737: @code{BEGIN}; if it is too pessimistic, the
 9738: user will get a spurious error about the local not being defined; if the
 9739: compiler is too optimistic, it will notice this later and issue a
 9740: warning. In the case above the compiler would complain about @code{x}
 9741: being undefined at its use. You can see from the obscure examples in
 9742: this section that it takes quite unusual control structures to get the
 9743: compiler into trouble, and even then it will often do fine.
 9744: 
 9745: If the @code{BEGIN} is reachable from above, the most optimistic guess
 9746: is that all locals visible before the @code{BEGIN} will also be
 9747: visible after the @code{BEGIN}. This guess is valid for all loops that
 9748: are entered only through the @code{BEGIN}, in particular, for normal
 9749: @code{BEGIN}...@code{WHILE}...@code{REPEAT} and
 9750: @code{BEGIN}...@code{UNTIL} loops and it is implemented in our
 9751: compiler. When the branch to the @code{BEGIN} is finally generated by
 9752: @code{AGAIN} or @code{UNTIL}, the compiler checks the guess and
 9753: warns the user if it was too optimistic:
 9754: @example
 9755: IF
 9756:   @{ x @}
 9757: BEGIN
 9758:   \ x ? 
 9759: [ 1 cs-roll ] THEN
 9760:   ...
 9761: UNTIL
 9762: @end example
 9763: 
 9764: Here, @code{x} lives only until the @code{BEGIN}, but the compiler
 9765: optimistically assumes that it lives until the @code{THEN}. It notices
 9766: this difference when it compiles the @code{UNTIL} and issues a
 9767: warning. The user can avoid the warning, and make sure that @code{x}
 9768: is not used in the wrong area by using explicit scoping:
 9769: @example
 9770: IF
 9771:   SCOPE
 9772:   @{ x @}
 9773:   ENDSCOPE
 9774: BEGIN
 9775: [ 1 cs-roll ] THEN
 9776:   ...
 9777: UNTIL
 9778: @end example
 9779: 
 9780: Since the guess is optimistic, there will be no spurious error messages
 9781: about undefined locals.
 9782: 
 9783: If the @code{BEGIN} is not reachable from above (e.g., after
 9784: @code{AHEAD} or @code{EXIT}), the compiler cannot even make an
 9785: optimistic guess, as the locals visible after the @code{BEGIN} may be
 9786: defined later. Therefore, the compiler assumes that no locals are
 9787: visible after the @code{BEGIN}. However, the user can use
 9788: @code{ASSUME-LIVE} to make the compiler assume that the same locals are
 9789: visible at the BEGIN as at the point where the top control-flow stack
 9790: item was created.
 9791: 
 9792: 
 9793: doc-assume-live
 9794: 
 9795: 
 9796: @noindent
 9797: E.g.,
 9798: @example
 9799: @{ x @}
 9800: AHEAD
 9801: ASSUME-LIVE
 9802: BEGIN
 9803:   x
 9804: [ 1 CS-ROLL ] THEN
 9805:   ...
 9806: UNTIL
 9807: @end example
 9808: 
 9809: Other cases where the locals are defined before the @code{BEGIN} can be
 9810: handled by inserting an appropriate @code{CS-ROLL} before the
 9811: @code{ASSUME-LIVE} (and changing the control-flow stack manipulation
 9812: behind the @code{ASSUME-LIVE}).
 9813: 
 9814: Cases where locals are defined after the @code{BEGIN} (but should be
 9815: visible immediately after the @code{BEGIN}) can only be handled by
 9816: rearranging the loop. E.g., the ``most insidious'' example above can be
 9817: arranged into:
 9818: @example
 9819: BEGIN
 9820:   @{ x @}
 9821:   ... 0=
 9822: WHILE
 9823:   x
 9824: REPEAT
 9825: @end example
 9826: 
 9827: @node How long do locals live?, Locals programming style, Where are locals visible by name?, Gforth locals
 9828: @subsubsection How long do locals live?
 9829: @cindex locals lifetime
 9830: @cindex lifetime of locals
 9831: 
 9832: The right answer for the lifetime question would be: A local lives at
 9833: least as long as it can be accessed. For a value-flavoured local this
 9834: means: until the end of its visibility. However, a variable-flavoured
 9835: local could be accessed through its address far beyond its visibility
 9836: scope. Ultimately, this would mean that such locals would have to be
 9837: garbage collected. Since this entails un-Forth-like implementation
 9838: complexities, I adopted the same cowardly solution as some other
 9839: languages (e.g., C): The local lives only as long as it is visible;
 9840: afterwards its address is invalid (and programs that access it
 9841: afterwards are erroneous).
 9842: 
 9843: @node Locals programming style, Locals implementation, How long do locals live?, Gforth locals
 9844: @subsubsection Locals programming style
 9845: @cindex locals programming style
 9846: @cindex programming style, locals
 9847: 
 9848: The freedom to define locals anywhere has the potential to change
 9849: programming styles dramatically. In particular, the need to use the
 9850: return stack for intermediate storage vanishes. Moreover, all stack
 9851: manipulations (except @code{PICK}s and @code{ROLL}s with run-time
 9852: determined arguments) can be eliminated: If the stack items are in the
 9853: wrong order, just write a locals definition for all of them; then
 9854: write the items in the order you want.
 9855: 
 9856: This seems a little far-fetched and eliminating stack manipulations is
 9857: unlikely to become a conscious programming objective. Still, the number
 9858: of stack manipulations will be reduced dramatically if local variables
 9859: are used liberally (e.g., compare @code{max} (@pxref{Gforth locals}) with
 9860: a traditional implementation of @code{max}).
 9861: 
 9862: This shows one potential benefit of locals: making Forth programs more
 9863: readable. Of course, this benefit will only be realized if the
 9864: programmers continue to honour the principle of factoring instead of
 9865: using the added latitude to make the words longer.
 9866: 
 9867: @cindex single-assignment style for locals
 9868: Using @code{TO} can and should be avoided.  Without @code{TO},
 9869: every value-flavoured local has only a single assignment and many
 9870: advantages of functional languages apply to Forth. I.e., programs are
 9871: easier to analyse, to optimize and to read: It is clear from the
 9872: definition what the local stands for, it does not turn into something
 9873: different later.
 9874: 
 9875: E.g., a definition using @code{TO} might look like this:
 9876: @example
 9877: : strcmp @{ addr1 u1 addr2 u2 -- n @}
 9878:  u1 u2 min 0
 9879:  ?do
 9880:    addr1 c@@ addr2 c@@ -
 9881:    ?dup-if
 9882:      unloop exit
 9883:    then
 9884:    addr1 char+ TO addr1
 9885:    addr2 char+ TO addr2
 9886:  loop
 9887:  u1 u2 - ;
 9888: @end example
 9889: Here, @code{TO} is used to update @code{addr1} and @code{addr2} at
 9890: every loop iteration. @code{strcmp} is a typical example of the
 9891: readability problems of using @code{TO}. When you start reading
 9892: @code{strcmp}, you think that @code{addr1} refers to the start of the
 9893: string. Only near the end of the loop you realize that it is something
 9894: else.
 9895: 
 9896: This can be avoided by defining two locals at the start of the loop that
 9897: are initialized with the right value for the current iteration.
 9898: @example
 9899: : strcmp @{ addr1 u1 addr2 u2 -- n @}
 9900:  addr1 addr2
 9901:  u1 u2 min 0 
 9902:  ?do @{ s1 s2 @}
 9903:    s1 c@@ s2 c@@ -
 9904:    ?dup-if
 9905:      unloop exit
 9906:    then
 9907:    s1 char+ s2 char+
 9908:  loop
 9909:  2drop
 9910:  u1 u2 - ;
 9911: @end example
 9912: Here it is clear from the start that @code{s1} has a different value
 9913: in every loop iteration.
 9914: 
 9915: @node Locals implementation,  , Locals programming style, Gforth locals
 9916: @subsubsection Locals implementation
 9917: @cindex locals implementation
 9918: @cindex implementation of locals
 9919: 
 9920: @cindex locals stack
 9921: Gforth uses an extra locals stack. The most compelling reason for
 9922: this is that the return stack is not float-aligned; using an extra stack
 9923: also eliminates the problems and restrictions of using the return stack
 9924: as locals stack. Like the other stacks, the locals stack grows toward
 9925: lower addresses. A few primitives allow an efficient implementation:
 9926: 
 9927: 
 9928: doc-@local#
 9929: doc-f@local#
 9930: doc-laddr#
 9931: doc-lp+!#
 9932: doc-lp!
 9933: doc->l
 9934: doc-f>l
 9935: 
 9936: 
 9937: In addition to these primitives, some specializations of these
 9938: primitives for commonly occurring inline arguments are provided for
 9939: efficiency reasons, e.g., @code{@@local0} as specialization of
 9940: @code{@@local#} for the inline argument 0. The following compiling words
 9941: compile the right specialized version, or the general version, as
 9942: appropriate:
 9943: 
 9944: 
 9945: @c doc-compile-@local
 9946: @c doc-compile-f@local
 9947: doc-compile-lp+!
 9948: 
 9949: 
 9950: Combinations of conditional branches and @code{lp+!#} like
 9951: @code{?branch-lp+!#} (the locals pointer is only changed if the branch
 9952: is taken) are provided for efficiency and correctness in loops.
 9953: 
 9954: A special area in the dictionary space is reserved for keeping the
 9955: local variable names. @code{@{} switches the dictionary pointer to this
 9956: area and @code{@}} switches it back and generates the locals
 9957: initializing code. @code{W:} etc.@ are normal defining words. This
 9958: special area is cleared at the start of every colon definition.
 9959: 
 9960: @cindex word list for defining locals
 9961: A special feature of Gforth's dictionary is used to implement the
 9962: definition of locals without type specifiers: every word list (aka
 9963: vocabulary) has its own methods for searching
 9964: etc. (@pxref{Word Lists}). For the present purpose we defined a word list
 9965: with a special search method: When it is searched for a word, it
 9966: actually creates that word using @code{W:}. @code{@{} changes the search
 9967: order to first search the word list containing @code{@}}, @code{W:} etc.,
 9968: and then the word list for defining locals without type specifiers.
 9969: 
 9970: The lifetime rules support a stack discipline within a colon
 9971: definition: The lifetime of a local is either nested with other locals
 9972: lifetimes or it does not overlap them.
 9973: 
 9974: At @code{BEGIN}, @code{IF}, and @code{AHEAD} no code for locals stack
 9975: pointer manipulation is generated. Between control structure words
 9976: locals definitions can push locals onto the locals stack. @code{AGAIN}
 9977: is the simplest of the other three control flow words. It has to
 9978: restore the locals stack depth of the corresponding @code{BEGIN}
 9979: before branching. The code looks like this:
 9980: @format
 9981: @code{lp+!#} current-locals-size @minus{} dest-locals-size
 9982: @code{branch} <begin>
 9983: @end format
 9984: 
 9985: @code{UNTIL} is a little more complicated: If it branches back, it
 9986: must adjust the stack just like @code{AGAIN}. But if it falls through,
 9987: the locals stack must not be changed. The compiler generates the
 9988: following code:
 9989: @format
 9990: @code{?branch-lp+!#} <begin> current-locals-size @minus{} dest-locals-size
 9991: @end format
 9992: The locals stack pointer is only adjusted if the branch is taken.
 9993: 
 9994: @code{THEN} can produce somewhat inefficient code:
 9995: @format
 9996: @code{lp+!#} current-locals-size @minus{} orig-locals-size
 9997: <orig target>:
 9998: @code{lp+!#} orig-locals-size @minus{} new-locals-size
 9999: @end format
10000: The second @code{lp+!#} adjusts the locals stack pointer from the
10001: level at the @i{orig} point to the level after the @code{THEN}. The
10002: first @code{lp+!#} adjusts the locals stack pointer from the current
10003: level to the level at the orig point, so the complete effect is an
10004: adjustment from the current level to the right level after the
10005: @code{THEN}.
10006: 
10007: @cindex locals information on the control-flow stack
10008: @cindex control-flow stack items, locals information
10009: In a conventional Forth implementation a dest control-flow stack entry
10010: is just the target address and an orig entry is just the address to be
10011: patched. Our locals implementation adds a word list to every orig or dest
10012: item. It is the list of locals visible (or assumed visible) at the point
10013: described by the entry. Our implementation also adds a tag to identify
10014: the kind of entry, in particular to differentiate between live and dead
10015: (reachable and unreachable) orig entries.
10016: 
10017: A few unusual operations have to be performed on locals word lists:
10018: 
10019: 
10020: doc-common-list
10021: doc-sub-list?
10022: doc-list-size
10023: 
10024: 
10025: Several features of our locals word list implementation make these
10026: operations easy to implement: The locals word lists are organised as
10027: linked lists; the tails of these lists are shared, if the lists
10028: contain some of the same locals; and the address of a name is greater
10029: than the address of the names behind it in the list.
10030: 
10031: Another important implementation detail is the variable
10032: @code{dead-code}. It is used by @code{BEGIN} and @code{THEN} to
10033: determine if they can be reached directly or only through the branch
10034: that they resolve. @code{dead-code} is set by @code{UNREACHABLE},
10035: @code{AHEAD}, @code{EXIT} etc., and cleared at the start of a colon
10036: definition, by @code{BEGIN} and usually by @code{THEN}.
10037: 
10038: Counted loops are similar to other loops in most respects, but
10039: @code{LEAVE} requires special attention: It performs basically the same
10040: service as @code{AHEAD}, but it does not create a control-flow stack
10041: entry. Therefore the information has to be stored elsewhere;
10042: traditionally, the information was stored in the target fields of the
10043: branches created by the @code{LEAVE}s, by organizing these fields into a
10044: linked list. Unfortunately, this clever trick does not provide enough
10045: space for storing our extended control flow information. Therefore, we
10046: introduce another stack, the leave stack. It contains the control-flow
10047: stack entries for all unresolved @code{LEAVE}s.
10048: 
10049: Local names are kept until the end of the colon definition, even if
10050: they are no longer visible in any control-flow path. In a few cases
10051: this may lead to increased space needs for the locals name area, but
10052: usually less than reclaiming this space would cost in code size.
10053: 
10054: 
10055: @node ANS Forth locals,  , Gforth locals, Locals
10056: @subsection ANS Forth locals
10057: @cindex locals, ANS Forth style
10058: 
10059: The ANS Forth locals wordset does not define a syntax for locals, but
10060: words that make it possible to define various syntaxes. One of the
10061: possible syntaxes is a subset of the syntax we used in the Gforth locals
10062: wordset, i.e.:
10063: 
10064: @example
10065: @{ local1 local2 ... -- comment @}
10066: @end example
10067: @noindent
10068: or
10069: @example
10070: @{ local1 local2 ... @}
10071: @end example
10072: 
10073: The order of the locals corresponds to the order in a stack comment. The
10074: restrictions are:
10075: 
10076: @itemize @bullet
10077: @item
10078: Locals can only be cell-sized values (no type specifiers are allowed).
10079: @item
10080: Locals can be defined only outside control structures.
10081: @item
10082: Locals can interfere with explicit usage of the return stack. For the
10083: exact (and long) rules, see the standard. If you don't use return stack
10084: accessing words in a definition using locals, you will be all right. The
10085: purpose of this rule is to make locals implementation on the return
10086: stack easier.
10087: @item
10088: The whole definition must be in one line.
10089: @end itemize
10090: 
10091: Locals defined in ANS Forth behave like @code{VALUE}s
10092: (@pxref{Values}). I.e., they are initialized from the stack. Using their
10093: name produces their value. Their value can be changed using @code{TO}.
10094: 
10095: Since the syntax above is supported by Gforth directly, you need not do
10096: anything to use it. If you want to port a program using this syntax to
10097: another ANS Forth system, use @file{compat/anslocal.fs} to implement the
10098: syntax on the other system.
10099: 
10100: Note that a syntax shown in the standard, section A.13 looks
10101: similar, but is quite different in having the order of locals
10102: reversed. Beware!
10103: 
10104: The ANS Forth locals wordset itself consists of one word:
10105: 
10106: doc-(local)
10107: 
10108: The ANS Forth locals extension wordset defines a syntax using
10109: @code{locals|}, but it is so awful that we strongly recommend not to use
10110: it. We have implemented this syntax to make porting to Gforth easy, but
10111: do not document it here. The problem with this syntax is that the locals
10112: are defined in an order reversed with respect to the standard stack
10113: comment notation, making programs harder to read, and easier to misread
10114: and miswrite. The only merit of this syntax is that it is easy to
10115: implement using the ANS Forth locals wordset.
10116: 
10117: 
10118: @c ----------------------------------------------------------
10119: @node Structures, Object-oriented Forth, Locals, Words
10120: @section  Structures
10121: @cindex structures
10122: @cindex records
10123: 
10124: This section presents the structure package that comes with Gforth. A
10125: version of the package implemented in ANS Forth is available in
10126: @file{compat/struct.fs}. This package was inspired by a posting on
10127: comp.lang.forth in 1989 (unfortunately I don't remember, by whom;
10128: possibly John Hayes). A version of this section has been published in
10129: M. Anton Ertl,
10130: @uref{http://www.complang.tuwien.ac.at/forth/objects/structs.html, Yet
10131: Another Forth Structures Package}, Forth Dimensions 19(3), pages
10132: 13--16. Marcel Hendrix provided helpful comments.
10133: 
10134: @menu
10135: * Why explicit structure support?::  
10136: * Structure Usage::             
10137: * Structure Naming Convention::  
10138: * Structure Implementation::    
10139: * Structure Glossary::          
10140: * Forth200x Structures::        
10141: @end menu
10142: 
10143: @node Why explicit structure support?, Structure Usage, Structures, Structures
10144: @subsection Why explicit structure support?
10145: 
10146: @cindex address arithmetic for structures
10147: @cindex structures using address arithmetic
10148: If we want to use a structure containing several fields, we could simply
10149: reserve memory for it, and access the fields using address arithmetic
10150: (@pxref{Address arithmetic}). As an example, consider a structure with
10151: the following fields
10152: 
10153: @table @code
10154: @item a
10155: is a float
10156: @item b
10157: is a cell
10158: @item c
10159: is a float
10160: @end table
10161: 
10162: Given the (float-aligned) base address of the structure we get the
10163: address of the field
10164: 
10165: @table @code
10166: @item a
10167: without doing anything further.
10168: @item b
10169: with @code{float+}
10170: @item c
10171: with @code{float+ cell+ faligned}
10172: @end table
10173: 
10174: It is easy to see that this can become quite tiring. 
10175: 
10176: Moreover, it is not very readable, because seeing a
10177: @code{cell+} tells us neither which kind of structure is
10178: accessed nor what field is accessed; we have to somehow infer the kind
10179: of structure, and then look up in the documentation, which field of
10180: that structure corresponds to that offset.
10181: 
10182: Finally, this kind of address arithmetic also causes maintenance
10183: troubles: If you add or delete a field somewhere in the middle of the
10184: structure, you have to find and change all computations for the fields
10185: afterwards.
10186: 
10187: So, instead of using @code{cell+} and friends directly, how
10188: about storing the offsets in constants:
10189: 
10190: @example
10191: 0 constant a-offset
10192: 0 float+ constant b-offset
10193: 0 float+ cell+ faligned c-offset
10194: @end example
10195: 
10196: Now we can get the address of field @code{x} with @code{x-offset
10197: +}. This is much better in all respects. Of course, you still
10198: have to change all later offset definitions if you add a field. You can
10199: fix this by declaring the offsets in the following way:
10200: 
10201: @example
10202: 0 constant a-offset
10203: a-offset float+ constant b-offset
10204: b-offset cell+ faligned constant c-offset
10205: @end example
10206: 
10207: Since we always use the offsets with @code{+}, we could use a defining
10208: word @code{cfield} that includes the @code{+} in the action of the
10209: defined word:
10210: 
10211: @example
10212: : cfield ( n "name" -- )
10213:     create ,
10214: does> ( name execution: addr1 -- addr2 )
10215:     @@ + ;
10216: 
10217: 0 cfield a
10218: 0 a float+ cfield b
10219: 0 b cell+ faligned cfield c
10220: @end example
10221: 
10222: Instead of @code{x-offset +}, we now simply write @code{x}.
10223: 
10224: The structure field words now can be used quite nicely. However,
10225: their definition is still a bit cumbersome: We have to repeat the
10226: name, the information about size and alignment is distributed before
10227: and after the field definitions etc.  The structure package presented
10228: here addresses these problems.
10229: 
10230: @node Structure Usage, Structure Naming Convention, Why explicit structure support?, Structures
10231: @subsection Structure Usage
10232: @cindex structure usage
10233: 
10234: @cindex @code{field} usage
10235: @cindex @code{struct} usage
10236: @cindex @code{end-struct} usage
10237: You can define a structure for a (data-less) linked list with:
10238: @example
10239: struct
10240:     cell% field list-next
10241: end-struct list%
10242: @end example
10243: 
10244: With the address of the list node on the stack, you can compute the
10245: address of the field that contains the address of the next node with
10246: @code{list-next}. E.g., you can determine the length of a list
10247: with:
10248: 
10249: @example
10250: : list-length ( list -- n )
10251: \ "list" is a pointer to the first element of a linked list
10252: \ "n" is the length of the list
10253:     0 BEGIN ( list1 n1 )
10254:         over
10255:     WHILE ( list1 n1 )
10256:         1+ swap list-next @@ swap
10257:     REPEAT
10258:     nip ;
10259: @end example
10260: 
10261: You can reserve memory for a list node in the dictionary with
10262: @code{list% %allot}, which leaves the address of the list node on the
10263: stack. For the equivalent allocation on the heap you can use @code{list%
10264: %alloc} (or, for an @code{allocate}-like stack effect (i.e., with ior),
10265: use @code{list% %allocate}). You can get the the size of a list
10266: node with @code{list% %size} and its alignment with @code{list%
10267: %alignment}.
10268: 
10269: Note that in ANS Forth the body of a @code{create}d word is
10270: @code{aligned} but not necessarily @code{faligned};
10271: therefore, if you do a:
10272: 
10273: @example
10274: create @emph{name} foo% %allot drop
10275: @end example
10276: 
10277: @noindent
10278: then the memory alloted for @code{foo%} is guaranteed to start at the
10279: body of @code{@emph{name}} only if @code{foo%} contains only character,
10280: cell and double fields.  Therefore, if your structure contains floats,
10281: better use
10282: 
10283: @example
10284: foo% %allot constant @emph{name}
10285: @end example
10286: 
10287: @cindex structures containing structures
10288: You can include a structure @code{foo%} as a field of
10289: another structure, like this:
10290: @example
10291: struct
10292: ...
10293:     foo% field ...
10294: ...
10295: end-struct ...
10296: @end example
10297: 
10298: @cindex structure extension
10299: @cindex extended records
10300: Instead of starting with an empty structure, you can extend an
10301: existing structure. E.g., a plain linked list without data, as defined
10302: above, is hardly useful; You can extend it to a linked list of integers,
10303: like this:@footnote{This feature is also known as @emph{extended
10304: records}. It is the main innovation in the Oberon language; in other
10305: words, adding this feature to Modula-2 led Wirth to create a new
10306: language, write a new compiler etc.  Adding this feature to Forth just
10307: required a few lines of code.}
10308: 
10309: @example
10310: list%
10311:     cell% field intlist-int
10312: end-struct intlist%
10313: @end example
10314: 
10315: @code{intlist%} is a structure with two fields:
10316: @code{list-next} and @code{intlist-int}.
10317: 
10318: @cindex structures containing arrays
10319: You can specify an array type containing @emph{n} elements of
10320: type @code{foo%} like this:
10321: 
10322: @example
10323: foo% @emph{n} *
10324: @end example
10325: 
10326: You can use this array type in any place where you can use a normal
10327: type, e.g., when defining a @code{field}, or with
10328: @code{%allot}.
10329: 
10330: @cindex first field optimization
10331: The first field is at the base address of a structure and the word for
10332: this field (e.g., @code{list-next}) actually does not change the address
10333: on the stack. You may be tempted to leave it away in the interest of
10334: run-time and space efficiency. This is not necessary, because the
10335: structure package optimizes this case: If you compile a first-field
10336: words, no code is generated. So, in the interest of readability and
10337: maintainability you should include the word for the field when accessing
10338: the field.
10339: 
10340: 
10341: @node Structure Naming Convention, Structure Implementation, Structure Usage, Structures
10342: @subsection Structure Naming Convention
10343: @cindex structure naming convention
10344: 
10345: The field names that come to (my) mind are often quite generic, and,
10346: if used, would cause frequent name clashes. E.g., many structures
10347: probably contain a @code{counter} field. The structure names
10348: that come to (my) mind are often also the logical choice for the names
10349: of words that create such a structure.
10350: 
10351: Therefore, I have adopted the following naming conventions: 
10352: 
10353: @itemize @bullet
10354: @cindex field naming convention
10355: @item
10356: The names of fields are of the form
10357: @code{@emph{struct}-@emph{field}}, where
10358: @code{@emph{struct}} is the basic name of the structure, and
10359: @code{@emph{field}} is the basic name of the field. You can
10360: think of field words as converting the (address of the)
10361: structure into the (address of the) field.
10362: 
10363: @cindex structure naming convention
10364: @item
10365: The names of structures are of the form
10366: @code{@emph{struct}%}, where
10367: @code{@emph{struct}} is the basic name of the structure.
10368: @end itemize
10369: 
10370: This naming convention does not work that well for fields of extended
10371: structures; e.g., the integer list structure has a field
10372: @code{intlist-int}, but has @code{list-next}, not
10373: @code{intlist-next}.
10374: 
10375: @node Structure Implementation, Structure Glossary, Structure Naming Convention, Structures
10376: @subsection Structure Implementation
10377: @cindex structure implementation
10378: @cindex implementation of structures
10379: 
10380: The central idea in the implementation is to pass the data about the
10381: structure being built on the stack, not in some global
10382: variable. Everything else falls into place naturally once this design
10383: decision is made.
10384: 
10385: The type description on the stack is of the form @emph{align
10386: size}. Keeping the size on the top-of-stack makes dealing with arrays
10387: very simple.
10388: 
10389: @code{field} is a defining word that uses @code{Create}
10390: and @code{DOES>}. The body of the field contains the offset
10391: of the field, and the normal @code{DOES>} action is simply:
10392: 
10393: @example
10394: @@ +
10395: @end example
10396: 
10397: @noindent
10398: i.e., add the offset to the address, giving the stack effect
10399: @i{addr1 -- addr2} for a field.
10400: 
10401: @cindex first field optimization, implementation
10402: This simple structure is slightly complicated by the optimization
10403: for fields with offset 0, which requires a different
10404: @code{DOES>}-part (because we cannot rely on there being
10405: something on the stack if such a field is invoked during
10406: compilation). Therefore, we put the different @code{DOES>}-parts
10407: in separate words, and decide which one to invoke based on the
10408: offset. For a zero offset, the field is basically a noop; it is
10409: immediate, and therefore no code is generated when it is compiled.
10410: 
10411: @node Structure Glossary, Forth200x Structures, Structure Implementation, Structures
10412: @subsection Structure Glossary
10413: @cindex structure glossary
10414: 
10415: 
10416: doc-%align
10417: doc-%alignment
10418: doc-%alloc
10419: doc-%allocate
10420: doc-%allot
10421: doc-cell%
10422: doc-char%
10423: doc-dfloat%
10424: doc-double%
10425: doc-end-struct
10426: doc-field
10427: doc-float%
10428: doc-naligned
10429: doc-sfloat%
10430: doc-%size
10431: doc-struct
10432: 
10433: 
10434: @node Forth200x Structures,  , Structure Glossary, Structures
10435: @subsection Forth200x Structures
10436: @cindex Structures in Forth200x
10437: 
10438: The Forth 200x standard defines a slightly less convenient form of
10439: structures.  In general (when using @code{field+}, you have to perform
10440: the alignment yourself, but there are a number of convenience words
10441: (e.g., @code{field:} that perform the alignment for you.
10442: 
10443: A typical usage example is:
10444: 
10445: @example
10446: 0
10447:   field:                   s-a
10448:   faligned 2 floats +field s-b
10449: constant s-struct
10450: @end example
10451: 
10452: An alternative way of writing this structure is:
10453: 
10454: @example
10455: begin-structure s-struct
10456:   field:                   s-a
10457:   faligned 2 floats +field s-b
10458: end-structure
10459: @end example
10460: 
10461: doc-begin-structure
10462: doc-end-structure
10463: doc-+field
10464: doc-cfield:
10465: doc-field:
10466: doc-2field:
10467: doc-ffield:
10468: doc-sffield:
10469: doc-dffield:
10470: 
10471: @c -------------------------------------------------------------
10472: @node Object-oriented Forth, Programming Tools, Structures, Words
10473: @section Object-oriented Forth
10474: 
10475: Gforth comes with three packages for object-oriented programming:
10476: @file{objects.fs}, @file{oof.fs}, and @file{mini-oof.fs}; none of them
10477: is preloaded, so you have to @code{include} them before use. The most
10478: important differences between these packages (and others) are discussed
10479: in @ref{Comparison with other object models}. All packages are written
10480: in ANS Forth and can be used with any other ANS Forth.
10481: 
10482: @menu
10483: * Why object-oriented programming?::  
10484: * Object-Oriented Terminology::  
10485: * Objects::                     
10486: * OOF::                         
10487: * Mini-OOF::                    
10488: * Comparison with other object models::  
10489: @end menu
10490: 
10491: @c ----------------------------------------------------------------
10492: @node Why object-oriented programming?, Object-Oriented Terminology, Object-oriented Forth, Object-oriented Forth
10493: @subsection Why object-oriented programming?
10494: @cindex object-oriented programming motivation
10495: @cindex motivation for object-oriented programming
10496: 
10497: Often we have to deal with several data structures (@emph{objects}),
10498: that have to be treated similarly in some respects, but differently in
10499: others. Graphical objects are the textbook example: circles, triangles,
10500: dinosaurs, icons, and others, and we may want to add more during program
10501: development. We want to apply some operations to any graphical object,
10502: e.g., @code{draw} for displaying it on the screen. However, @code{draw}
10503: has to do something different for every kind of object.
10504: @comment TODO add some other operations eg perimeter, area
10505: @comment and tie in to concrete examples later..
10506: 
10507: We could implement @code{draw} as a big @code{CASE}
10508: control structure that executes the appropriate code depending on the
10509: kind of object to be drawn. This would be not be very elegant, and,
10510: moreover, we would have to change @code{draw} every time we add
10511: a new kind of graphical object (say, a spaceship).
10512: 
10513: What we would rather do is: When defining spaceships, we would tell
10514: the system: ``Here's how you @code{draw} a spaceship; you figure
10515: out the rest''.
10516: 
10517: This is the problem that all systems solve that (rightfully) call
10518: themselves object-oriented; the object-oriented packages presented here
10519: solve this problem (and not much else).
10520: @comment TODO ?list properties of oo systems.. oo vs o-based?
10521: 
10522: @c ------------------------------------------------------------------------
10523: @node Object-Oriented Terminology, Objects, Why object-oriented programming?, Object-oriented Forth
10524: @subsection Object-Oriented Terminology
10525: @cindex object-oriented terminology
10526: @cindex terminology for object-oriented programming
10527: 
10528: This section is mainly for reference, so you don't have to understand
10529: all of it right away.  The terminology is mainly Smalltalk-inspired.  In
10530: short:
10531: 
10532: @table @emph
10533: @cindex class
10534: @item class
10535: a data structure definition with some extras.
10536: 
10537: @cindex object
10538: @item object
10539: an instance of the data structure described by the class definition.
10540: 
10541: @cindex instance variables
10542: @item instance variables
10543: fields of the data structure.
10544: 
10545: @cindex selector
10546: @cindex method selector
10547: @cindex virtual function
10548: @item selector
10549: (or @emph{method selector}) a word (e.g.,
10550: @code{draw}) that performs an operation on a variety of data
10551: structures (classes). A selector describes @emph{what} operation to
10552: perform. In C++ terminology: a (pure) virtual function.
10553: 
10554: @cindex method
10555: @item method
10556: the concrete definition that performs the operation
10557: described by the selector for a specific class. A method specifies
10558: @emph{how} the operation is performed for a specific class.
10559: 
10560: @cindex selector invocation
10561: @cindex message send
10562: @cindex invoking a selector
10563: @item selector invocation
10564: a call of a selector. One argument of the call (the TOS (top-of-stack))
10565: is used for determining which method is used. In Smalltalk terminology:
10566: a message (consisting of the selector and the other arguments) is sent
10567: to the object.
10568: 
10569: @cindex receiving object
10570: @item receiving object
10571: the object used for determining the method executed by a selector
10572: invocation. In the @file{objects.fs} model, it is the object that is on
10573: the TOS when the selector is invoked. (@emph{Receiving} comes from
10574: the Smalltalk @emph{message} terminology.)
10575: 
10576: @cindex child class
10577: @cindex parent class
10578: @cindex inheritance
10579: @item child class
10580: a class that has (@emph{inherits}) all properties (instance variables,
10581: selectors, methods) from a @emph{parent class}. In Smalltalk
10582: terminology: The subclass inherits from the superclass. In C++
10583: terminology: The derived class inherits from the base class.
10584: 
10585: @end table
10586: 
10587: @c If you wonder about the message sending terminology, it comes from
10588: @c a time when each object had it's own task and objects communicated via
10589: @c message passing; eventually the Smalltalk developers realized that
10590: @c they can do most things through simple (indirect) calls. They kept the
10591: @c terminology.
10592: 
10593: @c --------------------------------------------------------------
10594: @node Objects, OOF, Object-Oriented Terminology, Object-oriented Forth
10595: @subsection The @file{objects.fs} model
10596: @cindex objects
10597: @cindex object-oriented programming
10598: 
10599: @cindex @file{objects.fs}
10600: @cindex @file{oof.fs}
10601: 
10602: This section describes the @file{objects.fs} package. This material also
10603: has been published in M. Anton Ertl,
10604: @cite{@uref{http://www.complang.tuwien.ac.at/forth/objects/objects.html,
10605: Yet Another Forth Objects Package}}, Forth Dimensions 19(2), pages
10606: 37--43.
10607: @c McKewan's and Zsoter's packages
10608: 
10609: This section assumes that you have read @ref{Structures}.
10610: 
10611: The techniques on which this model is based have been used to implement
10612: the parser generator, Gray, and have also been used in Gforth for
10613: implementing the various flavours of word lists (hashed or not,
10614: case-sensitive or not, special-purpose word lists for locals etc.).
10615: 
10616: 
10617: @menu
10618: * Properties of the Objects model::  
10619: * Basic Objects Usage::         
10620: * The Objects base class::      
10621: * Creating objects::            
10622: * Object-Oriented Programming Style::  
10623: * Class Binding::               
10624: * Method conveniences::         
10625: * Classes and Scoping::         
10626: * Dividing classes::            
10627: * Object Interfaces::           
10628: * Objects Implementation::      
10629: * Objects Glossary::            
10630: @end menu
10631: 
10632: Marcel Hendrix provided helpful comments on this section.
10633: 
10634: @node Properties of the Objects model, Basic Objects Usage, Objects, Objects
10635: @subsubsection Properties of the @file{objects.fs} model
10636: @cindex @file{objects.fs} properties
10637: 
10638: @itemize @bullet
10639: @item
10640: It is straightforward to pass objects on the stack. Passing
10641: selectors on the stack is a little less convenient, but possible.
10642: 
10643: @item
10644: Objects are just data structures in memory, and are referenced by their
10645: address. You can create words for objects with normal defining words
10646: like @code{constant}. Likewise, there is no difference between instance
10647: variables that contain objects and those that contain other data.
10648: 
10649: @item
10650: Late binding is efficient and easy to use.
10651: 
10652: @item
10653: It avoids parsing, and thus avoids problems with state-smartness
10654: and reduced extensibility; for convenience there are a few parsing
10655: words, but they have non-parsing counterparts. There are also a few
10656: defining words that parse. This is hard to avoid, because all standard
10657: defining words parse (except @code{:noname}); however, such
10658: words are not as bad as many other parsing words, because they are not
10659: state-smart.
10660: 
10661: @item
10662: It does not try to incorporate everything. It does a few things and does
10663: them well (IMO). In particular, this model was not designed to support
10664: information hiding (although it has features that may help); you can use
10665: a separate package for achieving this.
10666: 
10667: @item
10668: It is layered; you don't have to learn and use all features to use this
10669: model. Only a few features are necessary (@pxref{Basic Objects Usage},
10670: @pxref{The Objects base class}, @pxref{Creating objects}.), the others
10671: are optional and independent of each other.
10672: 
10673: @item
10674: An implementation in ANS Forth is available.
10675: 
10676: @end itemize
10677: 
10678: 
10679: @node Basic Objects Usage, The Objects base class, Properties of the Objects model, Objects
10680: @subsubsection Basic @file{objects.fs} Usage
10681: @cindex basic objects usage
10682: @cindex objects, basic usage
10683: 
10684: You can define a class for graphical objects like this:
10685: 
10686: @cindex @code{class} usage
10687: @cindex @code{end-class} usage
10688: @cindex @code{selector} usage
10689: @example
10690: object class \ "object" is the parent class
10691:   selector draw ( x y graphical -- )
10692: end-class graphical
10693: @end example
10694: 
10695: This code defines a class @code{graphical} with an
10696: operation @code{draw}.  We can perform the operation
10697: @code{draw} on any @code{graphical} object, e.g.:
10698: 
10699: @example
10700: 100 100 t-rex draw
10701: @end example
10702: 
10703: @noindent
10704: where @code{t-rex} is a word (say, a constant) that produces a
10705: graphical object.
10706: 
10707: @comment TODO add a 2nd operation eg perimeter.. and use for
10708: @comment a concrete example
10709: 
10710: @cindex abstract class
10711: How do we create a graphical object? With the present definitions,
10712: we cannot create a useful graphical object. The class
10713: @code{graphical} describes graphical objects in general, but not
10714: any concrete graphical object type (C++ users would call it an
10715: @emph{abstract class}); e.g., there is no method for the selector
10716: @code{draw} in the class @code{graphical}.
10717: 
10718: For concrete graphical objects, we define child classes of the
10719: class @code{graphical}, e.g.:
10720: 
10721: @cindex @code{overrides} usage
10722: @cindex @code{field} usage in class definition
10723: @example
10724: graphical class \ "graphical" is the parent class
10725:   cell% field circle-radius
10726: 
10727: :noname ( x y circle -- )
10728:   circle-radius @@ draw-circle ;
10729: overrides draw
10730: 
10731: :noname ( n-radius circle -- )
10732:   circle-radius ! ;
10733: overrides construct
10734: 
10735: end-class circle
10736: @end example
10737: 
10738: Here we define a class @code{circle} as a child of @code{graphical},
10739: with field @code{circle-radius} (which behaves just like a field
10740: (@pxref{Structures}); it defines (using @code{overrides}) new methods
10741: for the selectors @code{draw} and @code{construct} (@code{construct} is
10742: defined in @code{object}, the parent class of @code{graphical}).
10743: 
10744: Now we can create a circle on the heap (i.e.,
10745: @code{allocate}d memory) with:
10746: 
10747: @cindex @code{heap-new} usage
10748: @example
10749: 50 circle heap-new constant my-circle
10750: @end example
10751: 
10752: @noindent
10753: @code{heap-new} invokes @code{construct}, thus
10754: initializing the field @code{circle-radius} with 50. We can draw
10755: this new circle at (100,100) with:
10756: 
10757: @example
10758: 100 100 my-circle draw
10759: @end example
10760: 
10761: @cindex selector invocation, restrictions
10762: @cindex class definition, restrictions
10763: Note: You can only invoke a selector if the object on the TOS
10764: (the receiving object) belongs to the class where the selector was
10765: defined or one of its descendents; e.g., you can invoke
10766: @code{draw} only for objects belonging to @code{graphical}
10767: or its descendents (e.g., @code{circle}).  Immediately before
10768: @code{end-class}, the search order has to be the same as
10769: immediately after @code{class}.
10770: 
10771: @node The Objects base class, Creating objects, Basic Objects Usage, Objects
10772: @subsubsection The @file{object.fs} base class
10773: @cindex @code{object} class
10774: 
10775: When you define a class, you have to specify a parent class.  So how do
10776: you start defining classes? There is one class available from the start:
10777: @code{object}. It is ancestor for all classes and so is the
10778: only class that has no parent. It has two selectors: @code{construct}
10779: and @code{print}.
10780: 
10781: @node Creating objects, Object-Oriented Programming Style, The Objects base class, Objects
10782: @subsubsection Creating objects
10783: @cindex creating objects
10784: @cindex object creation
10785: @cindex object allocation options
10786: 
10787: @cindex @code{heap-new} discussion
10788: @cindex @code{dict-new} discussion
10789: @cindex @code{construct} discussion
10790: You can create and initialize an object of a class on the heap with
10791: @code{heap-new} ( ... class -- object ) and in the dictionary
10792: (allocation with @code{allot}) with @code{dict-new} (
10793: ... class -- object ). Both words invoke @code{construct}, which
10794: consumes the stack items indicated by "..." above.
10795: 
10796: @cindex @code{init-object} discussion
10797: @cindex @code{class-inst-size} discussion
10798: If you want to allocate memory for an object yourself, you can get its
10799: alignment and size with @code{class-inst-size 2@@} ( class --
10800: align size ). Once you have memory for an object, you can initialize
10801: it with @code{init-object} ( ... class object -- );
10802: @code{construct} does only a part of the necessary work.
10803: 
10804: @node Object-Oriented Programming Style, Class Binding, Creating objects, Objects
10805: @subsubsection Object-Oriented Programming Style
10806: @cindex object-oriented programming style
10807: @cindex programming style, object-oriented
10808: 
10809: This section is not exhaustive.
10810: 
10811: @cindex stack effects of selectors
10812: @cindex selectors and stack effects
10813: In general, it is a good idea to ensure that all methods for the
10814: same selector have the same stack effect: when you invoke a selector,
10815: you often have no idea which method will be invoked, so, unless all
10816: methods have the same stack effect, you will not know the stack effect
10817: of the selector invocation.
10818: 
10819: One exception to this rule is methods for the selector
10820: @code{construct}. We know which method is invoked, because we
10821: specify the class to be constructed at the same place. Actually, I
10822: defined @code{construct} as a selector only to give the users a
10823: convenient way to specify initialization. The way it is used, a
10824: mechanism different from selector invocation would be more natural
10825: (but probably would take more code and more space to explain).
10826: 
10827: @node Class Binding, Method conveniences, Object-Oriented Programming Style, Objects
10828: @subsubsection Class Binding
10829: @cindex class binding
10830: @cindex early binding
10831: 
10832: @cindex late binding
10833: Normal selector invocations determine the method at run-time depending
10834: on the class of the receiving object. This run-time selection is called
10835: @i{late binding}.
10836: 
10837: Sometimes it's preferable to invoke a different method. For example,
10838: you might want to use the simple method for @code{print}ing
10839: @code{object}s instead of the possibly long-winded @code{print} method
10840: of the receiver class. You can achieve this by replacing the invocation
10841: of @code{print} with:
10842: 
10843: @cindex @code{[bind]} usage
10844: @example
10845: [bind] object print
10846: @end example
10847: 
10848: @noindent
10849: in compiled code or:
10850: 
10851: @cindex @code{bind} usage
10852: @example
10853: bind object print
10854: @end example
10855: 
10856: @cindex class binding, alternative to
10857: @noindent
10858: in interpreted code. Alternatively, you can define the method with a
10859: name (e.g., @code{print-object}), and then invoke it through the
10860: name. Class binding is just a (often more convenient) way to achieve
10861: the same effect; it avoids name clutter and allows you to invoke
10862: methods directly without naming them first.
10863: 
10864: @cindex superclass binding
10865: @cindex parent class binding
10866: A frequent use of class binding is this: When we define a method
10867: for a selector, we often want the method to do what the selector does
10868: in the parent class, and a little more. There is a special word for
10869: this purpose: @code{[parent]}; @code{[parent]
10870: @emph{selector}} is equivalent to @code{[bind] @emph{parent
10871: selector}}, where @code{@emph{parent}} is the parent
10872: class of the current class. E.g., a method definition might look like:
10873: 
10874: @cindex @code{[parent]} usage
10875: @example
10876: :noname
10877:   dup [parent] foo \ do parent's foo on the receiving object
10878:   ... \ do some more
10879: ; overrides foo
10880: @end example
10881: 
10882: @cindex class binding as optimization
10883: In @cite{Object-oriented programming in ANS Forth} (Forth Dimensions,
10884: March 1997), Andrew McKewan presents class binding as an optimization
10885: technique. I recommend not using it for this purpose unless you are in
10886: an emergency. Late binding is pretty fast with this model anyway, so the
10887: benefit of using class binding is small; the cost of using class binding
10888: where it is not appropriate is reduced maintainability.
10889: 
10890: While we are at programming style questions: You should bind
10891: selectors only to ancestor classes of the receiving object. E.g., say,
10892: you know that the receiving object is of class @code{foo} or its
10893: descendents; then you should bind only to @code{foo} and its
10894: ancestors.
10895: 
10896: @node Method conveniences, Classes and Scoping, Class Binding, Objects
10897: @subsubsection Method conveniences
10898: @cindex method conveniences
10899: 
10900: In a method you usually access the receiving object pretty often.  If
10901: you define the method as a plain colon definition (e.g., with
10902: @code{:noname}), you may have to do a lot of stack
10903: gymnastics. To avoid this, you can define the method with @code{m:
10904: ... ;m}. E.g., you could define the method for
10905: @code{draw}ing a @code{circle} with
10906: 
10907: @cindex @code{this} usage
10908: @cindex @code{m:} usage
10909: @cindex @code{;m} usage
10910: @example
10911: m: ( x y circle -- )
10912:   ( x y ) this circle-radius @@ draw-circle ;m
10913: @end example
10914: 
10915: @cindex @code{exit} in @code{m: ... ;m}
10916: @cindex @code{exitm} discussion
10917: @cindex @code{catch} in @code{m: ... ;m}
10918: When this method is executed, the receiver object is removed from the
10919: stack; you can access it with @code{this} (admittedly, in this
10920: example the use of @code{m: ... ;m} offers no advantage). Note
10921: that I specify the stack effect for the whole method (i.e. including
10922: the receiver object), not just for the code between @code{m:}
10923: and @code{;m}. You cannot use @code{exit} in
10924: @code{m:...;m}; instead, use
10925: @code{exitm}.@footnote{Moreover, for any word that calls
10926: @code{catch} and was defined before loading
10927: @code{objects.fs}, you have to redefine it like I redefined
10928: @code{catch}: @code{: catch this >r catch r> to-this ;}}
10929: 
10930: @cindex @code{inst-var} usage
10931: You will frequently use sequences of the form @code{this
10932: @emph{field}} (in the example above: @code{this
10933: circle-radius}). If you use the field only in this way, you can
10934: define it with @code{inst-var} and eliminate the
10935: @code{this} before the field name. E.g., the @code{circle}
10936: class above could also be defined with:
10937: 
10938: @example
10939: graphical class
10940:   cell% inst-var radius
10941: 
10942: m: ( x y circle -- )
10943:   radius @@ draw-circle ;m
10944: overrides draw
10945: 
10946: m: ( n-radius circle -- )
10947:   radius ! ;m
10948: overrides construct
10949: 
10950: end-class circle
10951: @end example
10952: 
10953: @code{radius} can only be used in @code{circle} and its
10954: descendent classes and inside @code{m:...;m}.
10955: 
10956: @cindex @code{inst-value} usage
10957: You can also define fields with @code{inst-value}, which is
10958: to @code{inst-var} what @code{value} is to
10959: @code{variable}.  You can change the value of such a field with
10960: @code{[to-inst]}.  E.g., we could also define the class
10961: @code{circle} like this:
10962: 
10963: @example
10964: graphical class
10965:   inst-value radius
10966: 
10967: m: ( x y circle -- )
10968:   radius draw-circle ;m
10969: overrides draw
10970: 
10971: m: ( n-radius circle -- )
10972:   [to-inst] radius ;m
10973: overrides construct
10974: 
10975: end-class circle
10976: @end example
10977: 
10978: @c !! :m is easy to confuse with m:.  Another name would be better.
10979: 
10980: @c Finally, you can define named methods with @code{:m}.  One use of this
10981: @c feature is the definition of words that occur only in one class and are
10982: @c not intended to be overridden, but which still need method context
10983: @c (e.g., for accessing @code{inst-var}s).  Another use is for methods that
10984: @c would be bound frequently, if defined anonymously.
10985: 
10986: 
10987: @node Classes and Scoping, Dividing classes, Method conveniences, Objects
10988: @subsubsection Classes and Scoping
10989: @cindex classes and scoping
10990: @cindex scoping and classes
10991: 
10992: Inheritance is frequent, unlike structure extension. This exacerbates
10993: the problem with the field name convention (@pxref{Structure Naming
10994: Convention}): One always has to remember in which class the field was
10995: originally defined; changing a part of the class structure would require
10996: changes for renaming in otherwise unaffected code.
10997: 
10998: @cindex @code{inst-var} visibility
10999: @cindex @code{inst-value} visibility
11000: To solve this problem, I added a scoping mechanism (which was not in my
11001: original charter): A field defined with @code{inst-var} (or
11002: @code{inst-value}) is visible only in the class where it is defined and in
11003: the descendent classes of this class.  Using such fields only makes
11004: sense in @code{m:}-defined methods in these classes anyway.
11005: 
11006: This scoping mechanism allows us to use the unadorned field name,
11007: because name clashes with unrelated words become much less likely.
11008: 
11009: @cindex @code{protected} discussion
11010: @cindex @code{private} discussion
11011: Once we have this mechanism, we can also use it for controlling the
11012: visibility of other words: All words defined after
11013: @code{protected} are visible only in the current class and its
11014: descendents. @code{public} restores the compilation
11015: (i.e. @code{current}) word list that was in effect before. If you
11016: have several @code{protected}s without an intervening
11017: @code{public} or @code{set-current}, @code{public}
11018: will restore the compilation word list in effect before the first of
11019: these @code{protected}s.
11020: 
11021: @node Dividing classes, Object Interfaces, Classes and Scoping, Objects
11022: @subsubsection Dividing classes
11023: @cindex Dividing classes
11024: @cindex @code{methods}...@code{end-methods}
11025: 
11026: You may want to do the definition of methods separate from the
11027: definition of the class, its selectors, fields, and instance variables,
11028: i.e., separate the implementation from the definition.  You can do this
11029: in the following way:
11030: 
11031: @example
11032: graphical class
11033:   inst-value radius
11034: end-class circle
11035: 
11036: ... \ do some other stuff
11037: 
11038: circle methods \ now we are ready
11039: 
11040: m: ( x y circle -- )
11041:   radius draw-circle ;m
11042: overrides draw
11043: 
11044: m: ( n-radius circle -- )
11045:   [to-inst] radius ;m
11046: overrides construct
11047: 
11048: end-methods
11049: @end example
11050: 
11051: You can use several @code{methods}...@code{end-methods} sections.  The
11052: only things you can do to the class in these sections are: defining
11053: methods, and overriding the class's selectors.  You must not define new
11054: selectors or fields.
11055: 
11056: Note that you often have to override a selector before using it.  In
11057: particular, you usually have to override @code{construct} with a new
11058: method before you can invoke @code{heap-new} and friends.  E.g., you
11059: must not create a circle before the @code{overrides construct} sequence
11060: in the example above.
11061: 
11062: @node Object Interfaces, Objects Implementation, Dividing classes, Objects
11063: @subsubsection Object Interfaces
11064: @cindex object interfaces
11065: @cindex interfaces for objects
11066: 
11067: In this model you can only call selectors defined in the class of the
11068: receiving objects or in one of its ancestors. If you call a selector
11069: with a receiving object that is not in one of these classes, the
11070: result is undefined; if you are lucky, the program crashes
11071: immediately.
11072: 
11073: @cindex selectors common to hardly-related classes
11074: Now consider the case when you want to have a selector (or several)
11075: available in two classes: You would have to add the selector to a
11076: common ancestor class, in the worst case to @code{object}. You
11077: may not want to do this, e.g., because someone else is responsible for
11078: this ancestor class.
11079: 
11080: The solution for this problem is interfaces. An interface is a
11081: collection of selectors. If a class implements an interface, the
11082: selectors become available to the class and its descendents. A class
11083: can implement an unlimited number of interfaces. For the problem
11084: discussed above, we would define an interface for the selector(s), and
11085: both classes would implement the interface.
11086: 
11087: As an example, consider an interface @code{storage} for
11088: writing objects to disk and getting them back, and a class
11089: @code{foo} that implements it. The code would look like this:
11090: 
11091: @cindex @code{interface} usage
11092: @cindex @code{end-interface} usage
11093: @cindex @code{implementation} usage
11094: @example
11095: interface
11096:   selector write ( file object -- )
11097:   selector read1 ( file object -- )
11098: end-interface storage
11099: 
11100: bar class
11101:   storage implementation
11102: 
11103: ... overrides write
11104: ... overrides read1
11105: ...
11106: end-class foo
11107: @end example
11108: 
11109: @noindent
11110: (I would add a word @code{read} @i{( file -- object )} that uses
11111: @code{read1} internally, but that's beyond the point illustrated
11112: here.)
11113: 
11114: Note that you cannot use @code{protected} in an interface; and
11115: of course you cannot define fields.
11116: 
11117: In the Neon model, all selectors are available for all classes;
11118: therefore it does not need interfaces. The price you pay in this model
11119: is slower late binding, and therefore, added complexity to avoid late
11120: binding.
11121: 
11122: @node Objects Implementation, Objects Glossary, Object Interfaces, Objects
11123: @subsubsection @file{objects.fs} Implementation
11124: @cindex @file{objects.fs} implementation
11125: 
11126: @cindex @code{object-map} discussion
11127: An object is a piece of memory, like one of the data structures
11128: described with @code{struct...end-struct}. It has a field
11129: @code{object-map} that points to the method map for the object's
11130: class.
11131: 
11132: @cindex method map
11133: @cindex virtual function table
11134: The @emph{method map}@footnote{This is Self terminology; in C++
11135: terminology: virtual function table.} is an array that contains the
11136: execution tokens (@i{xt}s) of the methods for the object's class. Each
11137: selector contains an offset into a method map.
11138: 
11139: @cindex @code{selector} implementation, class
11140: @code{selector} is a defining word that uses
11141: @code{CREATE} and @code{DOES>}. The body of the
11142: selector contains the offset; the @code{DOES>} action for a
11143: class selector is, basically:
11144: 
11145: @example
11146: ( object addr ) @@ over object-map @@ + @@ execute
11147: @end example
11148: 
11149: Since @code{object-map} is the first field of the object, it
11150: does not generate any code. As you can see, calling a selector has a
11151: small, constant cost.
11152: 
11153: @cindex @code{current-interface} discussion
11154: @cindex class implementation and representation
11155: A class is basically a @code{struct} combined with a method
11156: map. During the class definition the alignment and size of the class
11157: are passed on the stack, just as with @code{struct}s, so
11158: @code{field} can also be used for defining class
11159: fields. However, passing more items on the stack would be
11160: inconvenient, so @code{class} builds a data structure in memory,
11161: which is accessed through the variable
11162: @code{current-interface}. After its definition is complete, the
11163: class is represented on the stack by a pointer (e.g., as parameter for
11164: a child class definition).
11165: 
11166: A new class starts off with the alignment and size of its parent,
11167: and a copy of the parent's method map. Defining new fields extends the
11168: size and alignment; likewise, defining new selectors extends the
11169: method map. @code{overrides} just stores a new @i{xt} in the method
11170: map at the offset given by the selector.
11171: 
11172: @cindex class binding, implementation
11173: Class binding just gets the @i{xt} at the offset given by the selector
11174: from the class's method map and @code{compile,}s (in the case of
11175: @code{[bind]}) it.
11176: 
11177: @cindex @code{this} implementation
11178: @cindex @code{catch} and @code{this}
11179: @cindex @code{this} and @code{catch}
11180: I implemented @code{this} as a @code{value}. At the
11181: start of an @code{m:...;m} method the old @code{this} is
11182: stored to the return stack and restored at the end; and the object on
11183: the TOS is stored @code{TO this}. This technique has one
11184: disadvantage: If the user does not leave the method via
11185: @code{;m}, but via @code{throw} or @code{exit},
11186: @code{this} is not restored (and @code{exit} may
11187: crash). To deal with the @code{throw} problem, I have redefined
11188: @code{catch} to save and restore @code{this}; the same
11189: should be done with any word that can catch an exception. As for
11190: @code{exit}, I simply forbid it (as a replacement, there is
11191: @code{exitm}).
11192: 
11193: @cindex @code{inst-var} implementation
11194: @code{inst-var} is just the same as @code{field}, with
11195: a different @code{DOES>} action:
11196: @example
11197: @@ this +
11198: @end example
11199: Similar for @code{inst-value}.
11200: 
11201: @cindex class scoping implementation
11202: Each class also has a word list that contains the words defined with
11203: @code{inst-var} and @code{inst-value}, and its protected
11204: words. It also has a pointer to its parent. @code{class} pushes
11205: the word lists of the class and all its ancestors onto the search order stack,
11206: and @code{end-class} drops them.
11207: 
11208: @cindex interface implementation
11209: An interface is like a class without fields, parent and protected
11210: words; i.e., it just has a method map. If a class implements an
11211: interface, its method map contains a pointer to the method map of the
11212: interface. The positive offsets in the map are reserved for class
11213: methods, therefore interface map pointers have negative
11214: offsets. Interfaces have offsets that are unique throughout the
11215: system, unlike class selectors, whose offsets are only unique for the
11216: classes where the selector is available (invokable).
11217: 
11218: This structure means that interface selectors have to perform one
11219: indirection more than class selectors to find their method. Their body
11220: contains the interface map pointer offset in the class method map, and
11221: the method offset in the interface method map. The
11222: @code{does>} action for an interface selector is, basically:
11223: 
11224: @example
11225: ( object selector-body )
11226: 2dup selector-interface @@ ( object selector-body object interface-offset )
11227: swap object-map @@ + @@ ( object selector-body map )
11228: swap selector-offset @@ + @@ execute
11229: @end example
11230: 
11231: where @code{object-map} and @code{selector-offset} are
11232: first fields and generate no code.
11233: 
11234: As a concrete example, consider the following code:
11235: 
11236: @example
11237: interface
11238:   selector if1sel1
11239:   selector if1sel2
11240: end-interface if1
11241: 
11242: object class
11243:   if1 implementation
11244:   selector cl1sel1
11245:   cell% inst-var cl1iv1
11246: 
11247: ' m1 overrides construct
11248: ' m2 overrides if1sel1
11249: ' m3 overrides if1sel2
11250: ' m4 overrides cl1sel2
11251: end-class cl1
11252: 
11253: create obj1 object dict-new drop
11254: create obj2 cl1    dict-new drop
11255: @end example
11256: 
11257: The data structure created by this code (including the data structure
11258: for @code{object}) is shown in the
11259: @uref{objects-implementation.eps,figure}, assuming a cell size of 4.
11260: @comment TODO add this diagram..
11261: 
11262: @node Objects Glossary,  , Objects Implementation, Objects
11263: @subsubsection @file{objects.fs} Glossary
11264: @cindex @file{objects.fs} Glossary
11265: 
11266: 
11267: doc---objects-bind
11268: doc---objects-<bind>
11269: doc---objects-bind'
11270: doc---objects-[bind]
11271: doc---objects-class
11272: doc---objects-class->map
11273: doc---objects-class-inst-size
11274: doc---objects-class-override!
11275: doc---objects-class-previous
11276: doc---objects-class>order
11277: doc---objects-construct
11278: doc---objects-current'
11279: doc---objects-[current]
11280: doc---objects-current-interface
11281: doc---objects-dict-new
11282: doc---objects-end-class
11283: doc---objects-end-class-noname
11284: doc---objects-end-interface
11285: doc---objects-end-interface-noname
11286: doc---objects-end-methods
11287: doc---objects-exitm
11288: doc---objects-heap-new
11289: doc---objects-implementation
11290: doc---objects-init-object
11291: doc---objects-inst-value
11292: doc---objects-inst-var
11293: doc---objects-interface
11294: doc---objects-m:
11295: doc---objects-:m
11296: doc---objects-;m
11297: doc---objects-method
11298: doc---objects-methods
11299: doc---objects-object
11300: doc---objects-overrides
11301: doc---objects-[parent]
11302: doc---objects-print
11303: doc---objects-protected
11304: doc---objects-public
11305: doc---objects-selector
11306: doc---objects-this
11307: doc---objects-<to-inst>
11308: doc---objects-[to-inst]
11309: doc---objects-to-this
11310: doc---objects-xt-new
11311: 
11312: 
11313: @c -------------------------------------------------------------
11314: @node OOF, Mini-OOF, Objects, Object-oriented Forth
11315: @subsection The @file{oof.fs} model
11316: @cindex oof
11317: @cindex object-oriented programming
11318: 
11319: @cindex @file{objects.fs}
11320: @cindex @file{oof.fs}
11321: 
11322: This section describes the @file{oof.fs} package.
11323: 
11324: The package described in this section has been used in bigFORTH since 1991, and
11325: used for two large applications: a chromatographic system used to
11326: create new medicaments, and a graphic user interface library (MINOS).
11327: 
11328: You can find a description (in German) of @file{oof.fs} in @cite{Object
11329: oriented bigFORTH} by Bernd Paysan, published in @cite{Vierte Dimension}
11330: 10(2), 1994.
11331: 
11332: @menu
11333: * Properties of the OOF model::  
11334: * Basic OOF Usage::             
11335: * The OOF base class::          
11336: * Class Declaration::           
11337: * Class Implementation::        
11338: @end menu
11339: 
11340: @node Properties of the OOF model, Basic OOF Usage, OOF, OOF
11341: @subsubsection Properties of the @file{oof.fs} model
11342: @cindex @file{oof.fs} properties
11343: 
11344: @itemize @bullet
11345: @item
11346: This model combines object oriented programming with information
11347: hiding. It helps you writing large application, where scoping is
11348: necessary, because it provides class-oriented scoping.
11349: 
11350: @item
11351: Named objects, object pointers, and object arrays can be created,
11352: selector invocation uses the ``object selector'' syntax. Selector invocation
11353: to objects and/or selectors on the stack is a bit less convenient, but
11354: possible.
11355: 
11356: @item
11357: Selector invocation and instance variable usage of the active object is
11358: straightforward, since both make use of the active object.
11359: 
11360: @item
11361: Late binding is efficient and easy to use.
11362: 
11363: @item
11364: State-smart objects parse selectors. However, extensibility is provided
11365: using a (parsing) selector @code{postpone} and a selector @code{'}.
11366: 
11367: @item
11368: An implementation in ANS Forth is available.
11369: 
11370: @end itemize
11371: 
11372: 
11373: @node Basic OOF Usage, The OOF base class, Properties of the OOF model, OOF
11374: @subsubsection Basic @file{oof.fs} Usage
11375: @cindex @file{oof.fs} usage
11376: 
11377: This section uses the same example as for @code{objects} (@pxref{Basic Objects Usage}).
11378: 
11379: You can define a class for graphical objects like this:
11380: 
11381: @cindex @code{class} usage
11382: @cindex @code{class;} usage
11383: @cindex @code{method} usage
11384: @example
11385: object class graphical \ "object" is the parent class
11386:   method draw ( x y -- )
11387: class;
11388: @end example
11389: 
11390: This code defines a class @code{graphical} with an
11391: operation @code{draw}.  We can perform the operation
11392: @code{draw} on any @code{graphical} object, e.g.:
11393: 
11394: @example
11395: 100 100 t-rex draw
11396: @end example
11397: 
11398: @noindent
11399: where @code{t-rex} is an object or object pointer, created with e.g.
11400: @code{graphical : t-rex}.
11401: 
11402: @cindex abstract class
11403: How do we create a graphical object? With the present definitions,
11404: we cannot create a useful graphical object. The class
11405: @code{graphical} describes graphical objects in general, but not
11406: any concrete graphical object type (C++ users would call it an
11407: @emph{abstract class}); e.g., there is no method for the selector
11408: @code{draw} in the class @code{graphical}.
11409: 
11410: For concrete graphical objects, we define child classes of the
11411: class @code{graphical}, e.g.:
11412: 
11413: @example
11414: graphical class circle \ "graphical" is the parent class
11415:   cell var circle-radius
11416: how:
11417:   : draw ( x y -- )
11418:     circle-radius @@ draw-circle ;
11419: 
11420:   : init ( n-radius -- )
11421:     circle-radius ! ;
11422: class;
11423: @end example
11424: 
11425: Here we define a class @code{circle} as a child of @code{graphical},
11426: with a field @code{circle-radius}; it defines new methods for the
11427: selectors @code{draw} and @code{init} (@code{init} is defined in
11428: @code{object}, the parent class of @code{graphical}).
11429: 
11430: Now we can create a circle in the dictionary with:
11431: 
11432: @example
11433: 50 circle : my-circle
11434: @end example
11435: 
11436: @noindent
11437: @code{:} invokes @code{init}, thus initializing the field
11438: @code{circle-radius} with 50. We can draw this new circle at (100,100)
11439: with:
11440: 
11441: @example
11442: 100 100 my-circle draw
11443: @end example
11444: 
11445: @cindex selector invocation, restrictions
11446: @cindex class definition, restrictions
11447: Note: You can only invoke a selector if the receiving object belongs to
11448: the class where the selector was defined or one of its descendents;
11449: e.g., you can invoke @code{draw} only for objects belonging to
11450: @code{graphical} or its descendents (e.g., @code{circle}). The scoping
11451: mechanism will check if you try to invoke a selector that is not
11452: defined in this class hierarchy, so you'll get an error at compilation
11453: time.
11454: 
11455: 
11456: @node The OOF base class, Class Declaration, Basic OOF Usage, OOF
11457: @subsubsection The @file{oof.fs} base class
11458: @cindex @file{oof.fs} base class
11459: 
11460: When you define a class, you have to specify a parent class.  So how do
11461: you start defining classes? There is one class available from the start:
11462: @code{object}. You have to use it as ancestor for all classes. It is the
11463: only class that has no parent. Classes are also objects, except that
11464: they don't have instance variables; class manipulation such as
11465: inheritance or changing definitions of a class is handled through
11466: selectors of the class @code{object}.
11467: 
11468: @code{object} provides a number of selectors:
11469: 
11470: @itemize @bullet
11471: @item
11472: @code{class} for subclassing, @code{definitions} to add definitions
11473: later on, and @code{class?} to get type informations (is the class a
11474: subclass of the class passed on the stack?).
11475: 
11476: doc---object-class
11477: doc---object-definitions
11478: doc---object-class?
11479: 
11480: 
11481: @item
11482: @code{init} and @code{dispose} as constructor and destructor of the
11483: object. @code{init} is invocated after the object's memory is allocated,
11484: while @code{dispose} also handles deallocation. Thus if you redefine
11485: @code{dispose}, you have to call the parent's dispose with @code{super
11486: dispose}, too.
11487: 
11488: doc---object-init
11489: doc---object-dispose
11490: 
11491: 
11492: @item
11493: @code{new}, @code{new[]}, @code{:}, @code{ptr}, @code{asptr}, and
11494: @code{[]} to create named and unnamed objects and object arrays or
11495: object pointers.
11496: 
11497: doc---object-new
11498: doc---object-new[]
11499: doc---object-:
11500: doc---object-ptr
11501: doc---object-asptr
11502: doc---object-[]
11503: 
11504: 
11505: @item
11506: @code{::} and @code{super} for explicit scoping. You should use explicit
11507: scoping only for super classes or classes with the same set of instance
11508: variables. Explicitly-scoped selectors use early binding.
11509: 
11510: doc---object-::
11511: doc---object-super
11512: 
11513: 
11514: @item
11515: @code{self} to get the address of the object
11516: 
11517: doc---object-self
11518: 
11519: 
11520: @item
11521: @code{bind}, @code{bound}, @code{link}, and @code{is} to assign object
11522: pointers and instance defers.
11523: 
11524: doc---object-bind
11525: doc---object-bound
11526: doc---object-link
11527: doc---object-is
11528: 
11529: 
11530: @item
11531: @code{'} to obtain selector tokens, @code{send} to invocate selectors
11532: form the stack, and @code{postpone} to generate selector invocation code.
11533: 
11534: doc---object-'
11535: doc---object-postpone
11536: 
11537: 
11538: @item
11539: @code{with} and @code{endwith} to select the active object from the
11540: stack, and enable its scope. Using @code{with} and @code{endwith}
11541: also allows you to create code using selector @code{postpone} without being
11542: trapped by the state-smart objects.
11543: 
11544: doc---object-with
11545: doc---object-endwith
11546: 
11547: 
11548: @end itemize
11549: 
11550: @node Class Declaration, Class Implementation, The OOF base class, OOF
11551: @subsubsection Class Declaration
11552: @cindex class declaration
11553: 
11554: @itemize @bullet
11555: @item
11556: Instance variables
11557: 
11558: doc---oof-var
11559: 
11560: 
11561: @item
11562: Object pointers
11563: 
11564: doc---oof-ptr
11565: doc---oof-asptr
11566: 
11567: 
11568: @item
11569: Instance defers
11570: 
11571: doc---oof-defer
11572: 
11573: 
11574: @item
11575: Method selectors
11576: 
11577: doc---oof-early
11578: doc---oof-method
11579: 
11580: 
11581: @item
11582: Class-wide variables
11583: 
11584: doc---oof-static
11585: 
11586: 
11587: @item
11588: End declaration
11589: 
11590: doc---oof-how:
11591: doc---oof-class;
11592: 
11593: 
11594: @end itemize
11595: 
11596: @c -------------------------------------------------------------
11597: @node Class Implementation,  , Class Declaration, OOF
11598: @subsubsection Class Implementation
11599: @cindex class implementation
11600: 
11601: @c -------------------------------------------------------------
11602: @node Mini-OOF, Comparison with other object models, OOF, Object-oriented Forth
11603: @subsection The @file{mini-oof.fs} model
11604: @cindex mini-oof
11605: 
11606: Gforth's third object oriented Forth package is a 12-liner. It uses a
11607: mixture of the @file{objects.fs} and the @file{oof.fs} syntax,
11608: and reduces to the bare minimum of features. This is based on a posting
11609: of Bernd Paysan in comp.lang.forth.
11610: 
11611: @menu
11612: * Basic Mini-OOF Usage::        
11613: * Mini-OOF Example::            
11614: * Mini-OOF Implementation::     
11615: @end menu
11616: 
11617: @c -------------------------------------------------------------
11618: @node Basic Mini-OOF Usage, Mini-OOF Example, Mini-OOF, Mini-OOF
11619: @subsubsection Basic @file{mini-oof.fs} Usage
11620: @cindex mini-oof usage
11621: 
11622: There is a base class (@code{class}, which allocates one cell for the
11623: object pointer) plus seven other words: to define a method, a variable,
11624: a class; to end a class, to resolve binding, to allocate an object and
11625: to compile a class method.
11626: @comment TODO better description of the last one
11627: 
11628: 
11629: doc-object
11630: doc-method
11631: doc-var
11632: doc-class
11633: doc-end-class
11634: doc-defines
11635: doc-new
11636: doc-::
11637: 
11638: 
11639: 
11640: @c -------------------------------------------------------------
11641: @node Mini-OOF Example, Mini-OOF Implementation, Basic Mini-OOF Usage, Mini-OOF
11642: @subsubsection Mini-OOF Example
11643: @cindex mini-oof example
11644: 
11645: A short example shows how to use this package. This example, in slightly
11646: extended form, is supplied as @file{moof-exm.fs}
11647: @comment TODO could flesh this out with some comments from the Forthwrite article
11648: 
11649: @example
11650: object class
11651:   method init
11652:   method draw
11653: end-class graphical
11654: @end example
11655: 
11656: This code defines a class @code{graphical} with an
11657: operation @code{draw}.  We can perform the operation
11658: @code{draw} on any @code{graphical} object, e.g.:
11659: 
11660: @example
11661: 100 100 t-rex draw
11662: @end example
11663: 
11664: where @code{t-rex} is an object or object pointer, created with e.g.
11665: @code{graphical new Constant t-rex}.
11666: 
11667: For concrete graphical objects, we define child classes of the
11668: class @code{graphical}, e.g.:
11669: 
11670: @example
11671: graphical class
11672:   cell var circle-radius
11673: end-class circle \ "graphical" is the parent class
11674: 
11675: :noname ( x y -- )
11676:   circle-radius @@ draw-circle ; circle defines draw
11677: :noname ( r -- )
11678:   circle-radius ! ; circle defines init
11679: @end example
11680: 
11681: There is no implicit init method, so we have to define one. The creation
11682: code of the object now has to call init explicitely.
11683: 
11684: @example
11685: circle new Constant my-circle
11686: 50 my-circle init
11687: @end example
11688: 
11689: It is also possible to add a function to create named objects with
11690: automatic call of @code{init}, given that all objects have @code{init}
11691: on the same place:
11692: 
11693: @example
11694: : new: ( .. o "name" -- )
11695:     new dup Constant init ;
11696: 80 circle new: large-circle
11697: @end example
11698: 
11699: We can draw this new circle at (100,100) with:
11700: 
11701: @example
11702: 100 100 my-circle draw
11703: @end example
11704: 
11705: @node Mini-OOF Implementation,  , Mini-OOF Example, Mini-OOF
11706: @subsubsection @file{mini-oof.fs} Implementation
11707: 
11708: Object-oriented systems with late binding typically use a
11709: ``vtable''-approach: the first variable in each object is a pointer to a
11710: table, which contains the methods as function pointers. The vtable
11711: may also contain other information.
11712: 
11713: So first, let's declare selectors:
11714: 
11715: @example
11716: : method ( m v "name" -- m' v ) Create  over , swap cell+ swap
11717:   DOES> ( ... o -- ... ) @@ over @@ + @@ execute ;
11718: @end example
11719: 
11720: During selector declaration, the number of selectors and instance
11721: variables is on the stack (in address units). @code{method} creates one
11722: selector and increments the selector number. To execute a selector, it
11723: takes the object, fetches the vtable pointer, adds the offset, and
11724: executes the method @i{xt} stored there. Each selector takes the object
11725: it is invoked with as top of stack parameter; it passes the parameters
11726: (including the object) unchanged to the appropriate method which should
11727: consume that object.
11728: 
11729: Now, we also have to declare instance variables
11730: 
11731: @example
11732: : var ( m v size "name" -- m v' ) Create  over , +
11733:   DOES> ( o -- addr ) @@ + ;
11734: @end example
11735: 
11736: As before, a word is created with the current offset. Instance
11737: variables can have different sizes (cells, floats, doubles, chars), so
11738: all we do is take the size and add it to the offset. If your machine
11739: has alignment restrictions, put the proper @code{aligned} or
11740: @code{faligned} before the variable, to adjust the variable
11741: offset. That's why it is on the top of stack.
11742: 
11743: We need a starting point (the base object) and some syntactic sugar:
11744: 
11745: @example
11746: Create object  1 cells , 2 cells ,
11747: : class ( class -- class selectors vars ) dup 2@@ ;
11748: @end example
11749: 
11750: For inheritance, the vtable of the parent object has to be
11751: copied when a new, derived class is declared. This gives all the
11752: methods of the parent class, which can be overridden, though.
11753: 
11754: @example
11755: : end-class  ( class selectors vars "name" -- )
11756:   Create  here >r , dup , 2 cells ?DO ['] noop , 1 cells +LOOP
11757:   cell+ dup cell+ r> rot @@ 2 cells /string move ;
11758: @end example
11759: 
11760: The first line creates the vtable, initialized with
11761: @code{noop}s. The second line is the inheritance mechanism, it
11762: copies the xts from the parent vtable.
11763: 
11764: We still have no way to define new methods, let's do that now:
11765: 
11766: @example
11767: : defines ( xt class "name" -- ) ' >body @@ + ! ;
11768: @end example
11769: 
11770: To allocate a new object, we need a word, too:
11771: 
11772: @example
11773: : new ( class -- o )  here over @@ allot swap over ! ;
11774: @end example
11775: 
11776: Sometimes derived classes want to access the method of the
11777: parent object. There are two ways to achieve this with Mini-OOF:
11778: first, you could use named words, and second, you could look up the
11779: vtable of the parent object.
11780: 
11781: @example
11782: : :: ( class "name" -- ) ' >body @@ + @@ compile, ;
11783: @end example
11784: 
11785: 
11786: Nothing can be more confusing than a good example, so here is
11787: one. First let's declare a text object (called
11788: @code{button}), that stores text and position:
11789: 
11790: @example
11791: object class
11792:   cell var text
11793:   cell var len
11794:   cell var x
11795:   cell var y
11796:   method init
11797:   method draw
11798: end-class button
11799: @end example
11800: 
11801: @noindent
11802: Now, implement the two methods, @code{draw} and @code{init}:
11803: 
11804: @example
11805: :noname ( o -- )
11806:  >r r@@ x @@ r@@ y @@ at-xy  r@@ text @@ r> len @@ type ;
11807:  button defines draw
11808: :noname ( addr u o -- )
11809:  >r 0 r@@ x ! 0 r@@ y ! r@@ len ! r> text ! ;
11810:  button defines init
11811: @end example
11812: 
11813: @noindent
11814: To demonstrate inheritance, we define a class @code{bold-button}, with no
11815: new data and no new selectors:
11816: 
11817: @example
11818: button class
11819: end-class bold-button
11820: 
11821: : bold   27 emit ." [1m" ;
11822: : normal 27 emit ." [0m" ;
11823: @end example
11824: 
11825: @noindent
11826: The class @code{bold-button} has a different draw method to
11827: @code{button}, but the new method is defined in terms of the draw method
11828: for @code{button}:
11829: 
11830: @example
11831: :noname bold [ button :: draw ] normal ; bold-button defines draw
11832: @end example
11833: 
11834: @noindent
11835: Finally, create two objects and apply selectors:
11836: 
11837: @example
11838: button new Constant foo
11839: s" thin foo" foo init
11840: page
11841: foo draw
11842: bold-button new Constant bar
11843: s" fat bar" bar init
11844: 1 bar y !
11845: bar draw
11846: @end example
11847: 
11848: 
11849: @node Comparison with other object models,  , Mini-OOF, Object-oriented Forth
11850: @subsection Comparison with other object models
11851: @cindex comparison of object models
11852: @cindex object models, comparison
11853: 
11854: Many object-oriented Forth extensions have been proposed (@cite{A survey
11855: of object-oriented Forths} (SIGPLAN Notices, April 1996) by Bradford
11856: J. Rodriguez and W. F. S. Poehlman lists 17). This section discusses the
11857: relation of the object models described here to two well-known and two
11858: closely-related (by the use of method maps) models.  Andras Zsoter
11859: helped us with this section.
11860: 
11861: @cindex Neon model
11862: The most popular model currently seems to be the Neon model (see
11863: @cite{Object-oriented programming in ANS Forth} (Forth Dimensions, March
11864: 1997) by Andrew McKewan) but this model has a number of limitations
11865: @footnote{A longer version of this critique can be
11866: found in @cite{On Standardizing Object-Oriented Forth Extensions} (Forth
11867: Dimensions, May 1997) by Anton Ertl.}:
11868: 
11869: @itemize @bullet
11870: @item
11871: It uses a @code{@emph{selector object}} syntax, which makes it unnatural
11872: to pass objects on the stack.
11873: 
11874: @item
11875: It requires that the selector parses the input stream (at
11876: compile time); this leads to reduced extensibility and to bugs that are
11877: hard to find.
11878: 
11879: @item
11880: It allows using every selector on every object; this eliminates the
11881: need for interfaces, but makes it harder to create efficient
11882: implementations.
11883: @end itemize
11884: 
11885: @cindex Pountain's object-oriented model
11886: Another well-known publication is @cite{Object-Oriented Forth} (Academic
11887: Press, London, 1987) by Dick Pountain. However, it is not really about
11888: object-oriented programming, because it hardly deals with late
11889: binding. Instead, it focuses on features like information hiding and
11890: overloading that are characteristic of modular languages like Ada (83).
11891: 
11892: @cindex Zsoter's object-oriented model
11893: In @uref{http://www.forth.org/oopf.html, Does late binding have to be
11894: slow?} (Forth Dimensions 18(1) 1996, pages 31-35) Andras Zsoter
11895: describes a model that makes heavy use of an active object (like
11896: @code{this} in @file{objects.fs}): The active object is not only used
11897: for accessing all fields, but also specifies the receiving object of
11898: every selector invocation; you have to change the active object
11899: explicitly with @code{@{ ... @}}, whereas in @file{objects.fs} it
11900: changes more or less implicitly at @code{m: ... ;m}. Such a change at
11901: the method entry point is unnecessary with Zsoter's model, because the
11902: receiving object is the active object already. On the other hand, the
11903: explicit change is absolutely necessary in that model, because otherwise
11904: no one could ever change the active object. An ANS Forth implementation
11905: of this model is available through
11906: @uref{http://www.forth.org/oopf.html}.
11907: 
11908: @cindex @file{oof.fs}, differences to other models
11909: The @file{oof.fs} model combines information hiding and overloading
11910: resolution (by keeping names in various word lists) with object-oriented
11911: programming. It sets the active object implicitly on method entry, but
11912: also allows explicit changing (with @code{>o...o>} or with
11913: @code{with...endwith}). It uses parsing and state-smart objects and
11914: classes for resolving overloading and for early binding: the object or
11915: class parses the selector and determines the method from this. If the
11916: selector is not parsed by an object or class, it performs a call to the
11917: selector for the active object (late binding), like Zsoter's model.
11918: Fields are always accessed through the active object. The big
11919: disadvantage of this model is the parsing and the state-smartness, which
11920: reduces extensibility and increases the opportunities for subtle bugs;
11921: essentially, you are only safe if you never tick or @code{postpone} an
11922: object or class (Bernd disagrees, but I (Anton) am not convinced).
11923: 
11924: @cindex @file{mini-oof.fs}, differences to other models
11925: The @file{mini-oof.fs} model is quite similar to a very stripped-down
11926: version of the @file{objects.fs} model, but syntactically it is a
11927: mixture of the @file{objects.fs} and @file{oof.fs} models.
11928: 
11929: 
11930: @c -------------------------------------------------------------
11931: @node Programming Tools, C Interface, Object-oriented Forth, Words
11932: @section Programming Tools
11933: @cindex programming tools
11934: 
11935: @c !! move this and assembler down below OO stuff.
11936: 
11937: @menu
11938: * Examining::                   Data and Code.
11939: * Forgetting words::            Usually before reloading.
11940: * Debugging::                   Simple and quick.
11941: * Assertions::                  Making your programs self-checking.
11942: * Singlestep Debugger::         Executing your program word by word.
11943: @end menu
11944: 
11945: @node Examining, Forgetting words, Programming Tools, Programming Tools
11946: @subsection Examining data and code
11947: @cindex examining data and code
11948: @cindex data examination
11949: @cindex code examination
11950: 
11951: The following words inspect the stack non-destructively:
11952: 
11953: doc-.s
11954: doc-f.s
11955: doc-maxdepth-.s
11956: 
11957: There is a word @code{.r} but it does @i{not} display the return stack!
11958: It is used for formatted numeric output (@pxref{Simple numeric output}).
11959: 
11960: doc-depth
11961: doc-fdepth
11962: doc-clearstack
11963: doc-clearstacks
11964: 
11965: The following words inspect memory.
11966: 
11967: doc-?
11968: doc-dump
11969: 
11970: And finally, @code{see} allows to inspect code:
11971: 
11972: doc-see
11973: doc-xt-see
11974: doc-simple-see
11975: doc-simple-see-range
11976: doc-see-code
11977: doc-see-code-range
11978: 
11979: @node Forgetting words, Debugging, Examining, Programming Tools
11980: @subsection Forgetting words
11981: @cindex words, forgetting
11982: @cindex forgeting words
11983: 
11984: @c  anton: other, maybe better places for this subsection: Defining Words;
11985: @c  Dictionary allocation.  At least a reference should be there.
11986: 
11987: Forth allows you to forget words (and everything that was alloted in the
11988: dictonary after them) in a LIFO manner.
11989: 
11990: doc-marker
11991: 
11992: The most common use of this feature is during progam development: when
11993: you change a source file, forget all the words it defined and load it
11994: again (since you also forget everything defined after the source file
11995: was loaded, you have to reload that, too).  Note that effects like
11996: storing to variables and destroyed system words are not undone when you
11997: forget words.  With a system like Gforth, that is fast enough at
11998: starting up and compiling, I find it more convenient to exit and restart
11999: Gforth, as this gives me a clean slate.
12000: 
12001: Here's an example of using @code{marker} at the start of a source file
12002: that you are debugging; it ensures that you only ever have one copy of
12003: the file's definitions compiled at any time:
12004: 
12005: @example
12006: [IFDEF] my-code
12007:     my-code
12008: [ENDIF]
12009: 
12010: marker my-code
12011: init-included-files
12012: 
12013: \ .. definitions start here
12014: \ .
12015: \ .
12016: \ end
12017: @end example
12018: 
12019: 
12020: @node Debugging, Assertions, Forgetting words, Programming Tools
12021: @subsection Debugging
12022: @cindex debugging
12023: 
12024: Languages with a slow edit/compile/link/test development loop tend to
12025: require sophisticated tracing/stepping debuggers to facilate debugging.
12026: 
12027: A much better (faster) way in fast-compiling languages is to add
12028: printing code at well-selected places, let the program run, look at
12029: the output, see where things went wrong, add more printing code, etc.,
12030: until the bug is found.
12031: 
12032: The simple debugging aids provided in @file{debugs.fs}
12033: are meant to support this style of debugging.
12034: 
12035: The word @code{~~} prints debugging information (by default the source
12036: location and the stack contents). It is easy to insert. If you use Emacs
12037: it is also easy to remove (@kbd{C-x ~} in the Emacs Forth mode to
12038: query-replace them with nothing). The deferred words
12039: @code{printdebugdata} and @code{.debugline} control the output of
12040: @code{~~}. The default source location output format works well with
12041: Emacs' compilation mode, so you can step through the program at the
12042: source level using @kbd{C-x `} (the advantage over a stepping debugger
12043: is that you can step in any direction and you know where the crash has
12044: happened or where the strange data has occurred).
12045: 
12046: doc-~~
12047: doc-printdebugdata
12048: doc-.debugline
12049: doc-debug-fid
12050: 
12051: @cindex filenames in @code{~~} output
12052: @code{~~} (and assertions) will usually print the wrong file name if a
12053: marker is executed in the same file after their occurance.  They will
12054: print @samp{*somewhere*} as file name if a marker is executed in the
12055: same file before their occurance.
12056: 
12057: 
12058: @node Assertions, Singlestep Debugger, Debugging, Programming Tools
12059: @subsection Assertions
12060: @cindex assertions
12061: 
12062: It is a good idea to make your programs self-checking, especially if you
12063: make an assumption that may become invalid during maintenance (for
12064: example, that a certain field of a data structure is never zero). Gforth
12065: supports @dfn{assertions} for this purpose. They are used like this:
12066: 
12067: @example
12068: assert( @i{flag} )
12069: @end example
12070: 
12071: The code between @code{assert(} and @code{)} should compute a flag, that
12072: should be true if everything is alright and false otherwise. It should
12073: not change anything else on the stack. The overall stack effect of the
12074: assertion is @code{( -- )}. E.g.
12075: 
12076: @example
12077: assert( 1 1 + 2 = ) \ what we learn in school
12078: assert( dup 0<> ) \ assert that the top of stack is not zero
12079: assert( false ) \ this code should not be reached
12080: @end example
12081: 
12082: The need for assertions is different at different times. During
12083: debugging, we want more checking, in production we sometimes care more
12084: for speed. Therefore, assertions can be turned off, i.e., the assertion
12085: becomes a comment. Depending on the importance of an assertion and the
12086: time it takes to check it, you may want to turn off some assertions and
12087: keep others turned on. Gforth provides several levels of assertions for
12088: this purpose:
12089: 
12090: 
12091: doc-assert0(
12092: doc-assert1(
12093: doc-assert2(
12094: doc-assert3(
12095: doc-assert(
12096: doc-)
12097: 
12098: 
12099: The variable @code{assert-level} specifies the highest assertions that
12100: are turned on. I.e., at the default @code{assert-level} of one,
12101: @code{assert0(} and @code{assert1(} assertions perform checking, while
12102: @code{assert2(} and @code{assert3(} assertions are treated as comments.
12103: 
12104: The value of @code{assert-level} is evaluated at compile-time, not at
12105: run-time. Therefore you cannot turn assertions on or off at run-time;
12106: you have to set the @code{assert-level} appropriately before compiling a
12107: piece of code. You can compile different pieces of code at different
12108: @code{assert-level}s (e.g., a trusted library at level 1 and
12109: newly-written code at level 3).
12110: 
12111: 
12112: doc-assert-level
12113: 
12114: 
12115: If an assertion fails, a message compatible with Emacs' compilation mode
12116: is produced and the execution is aborted (currently with @code{ABORT"}.
12117: If there is interest, we will introduce a special throw code. But if you
12118: intend to @code{catch} a specific condition, using @code{throw} is
12119: probably more appropriate than an assertion).
12120: 
12121: @cindex filenames in assertion output
12122: Assertions (and @code{~~}) will usually print the wrong file name if a
12123: marker is executed in the same file after their occurance.  They will
12124: print @samp{*somewhere*} as file name if a marker is executed in the
12125: same file before their occurance.
12126: 
12127: Definitions in ANS Forth for these assertion words are provided
12128: in @file{compat/assert.fs}.
12129: 
12130: 
12131: @node Singlestep Debugger,  , Assertions, Programming Tools
12132: @subsection Singlestep Debugger
12133: @cindex singlestep Debugger
12134: @cindex debugging Singlestep
12135: 
12136: The singlestep debugger works only with the engine @code{gforth-itc}.
12137: 
12138: When you create a new word there's often the need to check whether it
12139: behaves correctly or not. You can do this by typing @code{dbg
12140: badword}. A debug session might look like this:
12141: 
12142: @example
12143: : badword 0 DO i . LOOP ;  ok
12144: 2 dbg badword 
12145: : badword  
12146: Scanning code...
12147: 
12148: Nesting debugger ready!
12149: 
12150: 400D4738  8049BC4 0              -> [ 2 ] 00002 00000 
12151: 400D4740  8049F68 DO             -> [ 0 ] 
12152: 400D4744  804A0C8 i              -> [ 1 ] 00000 
12153: 400D4748 400C5E60 .              -> 0 [ 0 ] 
12154: 400D474C  8049D0C LOOP           -> [ 0 ] 
12155: 400D4744  804A0C8 i              -> [ 1 ] 00001 
12156: 400D4748 400C5E60 .              -> 1 [ 0 ] 
12157: 400D474C  8049D0C LOOP           -> [ 0 ] 
12158: 400D4758  804B384 ;              ->  ok
12159: @end example
12160: 
12161: Each line displayed is one step. You always have to hit return to
12162: execute the next word that is displayed. If you don't want to execute
12163: the next word in a whole, you have to type @kbd{n} for @code{nest}. Here is
12164: an overview what keys are available:
12165: 
12166: @table @i
12167: 
12168: @item @key{RET}
12169: Next; Execute the next word.
12170: 
12171: @item n
12172: Nest; Single step through next word.
12173: 
12174: @item u
12175: Unnest; Stop debugging and execute rest of word. If we got to this word
12176: with nest, continue debugging with the calling word.
12177: 
12178: @item d
12179: Done; Stop debugging and execute rest.
12180: 
12181: @item s
12182: Stop; Abort immediately.
12183: 
12184: @end table
12185: 
12186: Debugging large application with this mechanism is very difficult, because
12187: you have to nest very deeply into the program before the interesting part
12188: begins. This takes a lot of time. 
12189: 
12190: To do it more directly put a @code{BREAK:} command into your source code.
12191: When program execution reaches @code{BREAK:} the single step debugger is
12192: invoked and you have all the features described above.
12193: 
12194: If you have more than one part to debug it is useful to know where the
12195: program has stopped at the moment. You can do this by the 
12196: @code{BREAK" string"} command. This behaves like @code{BREAK:} except that
12197: string is typed out when the ``breakpoint'' is reached.
12198: 
12199: 
12200: doc-dbg
12201: doc-break:
12202: doc-break"
12203: 
12204: @c ------------------------------------------------------------
12205: @node C Interface, Assembler and Code Words, Programming Tools, Words
12206: @section C Interface
12207: @cindex C interface
12208: @cindex foreign language interface
12209: @cindex interface to C functions
12210: 
12211: Note that the C interface is not yet complete; callbacks are missing,
12212: as well as a way of declaring structs, unions, and their fields.
12213: 
12214: @menu
12215: * Calling C Functions::         
12216: * Declaring C Functions::       
12217: * Calling C function pointers::  
12218: * Defining library interfaces::  
12219: * Declaring OS-level libraries::  
12220: * Callbacks::                   
12221: * C interface internals::       
12222: * Low-Level C Interface Words::  
12223: @end menu
12224: 
12225: @node Calling C Functions, Declaring C Functions, C Interface, C Interface
12226: @subsection Calling C functions
12227: @cindex C functions, calls to
12228: @cindex calling C functions
12229: 
12230: Once a C function is declared (see @pxref{Declaring C Functions}), you
12231: can call it as follows: You push the arguments on the stack(s), and
12232: then call the word for the C function.  The arguments have to be
12233: pushed in the same order as the arguments appear in the C
12234: documentation (i.e., the first argument is deepest on the stack).
12235: Integer and pointer arguments have to be pushed on the data stack,
12236: floating-point arguments on the FP stack; these arguments are consumed
12237: by the called C function.
12238: 
12239: On returning from the C function, the return value, if any, resides on
12240: the appropriate stack: an integer return value is pushed on the data
12241: stack, an FP return value on the FP stack, and a void return value
12242: results in not pushing anything.  Note that most C functions have a
12243: return value, even if that is often not used in C; in Forth, you have
12244: to @code{drop} this return value explicitly if you do not use it.
12245: 
12246: The C interface automatically converts between the C type and the
12247: Forth type as necessary, on a best-effort basis (in some cases, there
12248: may be some loss).
12249: 
12250: As an example, consider the POSIX function @code{lseek()}:
12251: 
12252: @example
12253: off_t lseek(int fd, off_t offset, int whence);
12254: @end example
12255: 
12256: This function takes three integer arguments, and returns an integer
12257: argument, so a Forth call for setting the current file offset to the
12258: start of the file could look like this:
12259: 
12260: @example
12261: fd @@ 0 SEEK_SET lseek -1 = if
12262:   ... \ error handling
12263: then
12264: @end example
12265: 
12266: You might be worried that an @code{off_t} does not fit into a cell, so
12267: you could not pass larger offsets to lseek, and might get only a part
12268: of the return values.  In that case, in your declaration of the
12269: function (@pxref{Declaring C Functions}) you should declare it to use
12270: double-cells for the off_t argument and return value, and maybe give
12271: the resulting Forth word a different name, like @code{dlseek}; the
12272: result could be called like this:
12273: 
12274: @example
12275: fd @@ 0. SEEK_SET dlseek -1. d= if
12276:   ... \ error handling
12277: then
12278: @end example
12279: 
12280: Passing and returning structs or unions is currently not supported by
12281: our interface@footnote{If you know the calling convention of your C
12282: compiler, you usually can call such functions in some way, but that
12283: way is usually not portable between platforms, and sometimes not even
12284: between C compilers.}.
12285: 
12286: Calling functions with a variable number of arguments (@emph{variadic}
12287: functions, e.g., @code{printf()}) is only supported by having you
12288: declare one function-calling word for each argument pattern, and
12289: calling the appropriate word for the desired pattern.
12290: 
12291: 
12292: 
12293: @node Declaring C Functions, Calling C function pointers, Calling C Functions, C Interface
12294: @subsection Declaring C Functions
12295: @cindex C functions, declarations
12296: @cindex declaring C functions
12297: 
12298: Before you can call @code{lseek} or @code{dlseek}, you have to declare
12299: it.  The declaration consists of two parts: 
12300: 
12301: @table @b
12302: 
12303: @item The C part
12304: is the C declaration of the function, or more typically and portably,
12305: a C-style @code{#include} of a file that contains the declaration of
12306: the C function.
12307: 
12308: @item The Forth part
12309: declares the Forth types of the parameters and the Forth word name
12310: corresponding to the C function.
12311: 
12312: @end table
12313: 
12314: For the words @code{lseek} and @code{dlseek} mentioned earlier, the
12315: declarations are:
12316: 
12317: @example
12318: \c #define _FILE_OFFSET_BITS 64
12319: \c #include <sys/types.h>
12320: \c #include <unistd.h>
12321: c-function lseek lseek n n n -- n
12322: c-function dlseek lseek n d n -- d
12323: @end example
12324: 
12325: The C part of the declarations is prefixed by @code{\c}, and the rest
12326: of the line is ordinary C code.  You can use as many lines of C
12327: declarations as you like, and they are visible for all further
12328: function declarations.
12329: 
12330: The Forth part declares each interface word with @code{c-function},
12331: followed by the Forth name of the word, the C name of the called
12332: function, and the stack effect of the word.  The stack effect contains
12333: an arbitrary number of types of parameters, then @code{--}, and then
12334: exactly one type for the return value.  The possible types are:
12335: 
12336: @table @code
12337: 
12338: @item n
12339: single-cell integer
12340: 
12341: @item a
12342: address (single-cell)
12343: 
12344: @item d
12345: double-cell integer
12346: 
12347: @item r
12348: floating-point value
12349: 
12350: @item func
12351: C function pointer
12352: 
12353: @item void
12354: no value (used as return type for void functions)
12355: 
12356: @end table
12357: 
12358: @cindex variadic C functions
12359: 
12360: To deal with variadic C functions, you can declare one Forth word for
12361: every pattern you want to use, e.g.:
12362: 
12363: @example
12364: \c #include <stdio.h>
12365: c-function printf-nr printf a n r -- n
12366: c-function printf-rn printf a r n -- n
12367: @end example
12368: 
12369: Note that with C functions declared as variadic (or if you don't
12370: provide a prototype), the C interface has no C type to convert to, so
12371: no automatic conversion happens, which may lead to portability
12372: problems in some cases.  In such cases you can perform the conversion
12373: explicitly on the C level, e.g., as follows:
12374: 
12375: @example
12376: \c #define printfll(s,ll) printf(s,(long long)ll)
12377: c-function printfll printfll a n -- n
12378: @end example
12379: 
12380: Here, instead of calling @code{printf()} directly, we define a macro
12381: that casts (converts) the Forth single-cell integer into a
12382: C @code{long long} before calling @code{printf()}.
12383: 
12384: doc-\c
12385: doc-c-function
12386: doc-c-value
12387: doc-c-variable
12388: 
12389: In order to work, this C interface invokes GCC at run-time and uses
12390: dynamic linking.  If these features are not available, there are
12391: other, less convenient and less portable C interfaces in @file{lib.fs}
12392: and @file{oldlib.fs}.  These interfaces are mostly undocumented and
12393: mostly incompatible with each other and with the documented C
12394: interface; you can find some examples for the @file{lib.fs} interface
12395: in @file{lib.fs}.
12396: 
12397: 
12398: @node Calling C function pointers, Defining library interfaces, Declaring C Functions, C Interface
12399: @subsection Calling C function pointers from Forth
12400: @cindex C function pointers, calling from Forth
12401: 
12402: If you come across a C function pointer (e.g., in some C-constructed
12403: structure) and want to call it from your Forth program, you can also
12404: use the features explained until now to achieve that, as follows:
12405: 
12406: Let us assume that there is a C function pointer type @code{func1}
12407: defined in some header file @file{func1.h}, and you know that these
12408: functions take one integer argument and return an integer result; and
12409: you want to call functions through such pointers.  Just define
12410: 
12411: @example
12412: \c #include <func1.h>
12413: \c #define call_func1(par1,fptr) ((func1)fptr)(par1)
12414: c-function call-func1 call_func1 n func -- n
12415: @end example
12416: 
12417: and then you can call a function pointed to by, say @code{func1a} as
12418: follows:
12419: 
12420: @example
12421: -5 func1a call-func1 .
12422: @end example
12423: 
12424: In the C part, @code{call_func} is defined as a macro to avoid having
12425: to declare the exact parameter and return types, so the C compiler
12426: knows them from the declaration of @code{func1}.
12427: 
12428: The Forth word @code{call-func1} is similar to @code{execute}, except
12429: that it takes a C @code{func1} pointer instead of a Forth execution
12430: token, and it is specific to @code{func1} pointers.  For each type of
12431: function pointer you want to call from Forth, you have to define
12432: a separate calling word.
12433: 
12434: 
12435: @node Defining library interfaces, Declaring OS-level libraries, Calling C function pointers, C Interface
12436: @subsection Defining library interfaces
12437: @cindex giving a name to a library interface
12438: @cindex library interface names
12439: 
12440: You can give a name to a bunch of C function declarations (a library
12441: interface), as follows:
12442: 
12443: @example
12444: c-library lseek-lib
12445: \c #define _FILE_OFFSET_BITS 64
12446: ...
12447: end-c-library
12448: @end example
12449: 
12450: The effect of giving such a name to the interface is that the names of
12451: the generated files will contain that name, and when you use the
12452: interface a second time, it will use the existing files instead of
12453: generating and compiling them again, saving you time.  Note that even
12454: if you change the declarations, the old (stale) files will be used,
12455: probably leading to errors.  So, during development of the
12456: declarations we recommend not using @code{c-library}.  Normally these
12457: files are cached in @file{$HOME/.gforth/libcc-named}, so by deleting
12458: that directory you can get rid of stale files.
12459: 
12460: Note that you should use @code{c-library} before everything else
12461: having anything to do with that library, as it resets some setup
12462: stuff.  The idea is that the typical use is to put each
12463: @code{c-library}...@code{end-library} unit in its own file, and to be
12464: able to include these files in any order.
12465: 
12466: Note that the library name is not allocated in the dictionary and
12467: therefore does not shadow dictionary names.  It is used in the file
12468: system, so you have to use naming conventions appropriate for file
12469: systems.  Also, you must not call a function you declare after
12470: @code{c-library} before you perform @code{end-c-library}.
12471: 
12472: A major benefit of these named library interfaces is that, once they
12473: are generated, the tools used to generated them (in particular, the C
12474: compiler and libtool) are no longer needed, so the interface can be
12475: used even on machines that do not have the tools installed.
12476: 
12477: doc-c-library-name
12478: doc-c-library
12479: doc-end-c-library
12480: 
12481: 
12482: @node Declaring OS-level libraries, Callbacks, Defining library interfaces, C Interface
12483: @subsection Declaring OS-level libraries
12484: @cindex Shared libraries in C interface
12485: @cindex Dynamically linked libraries in C interface
12486: @cindex Libraries in C interface
12487: 
12488: For calling some C functions, you need to link with a specific
12489: OS-level library that contains that function.  E.g., the @code{sin}
12490: function requires linking a special library by using the command line
12491: switch @code{-lm}.  In our C iterface you do the equivalent thing by
12492: calling @code{add-lib} as follows:
12493: 
12494: @example
12495: clear-libs
12496: s" m" add-lib
12497: \c #include <math.h>
12498: c-function sin sin r -- r
12499: @end example
12500: 
12501: First, you clear any libraries that may have been declared earlier
12502: (you don't need them for @code{sin}); then you add the @code{m}
12503: library (actually @code{libm.so} or somesuch) to the currently
12504: declared libraries; you can add as many as you need.  Finally you
12505: declare the function as shown above.  Typically you will use the same
12506: set of library declarations for many function declarations; you need
12507: to write only one set for that, right at the beginning.
12508: 
12509: Note that you must not call @code{clear-libs} inside
12510: @code{c-library...end-c-library}; however, @code{c-library} performs
12511: the function of @code{clear-libs}, so @code{clear-libs} is not
12512: necessary, and you usually want to put @code{add-lib} calls inside
12513: @code{c-library...end-c-library}.
12514: 
12515: doc-clear-libs
12516: doc-add-lib
12517: 
12518: 
12519: @node Callbacks, C interface internals, Declaring OS-level libraries, C Interface
12520: @subsection Callbacks
12521: @cindex Callback functions written in Forth
12522: @cindex C function pointers to Forth words
12523: 
12524: Callbacks are not yet supported by the documented C interface.  You
12525: can use the undocumented @file{lib.fs} interface for callbacks.
12526: 
12527: In some cases you have to pass a function pointer to a C function,
12528: i.e., the library wants to call back to your application (and the
12529: pointed-to function is called a callback function).  You can pass the
12530: address of an existing C function (that you get with @code{lib-sym},
12531: @pxref{Low-Level C Interface Words}), but if there is no appropriate C
12532: function, you probably want to define the function as a Forth word.
12533: 
12534: @c I don't understand the existing callback interface from the example - anton
12535: 
12536: 
12537: @c > > Und dann gibt's noch die fptr-Deklaration, die einem
12538: @c > > C-Funktionspointer entspricht (Deklaration gleich wie bei
12539: @c > > Library-Funktionen, nur ohne den C-Namen, Aufruf mit der
12540: @c > > C-Funktionsadresse auf dem TOS).
12541: @c >
12542: @c > Ja, da bin ich dann ausgestiegen, weil ich aus dem Beispiel nicht
12543: @c > gesehen habe, wozu das gut ist.
12544: @c 
12545: @c Irgendwie muss ich den Callback ja testen. Und es soll ja auch 
12546: @c vorkommen, dass man von irgendwelchen kranken Interfaces einen 
12547: @c Funktionspointer übergeben bekommt, den man dann bei Gelegenheit 
12548: @c aufrufen muss. Also kann man den deklarieren, und das damit deklarierte 
12549: @c Wort verhält sich dann wie ein EXECUTE für alle C-Funktionen mit 
12550: @c demselben Prototyp.
12551: 
12552: 
12553: @node C interface internals, Low-Level C Interface Words, Callbacks, C Interface
12554: @subsection How the C interface works
12555: 
12556: The documented C interface works by generating a C code out of the
12557: declarations.
12558: 
12559: In particular, for every Forth word declared with @code{c-function},
12560: it generates a wrapper function in C that takes the Forth data from
12561: the Forth stacks, and calls the target C function with these data as
12562: arguments.  The C compiler then performs an implicit conversion
12563: between the Forth type from the stack, and the C type for the
12564: parameter, which is given by the C function prototype.  After the C
12565: function returns, the return value is likewise implicitly converted to
12566: a Forth type and written back on the stack.
12567: 
12568: The @code{\c} lines are literally included in the C code (but without
12569: the @code{\c}), and provide the necessary declarations so that the C
12570: compiler knows the C types and has enough information to perform the
12571: conversion.
12572: 
12573: These wrapper functions are eventually compiled and dynamically linked
12574: into Gforth, and then they can be called.
12575: 
12576: The libraries added with @code{add-lib} are used in the compile
12577: command line to specify dependent libraries with @code{-l@var{lib}},
12578: causing these libraries to be dynamically linked when the wrapper
12579: function is linked.
12580: 
12581: 
12582: @node Low-Level C Interface Words,  , C interface internals, C Interface
12583: @subsection Low-Level C Interface Words
12584: 
12585: doc-open-lib
12586: doc-lib-sym
12587: doc-lib-error
12588: doc-call-c
12589: 
12590: @c -------------------------------------------------------------
12591: @node Assembler and Code Words, Threading Words, C Interface, Words
12592: @section Assembler and Code Words
12593: @cindex assembler
12594: @cindex code words
12595: 
12596: @menu
12597: * Assembler Definitions::       Definitions in assembly language
12598: * Common Assembler::            Assembler Syntax
12599: * Common Disassembler::         
12600: * 386 Assembler::               Deviations and special cases
12601: * AMD64 Assembler::             
12602: * Alpha Assembler::             Deviations and special cases
12603: * MIPS assembler::              Deviations and special cases
12604: * PowerPC assembler::           Deviations and special cases
12605: * ARM Assembler::               Deviations and special cases
12606: * Other assemblers::            How to write them
12607: @end menu
12608: 
12609: @node Assembler Definitions, Common Assembler, Assembler and Code Words, Assembler and Code Words
12610: @subsection Definitions in assembly language
12611: 
12612: Gforth provides ways to implement words in assembly language (using
12613: @code{abi-code}...@code{end-code}), and also ways to define defining
12614: words with arbitrary run-time behaviour (like @code{does>}), where
12615: (unlike @code{does>}) the behaviour is not defined in Forth, but in
12616: assembly language (with @code{;code}).
12617: 
12618: However, the machine-independent nature of Gforth poses a few
12619: problems: First of all, Gforth runs on several architectures, so it
12620: can provide no standard assembler. It does provide assemblers for
12621: several of the architectures it runs on, though.  Moreover, you can
12622: use a system-independent assembler in Gforth, or compile machine code
12623: directly with @code{,} and @code{c,}.
12624: 
12625: Another problem is that the virtual machine registers of Gforth (the
12626: stack pointers and the virtual machine instruction pointer) depend on
12627: the installation and engine.  Also, which registers are free to use
12628: also depend on the installation and engine.  So any code written to
12629: run in the context of the Gforth virtual machine is essentially
12630: limited to the installation and engine it was developed for (it may
12631: run elsewhere, but you cannot rely on that).
12632: 
12633: Fortunately, you can define @code{abi-code} words in Gforth that are
12634: portable to any Gforth running on a platform with the same calling
12635: convention (ABI); typically this means portability to the same
12636: architecture/OS combination, sometimes crossing OS boundaries).
12637: 
12638: doc-assembler
12639: doc-init-asm
12640: doc-abi-code
12641: doc-end-code
12642: doc-code
12643: doc-;code
12644: doc-flush-icache
12645: 
12646: 
12647: If @code{flush-icache} does not work correctly, @code{abi-code} words
12648: etc. will not work (reliably), either.
12649: 
12650: The typical usage of these words can be shown most easily by analogy
12651: to the equivalent high-level defining words:
12652: 
12653: @example
12654: : foo                              abi-code foo
12655:    <high-level Forth words>              <assembler>
12656: ;                                  end-code
12657:                                 
12658: : bar                              : bar
12659:    <high-level Forth words>           <high-level Forth words>
12660:    CREATE                             CREATE
12661:       <high-level Forth words>           <high-level Forth words>
12662:    DOES>                              ;code
12663:       <high-level Forth words>           <assembler>
12664: ;                                  end-code
12665: @end example
12666: 
12667: For using @code{abi-code}, take a look at the ABI documentation of
12668: your platform to see how the parameters are passed (so you know where
12669: you get the stack pointers) and how the return value is passed (so you
12670: know where the data stack pointer is returned).  The ABI documentation
12671: also tells you which registers are saved by the caller (caller-saved),
12672: so you are free to destroy them in your code, and which registers have
12673: to be preserved by the called word (callee-saved), so you have to save
12674: them before using them, and restore them afterwards.  For some
12675: architectures and OSs we give short summaries of the parts of the
12676: calling convention in the appropriate sections.  More
12677: reverse-engineering oriented people can also find out about the
12678: passing and returning of the stack pointers through @code{see
12679: abi-call}.
12680: 
12681: Most ABIs pass the parameters through registers, but some (in
12682: particular the most common 386 (aka IA-32) calling conventions) pass
12683: them on the architectural stack.  The common ABIs all pass the return
12684: value in a register.
12685: 
12686: Other things you need to know for using @code{abi-code} is that both
12687: the data and the FP stack grow downwards (towards lower addresses) in
12688: Gforth, with @code{1 cells} size per cell, and @code{1 floats} size
12689: per FP value.
12690: 
12691: Here's an example of using @code{abi-code} on the 386 architecture:
12692: 
12693: @example
12694: abi-code my+ ( n1 n2 -- n )
12695: 4 sp d) ax mov \ sp into return reg
12696: ax )    cx mov \ tos
12697: 4 #     ax add \ update sp (pop)
12698: cx    ax ) add \ sec = sec+tos
12699: ret            \ return from my+
12700: end-code
12701: @end example
12702: 
12703: An AMD64 variant of this example can be found in @ref{AMD64 Assembler}.
12704: 
12705: Here's a 386 example that deals with FP values:
12706: 
12707: @example
12708: abi-code my-f+ ( r1 r2 -- r )
12709: 8 sp d) cx mov  \ load address of fp
12710: cx )    dx mov  \ load fp
12711: .fl dx )   fld  \ r2
12712: 8 #     dx add  \ update fp
12713: .fl dx )   fadd \ r1+r2
12714: .fl dx )   fstp \ store r
12715: dx    cx ) mov  \ store new fp
12716: 4 sp d) ax mov  \ sp into return reg
12717: ret             \ return from my-f+
12718: end-code
12719: @end example
12720: 
12721: 
12722: @node Common Assembler, Common Disassembler, Assembler Definitions, Assembler and Code Words
12723: @subsection Common Assembler
12724: 
12725: The assemblers in Gforth generally use a postfix syntax, i.e., the
12726: instruction name follows the operands.
12727: 
12728: The operands are passed in the usual order (the same that is used in the
12729: manual of the architecture).  Since they all are Forth words, they have
12730: to be separated by spaces; you can also use Forth words to compute the
12731: operands.
12732: 
12733: The instruction names usually end with a @code{,}.  This makes it easier
12734: to visually separate instructions if you put several of them on one
12735: line; it also avoids shadowing other Forth words (e.g., @code{and}).
12736: 
12737: Registers are usually specified by number; e.g., (decimal) @code{11}
12738: specifies registers R11 and F11 on the Alpha architecture (which one,
12739: depends on the instruction).  The usual names are also available, e.g.,
12740: @code{s2} for R11 on Alpha.
12741: 
12742: Control flow is specified similar to normal Forth code (@pxref{Arbitrary
12743: control structures}), with @code{if,}, @code{ahead,}, @code{then,},
12744: @code{begin,}, @code{until,}, @code{again,}, @code{cs-roll},
12745: @code{cs-pick}, @code{else,}, @code{while,}, and @code{repeat,}.  The
12746: conditions are specified in a way specific to each assembler.
12747: 
12748: The rest of this section is of interest mainly for those who want to
12749: define @code{code} words (instead of the more portable @code{abi-code}
12750: words).
12751: 
12752: Note that the register assignments of the Gforth engine can change
12753: between Gforth versions, or even between different compilations of the
12754: same Gforth version (e.g., if you use a different GCC version).  If
12755: you are using @code{CODE} instead of @code{ABI-CODE}, and you want to
12756: refer to Gforth's registers (e.g., the stack pointer or TOS), I
12757: recommend defining your own words for refering to these registers, and
12758: using them later on; then you can adapt to a changed register
12759: assignment.
12760: 
12761: The most common use of these registers is to end a @code{code}
12762: definition with a dispatch to the next word (the @code{next} routine).
12763: A portable way to do this is to jump to @code{' noop >code-address}
12764: (of course, this is less efficient than integrating the @code{next}
12765: code and scheduling it well).  When using @code{ABI-CODE}, you can
12766: just assemble a normal subroutine return (but make sure you return the
12767: data stack pointer).
12768: 
12769: Another difference between Gforth versions is that the top of stack is
12770: kept in memory in @code{gforth} and, on most platforms, in a register
12771: in @code{gforth-fast}.  For @code{ABI-CODE} definitions, any stack
12772: caching registers are guaranteed to be flushed to the stack, allowing
12773: you to reliably access the top of stack in memory.
12774: 
12775: @node  Common Disassembler, 386 Assembler, Common Assembler, Assembler and Code Words
12776: @subsection Common Disassembler
12777: @cindex disassembler, general
12778: @cindex gdb disassembler
12779: 
12780: You can disassemble a @code{code} word with @code{see}
12781: (@pxref{Debugging}).  You can disassemble a section of memory with
12782: 
12783: doc-discode
12784: 
12785: There are two kinds of disassembler for Gforth: The Forth disassembler
12786: (available on some CPUs) and the gdb disassembler (available on
12787: platforms with @command{gdb} and @command{mktemp}).  If both are
12788: available, the Forth disassembler is used by default.  If you prefer
12789: the gdb disassembler, say
12790: 
12791: @example
12792: ' disasm-gdb is discode
12793: @end example
12794: 
12795: If neither is available, @code{discode} performs @code{dump}.
12796: 
12797: The Forth disassembler generally produces output that can be fed into the
12798: assembler (i.e., same syntax, etc.).  It also includes additional
12799: information in comments.  In particular, the address of the instruction
12800: is given in a comment before the instruction.
12801: 
12802: The gdb disassembler produces output in the same format as the gdb
12803: @code{disassemble} command (@pxref{Machine Code,,Source and machine
12804: code,gdb,Debugging with GDB}), in the default flavour (AT&T syntax for
12805: the 386 and AMD64 architectures).
12806: 
12807: @code{See} may display more or less than the actual code of the word,
12808: because the recognition of the end of the code is unreliable.  You can
12809: use @code{discode} if it did not display enough.  It may display more, if
12810: the code word is not immediately followed by a named word.  If you have
12811: something else there, you can follow the word with @code{align latest ,}
12812: to ensure that the end is recognized.
12813: 
12814: @node 386 Assembler, AMD64 Assembler, Common Disassembler, Assembler and Code Words
12815: @subsection 386 Assembler
12816: 
12817: The 386 assembler included in Gforth was written by Bernd Paysan, it's
12818: available under GPL, and originally part of bigFORTH.
12819: 
12820: The 386 disassembler included in Gforth was written by Andrew McKewan
12821: and is in the public domain.
12822: 
12823: The disassembler displays code in an Intel-like prefix syntax.
12824: 
12825: The assembler uses a postfix syntax with AT&T-style parameter order
12826: (i.e., destination last).
12827: 
12828: The assembler includes all instruction of the Athlon, i.e. 486 core
12829: instructions, Pentium and PPro extensions, floating point, MMX, 3Dnow!,
12830: but not ISSE. It's an integrated 16- and 32-bit assembler. Default is 32
12831: bit, you can switch to 16 bit with .86 and back to 32 bit with .386.
12832: 
12833: There are several prefixes to switch between different operation sizes,
12834: @code{.b} for byte accesses, @code{.w} for word accesses, @code{.d} for
12835: double-word accesses. Addressing modes can be switched with @code{.wa}
12836: for 16 bit addresses, and @code{.da} for 32 bit addresses. You don't
12837: need a prefix for byte register names (@code{AL} et al).
12838: 
12839: For floating point operations, the prefixes are @code{.fs} (IEEE
12840: single), @code{.fl} (IEEE double), @code{.fx} (extended), @code{.fw}
12841: (word), @code{.fd} (double-word), and @code{.fq} (quad-word).  The
12842: default is @code{.fx}, so you need to specify @code{.fl} explicitly
12843: when dealing with Gforth FP values.
12844: 
12845: The MMX opcodes don't have size prefixes, they are spelled out like in
12846: the Intel assembler. Instead of move from and to memory, there are
12847: PLDQ/PLDD and PSTQ/PSTD.
12848: 
12849: The registers lack the 'e' prefix; even in 32 bit mode, eax is called
12850: ax.  Immediate values are indicated by postfixing them with @code{#},
12851: e.g., @code{3 #}.  Here are some examples of addressing modes in various
12852: syntaxes:
12853: 
12854: @example
12855: Gforth          Intel (NASM)   AT&T (gas)      Name
12856: .w ax           ax             %ax             register (16 bit)
12857: ax              eax            %eax            register (32 bit)
12858: 3 #             offset 3       $3              immediate
12859: 1000 #)         byte ptr 1000  1000            displacement
12860: bx )            [ebx]          (%ebx)          base
12861: 100 di d)       100[edi]       100(%edi)       base+displacement
12862: 20 ax *4 i#)    20[eax*4]      20(,%eax,4)     (index*scale)+displacement
12863: di ax *4 i)     [edi][eax*4]   (%edi,%eax,4)   base+(index*scale)
12864: 4 bx cx di)     4[ebx][ecx]    4(%ebx,%ecx)    base+index+displacement
12865: 12 sp ax *2 di) 12[esp][eax*2] 12(%esp,%eax,2) base+(index*scale)+displacement
12866: @end example
12867: 
12868: You can use @code{L)} and @code{LI)} instead of @code{D)} and
12869: @code{DI)} to enforce 32-bit displacement fields (useful for
12870: later patching).
12871: 
12872: Some example of instructions are:
12873: 
12874: @example
12875: ax bx mov             \ move ebx,eax
12876: 3 # ax mov            \ mov eax,3
12877: 100 di d) ax mov      \ mov eax,100[edi]
12878: 4 bx cx di) ax mov    \ mov eax,4[ebx][ecx]
12879: .w ax bx mov          \ mov bx,ax
12880: @end example
12881: 
12882: The following forms are supported for binary instructions:
12883: 
12884: @example
12885: <reg> <reg> <inst>
12886: <n> # <reg> <inst>
12887: <mem> <reg> <inst>
12888: <reg> <mem> <inst>
12889: <n> # <mem> <inst>
12890: @end example
12891: 
12892: The shift/rotate syntax is:
12893: 
12894: @example
12895: <reg/mem> 1 # shl \ shortens to shift without immediate
12896: <reg/mem> 4 # shl
12897: <reg/mem> cl shl
12898: @end example
12899: 
12900: Precede string instructions (@code{movs} etc.) with @code{.b} to get
12901: the byte version.
12902: 
12903: The control structure words @code{IF} @code{UNTIL} etc. must be preceded
12904: by one of these conditions: @code{vs vc u< u>= 0= 0<> u<= u> 0< 0>= ps
12905: pc < >= <= >}. (Note that most of these words shadow some Forth words
12906: when @code{assembler} is in front of @code{forth} in the search path,
12907: e.g., in @code{code} words).  Currently the control structure words use
12908: one stack item, so you have to use @code{roll} instead of @code{cs-roll}
12909: to shuffle them (you can also use @code{swap} etc.).
12910: 
12911: Based on the Intel ABI (used in Linux), @code{abi-code} words can find
12912: the data stack pointer at @code{4 sp d)}, and the address of the FP
12913: stack pointer at @code{8 sp d)}; the data stack pointer is returned in
12914: @code{ax}; @code{Ax}, @code{cx}, and @code{dx} are caller-saved, so
12915: you do not need to preserve their values inside the word.  You can
12916: return from the word with @code{ret}, the parameters are cleaned up by
12917: the caller.
12918: 
12919: For examples of 386 @code{abi-code} words, see @ref{Assembler Definitions}.
12920: 
12921: 
12922: @node AMD64 Assembler, Alpha Assembler, 386 Assembler, Assembler and Code Words
12923: @subsection AMD64 (x86_64) Assembler
12924: 
12925: The AMD64 assembler is a slightly modified version of the 386
12926: assembler, and as such shares most of the syntax.  Two new prefixes,
12927: @code{.q} and @code{.qa}, are provided to select 64-bit operand and
12928: address sizes respectively.  64-bit sizes are the default, so normally
12929: you only have to use the other prefixes.  Also there are additional
12930: register operands @code{R8}-@code{R15}.
12931: 
12932: The registers lack the 'e' or 'r' prefix; even in 64 bit mode,
12933: @code{rax} is called @code{ax}.  Additional register operands are
12934: available to refer to the lowest-significant byte of all registers:
12935: @code{R8L}-@code{R15L}, @code{SPL}, @code{BPL}, @code{SIL},
12936: @code{DIL}.
12937: 
12938: The Linux-AMD64 calling convention is to pass the first 6 integer
12939: parameters in rdi, rsi, rdx, rcx, r8 and r9 and to return the result
12940: in rax and rdx; to pass the first 8 FP parameters in xmm0--xmm7 and to
12941: return FP results in xmm0--xmm1.  So @code{abi-code} words get the
12942: data stack pointer in @code{di} and the address of the FP stack
12943: pointer in @code{si}, and return the data stack pointer in @code{ax}.
12944: The other caller-saved registers are: r10, r11, xmm8-xmm15.  This
12945: calling convention reportedly is also used in other non-Microsoft OSs.
12946: @c source: http://en.wikipedia.org/wiki/X86_calling_conventions#AMD64_ABI_convention
12947: 
12948: @c source: http://msdn.microsoft.com/en-us/library/9b372w95(v=VS.90).aspx
12949: Windows x64 passes the first four integer parameters in rcx, rdx, r8
12950: and r9 and return the integer result in rax.  The other caller-saved
12951: registers are r10 and r11.
12952: 
12953: Here is an example of an AMD64 @code{abi-code} word:
12954: 
12955: @example
12956: abi-code my+  ( n1 n2 -- n3 )
12957: \ SP passed in di, returned in ax,  address of FP passed in si
12958: 8 di d) ax lea        \ compute new sp in result reg
12959: di )    dx mov        \ get old tos
12960: dx    ax ) add        \ add to new tos
12961: ret
12962: end-code
12963: @end example
12964: 
12965: Here's a AMD64 example that deals with FP values:
12966: 
12967: @example
12968: abi-code my-f+  ( r1 r2 -- r )
12969: \ SP passed in di, returned in ax,  address of FP passed in si
12970: si )       dx mov         \ load fp
12971: 8 dx d)  xmm0 movsd       \ r2
12972: dx )     xmm0 addsd       \ r1+r2
12973: xmm0  8 dx d) movsd       \ store r
12974: 8 #      si ) add         \ update fp
12975: di         ax mov         \ sp into return reg
12976: ret
12977: end-code
12978: @end example
12979: 
12980: @node Alpha Assembler, MIPS assembler, AMD64 Assembler, Assembler and Code Words
12981: @subsection Alpha Assembler
12982: 
12983: The Alpha assembler and disassembler were originally written by Bernd
12984: Thallner.
12985: 
12986: The register names @code{a0}--@code{a5} are not available to avoid
12987: shadowing hex numbers.
12988: 
12989: Immediate forms of arithmetic instructions are distinguished by a
12990: @code{#} just before the @code{,}, e.g., @code{and#,} (note: @code{lda,}
12991: does not count as arithmetic instruction).
12992: 
12993: You have to specify all operands to an instruction, even those that
12994: other assemblers consider optional, e.g., the destination register for
12995: @code{br,}, or the destination register and hint for @code{jmp,}.
12996: 
12997: You can specify conditions for @code{if,} by removing the first @code{b}
12998: and the trailing @code{,} from a branch with a corresponding name; e.g.,
12999: 
13000: @example
13001: 11 fgt if, \ if F11>0e
13002:   ...
13003: endif,
13004: @end example
13005: 
13006: @code{fbgt,} gives @code{fgt}.  
13007: 
13008: @node MIPS assembler, PowerPC assembler, Alpha Assembler, Assembler and Code Words
13009: @subsection MIPS assembler
13010: 
13011: The MIPS assembler was originally written by Christian Pirker.
13012: 
13013: Currently the assembler and disassembler covers most of the MIPS32
13014: architecture and doesn't support FP instructions.
13015: 
13016: The register names @code{$a0}--@code{$a3} are not available to avoid
13017: shadowing hex numbers.  Use register numbers @code{$4}--@code{$7}
13018: instead.
13019: 
13020: Nothing distinguishes registers from immediate values.  Use explicit
13021: opcode names with the @code{i} suffix for instructions with immediate
13022: argument.  E.g. @code{addiu,} in place of @code{addu,}.
13023: 
13024: Where the architecture manual specifies several formats for the
13025: instruction (e.g., for @code{jalr,}),use the one with more arguments
13026: (i.e. two for @code{jalr,}).  When in doubt, see
13027: @code{arch/mips/testasm.fs} for an example of correct use.
13028: 
13029: Branches and jumps in the MIPS architecture have a delay slot.  You
13030: have to fill it manually (the simplest way is to use @code{nop,}), the
13031: assembler does not do it for you (unlike @command{as}).  Even
13032: @code{if,}, @code{ahead,}, @code{until,}, @code{again,},
13033: @code{while,}, @code{else,} and @code{repeat,} need a delay slot.
13034: Since @code{begin,} and @code{then,} just specify branch targets, they
13035: are not affected.  For branches the argument specifying the target is
13036: a relative address.  Add the address of the delay slot to get the
13037: absolute address.
13038: 
13039: Note that you must not put branches nor jumps (nor control-flow
13040: instructions) into the delay slot.  Also it is a bad idea to put
13041: pseudo-ops such as @code{li,} into a delay slot, as these may expand
13042: to several instructions.  The MIPS I architecture also had load delay
13043: slots, and newer MIPSes still have restrictions on using @code{mfhi,}
13044: and @code{mflo,}.  Be careful to satisfy these restrictions, the
13045: assembler does not do it for you.
13046: 
13047: Some example of instructions are:
13048: 
13049: @example
13050: $ra  12 $sp  sw,         \ sw    ra,12(sp)
13051: $4    8 $s0  lw,         \ lw    a0,8(s0)
13052: $v0  $0  lui,            \ lui   v0,0x0
13053: $s0  $s4  $12  addiu,    \ addiu s0,s4,0x12
13054: $s0  $s4  $4  addu,      \ addu  s0,s4,$a0
13055: $ra  $t9  jalr,          \ jalr  t9
13056: @end example
13057: 
13058: You can specify the conditions for @code{if,} etc. by taking a
13059: conditional branch and leaving away the @code{b} at the start and the
13060: @code{,} at the end.  E.g.,
13061: 
13062: @example
13063: 4 5 eq if,
13064:   ... \ do something if $4 equals $5
13065: then,
13066: @end example
13067: 
13068: The calling conventions for 32-bit MIPS machines is to pass the first
13069: 4 arguments in registers @code{$4}..@code{$7}, and to use
13070: @code{$v0}-@code{$v1} for return values.  In addition to these
13071: registers, it is ok to clobber registers @code{$t0}-@code{$t8} without
13072: saving and restoring them.
13073: 
13074: If you use @code{jalr,} to call into dynamic library routines, you
13075: must first load the called function's address into @code{$t9}, which
13076: is used by position-indirect code to do relative memory accesses.
13077: 
13078: Here is an example of a MIPS32 @code{abi-code} word:
13079: 
13080: @example
13081: abi-code my+  ( n1 n2 -- n3 )
13082:   \ SP passed in $4, returned in $v0
13083:   $t0  4 $4  lw,         \ load n1, n2 from stack
13084:   $t1  0 $4  lw,    
13085:   $t0  $t0  $t1  addu,   \ add n1+n2, result in $t0
13086:   $t0  4 $4  sw,         \ store result (overwriting n1)
13087:   $ra  jr,               \ return to caller
13088:   $v0  $4  4  addiu,     \ (delay slot) return uptated SP in $v0
13089: end-code
13090: @end example
13091: 
13092: @node PowerPC assembler, ARM Assembler, MIPS assembler, Assembler and Code Words
13093: @subsection PowerPC assembler
13094: 
13095: The PowerPC assembler and disassembler were contributed by Michal
13096: Revucky.
13097: 
13098: This assembler does not follow the convention of ending mnemonic names
13099: with a ``,'', so some mnemonic names shadow regular Forth words (in
13100: particular: @code{and or xor fabs}); so if you want to use the Forth
13101: words, you have to make them visible first, e.g., with @code{also
13102: forth}.
13103: 
13104: Registers are referred to by their number, e.g., @code{9} means the
13105: integer register 9 or the FP register 9 (depending on the
13106: instruction).
13107: 
13108: Because there is no way to distinguish registers from immediate values,
13109: you have to explicitly use the immediate forms of instructions, i.e.,
13110: @code{addi,}, not just @code{add,}.
13111: 
13112: The assembler and disassembler usually support the most general form
13113: of an instruction, but usually not the shorter forms (especially for
13114: branches).
13115: 
13116: 
13117: @node ARM Assembler, Other assemblers, PowerPC assembler, Assembler and Code Words
13118: @subsection ARM Assembler
13119: 
13120: The ARM assembler includes all instruction of ARM architecture version
13121: 4, and the BLX instruction from architecture 5.  It does not (yet)
13122: have support for Thumb instructions.  It also lacks support for any
13123: co-processors.
13124: 
13125: The assembler uses a postfix syntax with the same operand order as
13126: used in the ARM Architecture Reference Manual.  Mnemonics are suffixed
13127: by a comma.
13128: 
13129: Registers are specified by their names @code{r0} through @code{r15},
13130: with the aliases @code{pc}, @code{lr}, @code{sp}, @code{ip} and
13131: @code{fp} provided for convenience.  Note that @code{ip} refers to
13132: the``intra procedure call scratch register'' (@code{r12}) and does not
13133: refer to an instruction pointer.  @code{sp} refers to the ARM ABI
13134: stack pointer (@code{r13}) and not the Forth stack pointer.
13135: 
13136: Condition codes can be specified anywhere in the instruction, but will
13137: be most readable if specified just in front of the mnemonic.  The 'S'
13138: flag is not a separate word, but encoded into instruction mnemonics,
13139: ie. just use @code{adds,} instead of @code{add,} if you want the
13140: status register to be updated.
13141: 
13142: The following table lists the syntax of operands for general
13143: instructions:
13144: 
13145: @example
13146: Gforth          normal assembler      description
13147: 123 #           #123                  immediate
13148: r12             r12                   register
13149: r12 4 #LSL      r12, LSL #4           shift left by immediate
13150: r12 r1 #LSL     r12, LSL r1           shift left by register
13151: r12 4 #LSR      r12, LSR #4           shift right by immediate
13152: r12 r1 #LSR     r12, LSR r1           shift right by register
13153: r12 4 #ASR      r12, ASR #4           arithmetic shift right
13154: r12 r1 #ASR     r12, ASR r1           ... by register
13155: r12 4 #ROR      r12, ROR #4           rotate right by immediate
13156: r12 r1 #ROR     r12, ROR r1           ... by register
13157: r12 RRX         r12, RRX              rotate right with extend by 1
13158: @end example
13159: 
13160: Memory operand syntax is listed in this table:
13161: 
13162: @example
13163: Gforth            normal assembler      description
13164: r4 ]              [r4]                  register
13165: r4 4 #]           [r4, #+4]             register with immediate offset
13166: r4 -4 #]          [r4, #-4]             with negative offset
13167: r4 r1 +]          [r4, +r1]             register with register offset
13168: r4 r1 -]          [r4, -r1]             with negated register offset
13169: r4 r1 2 #LSL -]   [r4, -r1, LSL #2]     with negated and shifted offset
13170: r4 4 #]!          [r4, #+4]!            immediate preincrement
13171: r4 r1 +]!         [r4, +r1]!            register preincrement
13172: r4 r1 -]!         [r4, +r1]!            register predecrement
13173: r4 r1 2 #LSL +]!  [r4, +r1, LSL #2]!    shifted preincrement
13174: r4 -4 ]#          [r4], #-4             immediate postdecrement
13175: r4 r1 ]+          [r4], r1              register postincrement
13176: r4 r1 ]-          [r4], -r1             register postdecrement
13177: r4 r1 2 #LSL ]-   [r4], -r1, LSL #2     shifted postdecrement
13178: ' xyz >body [#]   xyz                   PC-relative addressing
13179: @end example
13180: 
13181: Register lists for load/store multiple instructions are started and
13182: terminated by using the words @code{@{} and @code{@}} respectively.
13183: Between braces, register names can be listed one by one or register
13184: ranges can be formed by using the postfix operator @code{r-r}.  The
13185: @code{^} flag is not encoded in the register list operand, but instead
13186: directly encoded into the instruction mnemonic, ie. use @code{^ldm,}
13187: and @code{^stm,}.
13188: 
13189: Addressing modes for load/store multiple are not encoded as
13190: instruction suffixes, but instead specified like an addressing mode,
13191: Use one of @code{DA}, @code{IA}, @code{DB}, @code{IB}, @code{DA!},
13192: @code{IA!}, @code{DB!} or @code{IB!}.
13193: 
13194: The following table gives some examples:
13195: 
13196: @example
13197: Gforth                           normal assembler
13198: r4 ia  @{ r0 r7 r8 @}  stm,        stmia    r4, @{r0,r7,r8@}
13199: r4 db!  @{ r0 r7 r8 @}  ldm,       ldmdb    r4!, @{r0,r7,r8@}
13200: sp ia!  @{ r0 r15 r-r @}  ^ldm,    ldmfd    sp!, @{r0-r15@}^
13201: @end example
13202: 
13203: Control structure words typical for Forth assemblers are available:
13204: @code{if,} @code{ahead,} @code{then,} @code{else,} @code{begin,}
13205: @code{until,} @code{again,} @code{while,} @code{repeat,}
13206: @code{repeat-until,}.  Conditions are specified in front of these words:
13207: 
13208: @example
13209: r1 r2 cmp,    \ compare r1 and r2
13210: eq if,        \ equal?
13211:    ...          \ code executed if r1 == r2
13212: then,
13213: @end example
13214: 
13215: Example of a definition using the ARM assembler:
13216: 
13217: @example
13218: abi-code my+ ( n1 n2 --  n3 )
13219:    \ arm abi: r0=SP, r1=&FP, r2,r3,r12 saved by caller
13220:    r0 IA!  @{ r2 r3 @}  ldm,     \ pop r2 = n2, r3 = n1
13221:    r3  r2  r3         add,     \ r3 = n1+n1
13222:    r3  r0 -4 #]!      str,     \ push r3
13223:    pc  lr             mov,     \ return to caller, new SP in r0
13224: end-code
13225: @end example
13226: 
13227: @node Other assemblers,  , ARM Assembler, Assembler and Code Words
13228: @subsection Other assemblers
13229: 
13230: If you want to contribute another assembler/disassembler, please contact
13231: us (@email{anton@@mips.complang.tuwien.ac.at}) to check if we have such
13232: an assembler already.  If you are writing them from scratch, please use
13233: a similar syntax style as the one we use (i.e., postfix, commas at the
13234: end of the instruction names, @pxref{Common Assembler}); make the output
13235: of the disassembler be valid input for the assembler, and keep the style
13236: similar to the style we used.
13237: 
13238: Hints on implementation: The most important part is to have a good test
13239: suite that contains all instructions.  Once you have that, the rest is
13240: easy.  For actual coding you can take a look at
13241: @file{arch/mips/disasm.fs} to get some ideas on how to use data for both
13242: the assembler and disassembler, avoiding redundancy and some potential
13243: bugs.  You can also look at that file (and @pxref{Advanced does> usage
13244: example}) to get ideas how to factor a disassembler.
13245: 
13246: Start with the disassembler, because it's easier to reuse data from the
13247: disassembler for the assembler than the other way round.
13248: 
13249: For the assembler, take a look at @file{arch/alpha/asm.fs}, which shows
13250: how simple it can be.
13251: 
13252: 
13253: 
13254: 
13255: @c -------------------------------------------------------------
13256: @node Threading Words, Passing Commands to the OS, Assembler and Code Words, Words
13257: @section Threading Words
13258: @cindex threading words
13259: 
13260: @cindex code address
13261: These words provide access to code addresses and other threading stuff
13262: in Gforth (and, possibly, other interpretive Forths). It more or less
13263: abstracts away the differences between direct and indirect threading
13264: (and, for direct threading, the machine dependences). However, at
13265: present this wordset is still incomplete. It is also pretty low-level;
13266: some day it will hopefully be made unnecessary by an internals wordset
13267: that abstracts implementation details away completely.
13268: 
13269: The terminology used here stems from indirect threaded Forth systems; in
13270: such a system, the XT of a word is represented by the CFA (code field
13271: address) of a word; the CFA points to a cell that contains the code
13272: address.  The code address is the address of some machine code that
13273: performs the run-time action of invoking the word (e.g., the
13274: @code{dovar:} routine pushes the address of the body of the word (a
13275: variable) on the stack
13276: ).
13277: 
13278: @cindex code address
13279: @cindex code field address
13280: In an indirect threaded Forth, you can get the code address of @i{name}
13281: with @code{' @i{name} @@}; in Gforth you can get it with @code{' @i{name}
13282: >code-address}, independent of the threading method.
13283: 
13284: doc-threading-method
13285: doc->code-address
13286: doc-code-address!
13287: 
13288: @cindex @code{does>}-handler
13289: @cindex @code{does>}-code
13290: For a word defined with @code{DOES>}, the code address usually points to
13291: a jump instruction (the @dfn{does-handler}) that jumps to the dodoes
13292: routine (in Gforth on some platforms, it can also point to the dodoes
13293: routine itself).  What you are typically interested in, though, is
13294: whether a word is a @code{DOES>}-defined word, and what Forth code it
13295: executes; @code{>does-code} tells you that.
13296: 
13297: doc->does-code
13298: 
13299: To create a @code{DOES>}-defined word with the following basic words,
13300: you have to set up a @code{DOES>}-handler with @code{does-handler!};
13301: @code{/does-handler} aus behind you have to place your executable Forth
13302: code.  Finally you have to create a word and modify its behaviour with
13303: @code{does-handler!}.
13304: 
13305: doc-does-code!
13306: doc-does-handler!
13307: doc-/does-handler
13308: 
13309: The code addresses produced by various defining words are produced by
13310: the following words:
13311: 
13312: doc-docol:
13313: doc-docon:
13314: doc-dovar:
13315: doc-douser:
13316: doc-dodefer:
13317: doc-dofield:
13318: 
13319: @cindex definer
13320: The following two words generalize @code{>code-address},
13321: @code{>does-code}, @code{code-address!}, and @code{does-code!}:
13322: 
13323: doc->definer
13324: doc-definer!
13325: 
13326: @c -------------------------------------------------------------
13327: @node Passing Commands to the OS, Keeping track of Time, Threading Words, Words
13328: @section Passing Commands to the Operating System
13329: @cindex operating system - passing commands
13330: @cindex shell commands
13331: 
13332: Gforth allows you to pass an arbitrary string to the host operating
13333: system shell (if such a thing exists) for execution.
13334: 
13335: doc-sh
13336: doc-system
13337: doc-$?
13338: doc-getenv
13339: 
13340: @c -------------------------------------------------------------
13341: @node Keeping track of Time, Miscellaneous Words, Passing Commands to the OS, Words
13342: @section Keeping track of Time
13343: @cindex time-related words
13344: 
13345: doc-ms
13346: doc-time&date
13347: doc-utime
13348: doc-cputime
13349: 
13350: 
13351: @c -------------------------------------------------------------
13352: @node Miscellaneous Words,  , Keeping track of Time, Words
13353: @section Miscellaneous Words
13354: @cindex miscellaneous words
13355: 
13356: @comment TODO find homes for these
13357: 
13358: These section lists the ANS Forth words that are not documented
13359: elsewhere in this manual. Ultimately, they all need proper homes.
13360: 
13361: doc-quit
13362: 
13363: The following ANS Forth words are not currently supported by Gforth 
13364: (@pxref{ANS conformance}):
13365: 
13366: @code{EDITOR} 
13367: @code{EMIT?} 
13368: @code{FORGET} 
13369: 
13370: @c ******************************************************************
13371: @node Error messages, Tools, Words, Top
13372: @chapter Error messages
13373: @cindex error messages
13374: @cindex backtrace
13375: 
13376: A typical Gforth error message looks like this:
13377: 
13378: @example
13379: in file included from \evaluated string/:-1
13380: in file included from ./yyy.fs:1
13381: ./xxx.fs:4: Invalid memory address
13382: >>>bar<<<
13383: Backtrace:
13384: $400E664C @@
13385: $400E6664 foo
13386: @end example
13387: 
13388: The message identifying the error is @code{Invalid memory address}.  The
13389: error happened when text-interpreting line 4 of the file
13390: @file{./xxx.fs}. This line is given (it contains @code{bar}), and the
13391: word on the line where the error happened, is pointed out (with
13392: @code{>>>} and @code{<<<}).
13393: 
13394: The file containing the error was included in line 1 of @file{./yyy.fs},
13395: and @file{yyy.fs} was included from a non-file (in this case, by giving
13396: @file{yyy.fs} as command-line parameter to Gforth).
13397: 
13398: At the end of the error message you find a return stack dump that can be
13399: interpreted as a backtrace (possibly empty). On top you find the top of
13400: the return stack when the @code{throw} happened, and at the bottom you
13401: find the return stack entry just above the return stack of the topmost
13402: text interpreter.
13403: 
13404: To the right of most return stack entries you see a guess for the word
13405: that pushed that return stack entry as its return address. This gives a
13406: backtrace. In our case we see that @code{bar} called @code{foo}, and
13407: @code{foo} called @code{@@} (and @code{@@} had an @emph{Invalid memory
13408: address} exception).
13409: 
13410: Note that the backtrace is not perfect: We don't know which return stack
13411: entries are return addresses (so we may get false positives); and in
13412: some cases (e.g., for @code{abort"}) we cannot determine from the return
13413: address the word that pushed the return address, so for some return
13414: addresses you see no names in the return stack dump.
13415: 
13416: @cindex @code{catch} and backtraces
13417: The return stack dump represents the return stack at the time when a
13418: specific @code{throw} was executed.  In programs that make use of
13419: @code{catch}, it is not necessarily clear which @code{throw} should be
13420: used for the return stack dump (e.g., consider one @code{throw} that
13421: indicates an error, which is caught, and during recovery another error
13422: happens; which @code{throw} should be used for the stack dump?).
13423: Gforth presents the return stack dump for the first @code{throw} after
13424: the last executed (not returned-to) @code{catch} or @code{nothrow};
13425: this works well in the usual case. To get the right backtrace, you
13426: usually want to insert @code{nothrow} or @code{['] false catch drop}
13427: after a @code{catch} if the error is not rethrown.
13428: 
13429: @cindex @code{gforth-fast} and backtraces
13430: @cindex @code{gforth-fast}, difference from @code{gforth}
13431: @cindex backtraces with @code{gforth-fast}
13432: @cindex return stack dump with @code{gforth-fast}
13433: @code{Gforth} is able to do a return stack dump for throws generated
13434: from primitives (e.g., invalid memory address, stack empty etc.);
13435: @code{gforth-fast} is only able to do a return stack dump from a
13436: directly called @code{throw} (including @code{abort} etc.).  Given an
13437: exception caused by a primitive in @code{gforth-fast}, you will
13438: typically see no return stack dump at all; however, if the exception is
13439: caught by @code{catch} (e.g., for restoring some state), and then
13440: @code{throw}n again, the return stack dump will be for the first such
13441: @code{throw}.
13442: 
13443: @c ******************************************************************
13444: @node Tools, ANS conformance, Error messages, Top
13445: @chapter Tools
13446: 
13447: @menu
13448: * ANS Report::                  Report the words used, sorted by wordset.
13449: * Stack depth changes::         Where does this stack item come from?
13450: @end menu
13451: 
13452: See also @ref{Emacs and Gforth}.
13453: 
13454: @node ANS Report, Stack depth changes, Tools, Tools
13455: @section @file{ans-report.fs}: Report the words used, sorted by wordset
13456: @cindex @file{ans-report.fs}
13457: @cindex report the words used in your program
13458: @cindex words used in your program
13459: 
13460: If you want to label a Forth program as ANS Forth Program, you must
13461: document which wordsets the program uses; for extension wordsets, it is
13462: helpful to list the words the program requires from these wordsets
13463: (because Forth systems are allowed to provide only some words of them).
13464: 
13465: The @file{ans-report.fs} tool makes it easy for you to determine which
13466: words from which wordset and which non-ANS words your application
13467: uses. You simply have to include @file{ans-report.fs} before loading the
13468: program you want to check. After loading your program, you can get the
13469: report with @code{print-ans-report}. A typical use is to run this as
13470: batch job like this:
13471: @example
13472: gforth ans-report.fs myprog.fs -e "print-ans-report bye"
13473: @end example
13474: 
13475: The output looks like this (for @file{compat/control.fs}):
13476: @example
13477: The program uses the following words
13478: from CORE :
13479: : POSTPONE THEN ; immediate ?dup IF 0= 
13480: from BLOCK-EXT :
13481: \ 
13482: from FILE :
13483: ( 
13484: @end example
13485: 
13486: @subsection Caveats
13487: 
13488: Note that @file{ans-report.fs} just checks which words are used, not whether
13489: they are used in an ANS Forth conforming way!
13490: 
13491: Some words are defined in several wordsets in the
13492: standard. @file{ans-report.fs} reports them for only one of the
13493: wordsets, and not necessarily the one you expect. It depends on usage
13494: which wordset is the right one to specify. E.g., if you only use the
13495: compilation semantics of @code{S"}, it is a Core word; if you also use
13496: its interpretation semantics, it is a File word.
13497: 
13498: 
13499: @node Stack depth changes,  , ANS Report, Tools
13500: @section Stack depth changes during interpretation
13501: @cindex @file{depth-changes.fs}
13502: @cindex depth changes during interpretation
13503: @cindex stack depth changes during interpretation
13504: @cindex items on the stack after interpretation
13505: 
13506: Sometimes you notice that, after loading a file, there are items left
13507: on the stack.  The tool @file{depth-changes.fs} helps you find out
13508: quickly where in the file these stack items are coming from.
13509: 
13510: The simplest way of using @file{depth-changes.fs} is to include it
13511: before the file(s) you want to check, e.g.:
13512: 
13513: @example
13514: gforth depth-changes.fs my-file.fs
13515: @end example
13516: 
13517: This will compare the stack depths of the data and FP stack at every
13518: empty line (in interpretation state) against these depths at the last
13519: empty line (in interpretation state).  If the depths are not equal,
13520: the position in the file and the stack contents are printed with
13521: @code{~~} (@pxref{Debugging}).  This indicates that a stack depth
13522: change has occured in the paragraph of non-empty lines before the
13523: indicated line.  It is a good idea to leave an empty line at the end
13524: of the file, so the last paragraph is checked, too.
13525: 
13526: Checking only at empty lines usually works well, but sometimes you
13527: have big blocks of non-empty lines (e.g., when building a big table),
13528: and you want to know where in this block the stack depth changed.  You
13529: can check all interpreted lines with
13530: 
13531: @example
13532: gforth depth-changes.fs -e "' all-lines is depth-changes-filter" my-file.fs
13533: @end example
13534: 
13535: This checks the stack depth at every end-of-line.  So the depth change
13536: occured in the line reported by the @code{~~} (not in the line
13537: before).
13538: 
13539: Note that, while this offers better accuracy in indicating where the
13540: stack depth changes, it will often report many intentional stack depth
13541: changes (e.g., when an interpreted computation stretches across
13542: several lines).  You can suppress the checking of some lines by
13543: putting backslashes at the end of these lines (not followed by white
13544: space), and using
13545: 
13546: @example
13547: gforth depth-changes.fs -e "' most-lines is depth-changes-filter" my-file.fs
13548: @end example
13549: 
13550: @c ******************************************************************
13551: @node ANS conformance, Standard vs Extensions, Tools, Top
13552: @chapter ANS conformance
13553: @cindex ANS conformance of Gforth
13554: 
13555: To the best of our knowledge, Gforth is an
13556: 
13557: ANS Forth System
13558: @itemize @bullet
13559: @item providing the Core Extensions word set
13560: @item providing the Block word set
13561: @item providing the Block Extensions word set
13562: @item providing the Double-Number word set
13563: @item providing the Double-Number Extensions word set
13564: @item providing the Exception word set
13565: @item providing the Exception Extensions word set
13566: @item providing the Facility word set
13567: @item providing @code{EKEY}, @code{EKEY>CHAR}, @code{EKEY?}, @code{MS} and @code{TIME&DATE} from the Facility Extensions word set
13568: @item providing the File Access word set
13569: @item providing the File Access Extensions word set
13570: @item providing the Floating-Point word set
13571: @item providing the Floating-Point Extensions word set
13572: @item providing the Locals word set
13573: @item providing the Locals Extensions word set
13574: @item providing the Memory-Allocation word set
13575: @item providing the Memory-Allocation Extensions word set (that one's easy)
13576: @item providing the Programming-Tools word set
13577: @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
13578: @item providing the Search-Order word set
13579: @item providing the Search-Order Extensions word set
13580: @item providing the String word set
13581: @item providing the String Extensions word set (another easy one)
13582: @end itemize
13583: 
13584: Gforth has the following environmental restrictions:
13585: 
13586: @cindex environmental restrictions
13587: @itemize @bullet
13588: @item
13589: While processing the OS command line, if an exception is not caught,
13590: Gforth exits with a non-zero exit code instyead of performing QUIT.
13591: 
13592: @item
13593: When an @code{throw} is performed after a @code{query}, Gforth does not
13594: allways restore the input source specification in effect at the
13595: corresponding catch.
13596: 
13597: @end itemize
13598: 
13599: 
13600: @cindex system documentation
13601: In addition, ANS Forth systems are required to document certain
13602: implementation choices. This chapter tries to meet these
13603: requirements. In many cases it gives a way to ask the system for the
13604: information instead of providing the information directly, in
13605: particular, if the information depends on the processor, the operating
13606: system or the installation options chosen, or if they are likely to
13607: change during the maintenance of Gforth.
13608: 
13609: @comment The framework for the rest has been taken from pfe.
13610: 
13611: @menu
13612: * The Core Words::              
13613: * The optional Block word set::  
13614: * The optional Double Number word set::  
13615: * The optional Exception word set::  
13616: * The optional Facility word set::  
13617: * The optional File-Access word set::  
13618: * The optional Floating-Point word set::  
13619: * The optional Locals word set::  
13620: * The optional Memory-Allocation word set::  
13621: * The optional Programming-Tools word set::  
13622: * The optional Search-Order word set::  
13623: @end menu
13624: 
13625: 
13626: @c =====================================================================
13627: @node The Core Words, The optional Block word set, ANS conformance, ANS conformance
13628: @comment  node-name,  next,  previous,  up
13629: @section The Core Words
13630: @c =====================================================================
13631: @cindex core words, system documentation
13632: @cindex system documentation, core words
13633: 
13634: @menu
13635: * core-idef::                   Implementation Defined Options                   
13636: * core-ambcond::                Ambiguous Conditions                
13637: * core-other::                  Other System Documentation                  
13638: @end menu
13639: 
13640: @c ---------------------------------------------------------------------
13641: @node core-idef, core-ambcond, The Core Words, The Core Words
13642: @subsection Implementation Defined Options
13643: @c ---------------------------------------------------------------------
13644: @cindex core words, implementation-defined options
13645: @cindex implementation-defined options, core words
13646: 
13647: 
13648: @table @i
13649: @item (Cell) aligned addresses:
13650: @cindex cell-aligned addresses
13651: @cindex aligned addresses
13652: processor-dependent. Gforth's alignment words perform natural alignment
13653: (e.g., an address aligned for a datum of size 8 is divisible by
13654: 8). Unaligned accesses usually result in a @code{-23 THROW}.
13655: 
13656: @item @code{EMIT} and non-graphic characters:
13657: @cindex @code{EMIT} and non-graphic characters
13658: @cindex non-graphic characters and @code{EMIT}
13659: The character is output using the C library function (actually, macro)
13660: @code{putc}.
13661: 
13662: @item character editing of @code{ACCEPT} and @code{EXPECT}:
13663: @cindex character editing of @code{ACCEPT} and @code{EXPECT}
13664: @cindex editing in @code{ACCEPT} and @code{EXPECT}
13665: @cindex @code{ACCEPT}, editing
13666: @cindex @code{EXPECT}, editing
13667: This is modeled on the GNU readline library (@pxref{Readline
13668: Interaction, , Command Line Editing, readline, The GNU Readline
13669: Library}) with Emacs-like key bindings. @kbd{Tab} deviates a little by
13670: producing a full word completion every time you type it (instead of
13671: producing the common prefix of all completions). @xref{Command-line editing}.
13672: 
13673: @item character set:
13674: @cindex character set
13675: The character set of your computer and display device. Gforth is
13676: 8-bit-clean (but some other component in your system may make trouble).
13677: 
13678: @item Character-aligned address requirements:
13679: @cindex character-aligned address requirements
13680: installation-dependent. Currently a character is represented by a C
13681: @code{unsigned char}; in the future we might switch to @code{wchar_t}
13682: (Comments on that requested).
13683: 
13684: @item character-set extensions and matching of names:
13685: @cindex character-set extensions and matching of names
13686: @cindex case-sensitivity for name lookup
13687: @cindex name lookup, case-sensitivity
13688: @cindex locale and case-sensitivity
13689: Any character except the ASCII NUL character can be used in a
13690: name. Matching is case-insensitive (except in @code{TABLE}s). The
13691: matching is performed using the C library function @code{strncasecmp}, whose
13692: function is probably influenced by the locale. E.g., the @code{C} locale
13693: does not know about accents and umlauts, so they are matched
13694: case-sensitively in that locale. For portability reasons it is best to
13695: write programs such that they work in the @code{C} locale. Then one can
13696: use libraries written by a Polish programmer (who might use words
13697: containing ISO Latin-2 encoded characters) and by a French programmer
13698: (ISO Latin-1) in the same program (of course, @code{WORDS} will produce
13699: funny results for some of the words (which ones, depends on the font you
13700: are using)). Also, the locale you prefer may not be available in other
13701: operating systems. Hopefully, Unicode will solve these problems one day.
13702: 
13703: @item conditions under which control characters match a space delimiter:
13704: @cindex space delimiters
13705: @cindex control characters as delimiters
13706: If @code{word} is called with the space character as a delimiter, all
13707: white-space characters (as identified by the C macro @code{isspace()})
13708: are delimiters. @code{Parse}, on the other hand, treats space like other
13709: delimiters.  @code{Parse-name}, which is used by the outer
13710: interpreter (aka text interpreter) by default, treats all white-space
13711: characters as delimiters.
13712: 
13713: @item format of the control-flow stack:
13714: @cindex control-flow stack, format
13715: The data stack is used as control-flow stack. The size of a control-flow
13716: stack item in cells is given by the constant @code{cs-item-size}. At the
13717: time of this writing, an item consists of a (pointer to a) locals list
13718: (third), an address in the code (second), and a tag for identifying the
13719: item (TOS). The following tags are used: @code{defstart},
13720: @code{live-orig}, @code{dead-orig}, @code{dest}, @code{do-dest},
13721: @code{scopestart}.
13722: 
13723: @item conversion of digits > 35
13724: @cindex digits > 35
13725: The characters @code{[\]^_'} are the digits with the decimal value
13726: 36@minus{}41. There is no way to input many of the larger digits.
13727: 
13728: @item display after input terminates in @code{ACCEPT} and @code{EXPECT}:
13729: @cindex @code{EXPECT}, display after end of input
13730: @cindex @code{ACCEPT}, display after end of input
13731: The cursor is moved to the end of the entered string. If the input is
13732: terminated using the @kbd{Return} key, a space is typed.
13733: 
13734: @item exception abort sequence of @code{ABORT"}:
13735: @cindex exception abort sequence of @code{ABORT"}
13736: @cindex @code{ABORT"}, exception abort sequence
13737: The error string is stored into the variable @code{"error} and a
13738: @code{-2 throw} is performed.
13739: 
13740: @item input line terminator:
13741: @cindex input line terminator
13742: @cindex line terminator on input
13743: @cindex newline character on input
13744: For interactive input, @kbd{C-m} (CR) and @kbd{C-j} (LF) terminate
13745: lines. One of these characters is typically produced when you type the
13746: @kbd{Enter} or @kbd{Return} key.
13747: 
13748: @item maximum size of a counted string:
13749: @cindex maximum size of a counted string
13750: @cindex counted string, maximum size
13751: @code{s" /counted-string" environment? drop .}. Currently 255 characters
13752: on all platforms, but this may change.
13753: 
13754: @item maximum size of a parsed string:
13755: @cindex maximum size of a parsed string
13756: @cindex parsed string, maximum size
13757: Given by the constant @code{/line}. Currently 255 characters.
13758: 
13759: @item maximum size of a definition name, in characters:
13760: @cindex maximum size of a definition name, in characters
13761: @cindex name, maximum length
13762: MAXU/8
13763: 
13764: @item maximum string length for @code{ENVIRONMENT?}, in characters:
13765: @cindex maximum string length for @code{ENVIRONMENT?}, in characters
13766: @cindex @code{ENVIRONMENT?} string length, maximum
13767: MAXU/8
13768: 
13769: @item method of selecting the user input device:
13770: @cindex user input device, method of selecting
13771: The user input device is the standard input. There is currently no way to
13772: change it from within Gforth. However, the input can typically be
13773: redirected in the command line that starts Gforth.
13774: 
13775: @item method of selecting the user output device:
13776: @cindex user output device, method of selecting
13777: @code{EMIT} and @code{TYPE} output to the file-id stored in the value
13778: @code{outfile-id} (@code{stdout} by default). Gforth uses unbuffered
13779: output when the user output device is a terminal, otherwise the output
13780: is buffered.
13781: 
13782: @item methods of dictionary compilation:
13783: What are we expected to document here?
13784: 
13785: @item number of bits in one address unit:
13786: @cindex number of bits in one address unit
13787: @cindex address unit, size in bits
13788: @code{s" address-units-bits" environment? drop .}. 8 in all current
13789: platforms.
13790: 
13791: @item number representation and arithmetic:
13792: @cindex number representation and arithmetic
13793: Processor-dependent. Binary two's complement on all current platforms.
13794: 
13795: @item ranges for integer types:
13796: @cindex ranges for integer types
13797: @cindex integer types, ranges
13798: Installation-dependent. Make environmental queries for @code{MAX-N},
13799: @code{MAX-U}, @code{MAX-D} and @code{MAX-UD}. The lower bounds for
13800: unsigned (and positive) types is 0. The lower bound for signed types on
13801: two's complement and one's complement machines machines can be computed
13802: by adding 1 to the upper bound.
13803: 
13804: @item read-only data space regions:
13805: @cindex read-only data space regions
13806: @cindex data-space, read-only regions
13807: The whole Forth data space is writable.
13808: 
13809: @item size of buffer at @code{WORD}:
13810: @cindex size of buffer at @code{WORD}
13811: @cindex @code{WORD} buffer size
13812: @code{PAD HERE - .}. 104 characters on 32-bit machines. The buffer is
13813: shared with the pictured numeric output string. If overwriting
13814: @code{PAD} is acceptable, it is as large as the remaining dictionary
13815: space, although only as much can be sensibly used as fits in a counted
13816: string.
13817: 
13818: @item size of one cell in address units:
13819: @cindex cell size
13820: @code{1 cells .}.
13821: 
13822: @item size of one character in address units:
13823: @cindex char size
13824: @code{1 chars .}. 1 on all current platforms.
13825: 
13826: @item size of the keyboard terminal buffer:
13827: @cindex size of the keyboard terminal buffer
13828: @cindex terminal buffer, size
13829: Varies. You can determine the size at a specific time using @code{lp@@
13830: tib - .}. It is shared with the locals stack and TIBs of files that
13831: include the current file. You can change the amount of space for TIBs
13832: and locals stack at Gforth startup with the command line option
13833: @code{-l}.
13834: 
13835: @item size of the pictured numeric output buffer:
13836: @cindex size of the pictured numeric output buffer
13837: @cindex pictured numeric output buffer, size
13838: @code{PAD HERE - .}. 104 characters on 32-bit machines. The buffer is
13839: shared with @code{WORD}.
13840: 
13841: @item size of the scratch area returned by @code{PAD}:
13842: @cindex size of the scratch area returned by @code{PAD}
13843: @cindex @code{PAD} size
13844: The remainder of dictionary space. @code{unused pad here - - .}.
13845: 
13846: @item system case-sensitivity characteristics:
13847: @cindex case-sensitivity characteristics
13848: Dictionary searches are case-insensitive (except in
13849: @code{TABLE}s). However, as explained above under @i{character-set
13850: extensions}, the matching for non-ASCII characters is determined by the
13851: locale you are using. In the default @code{C} locale all non-ASCII
13852: characters are matched case-sensitively.
13853: 
13854: @item system prompt:
13855: @cindex system prompt
13856: @cindex prompt
13857: @code{ ok} in interpret state, @code{ compiled} in compile state.
13858: 
13859: @item division rounding:
13860: @cindex division rounding
13861: The ordinary division words @code{/ mod /mod */ */mod} perform floored
13862: division (with the default installation of Gforth).  You can check
13863: this with @code{s" floored" environment? drop .}.  If you write
13864: programs that need a specific division rounding, best use
13865: @code{fm/mod} or @code{sm/rem} for portability.
13866: 
13867: @item values of @code{STATE} when true:
13868: @cindex @code{STATE} values
13869: -1.
13870: 
13871: @item values returned after arithmetic overflow:
13872: On two's complement machines, arithmetic is performed modulo
13873: 2**bits-per-cell for single arithmetic and 4**bits-per-cell for double
13874: arithmetic (with appropriate mapping for signed types). Division by
13875: zero typically results in a @code{-55 throw} (Floating-point
13876: unidentified fault) or @code{-10 throw} (divide by zero).  Integer
13877: division overflow can result in these throws, or in @code{-11 throw};
13878: in @code{gforth-fast} division overflow and divide by zero may also
13879: result in returning bogus results without producing an exception.
13880: 
13881: @item whether the current definition can be found after @t{DOES>}:
13882: @cindex @t{DOES>}, visibility of current definition
13883: No.
13884: 
13885: @end table
13886: 
13887: @c ---------------------------------------------------------------------
13888: @node core-ambcond, core-other, core-idef, The Core Words
13889: @subsection Ambiguous conditions
13890: @c ---------------------------------------------------------------------
13891: @cindex core words, ambiguous conditions
13892: @cindex ambiguous conditions, core words
13893: 
13894: @table @i
13895: 
13896: @item a name is neither a word nor a number:
13897: @cindex name not found
13898: @cindex undefined word
13899: @code{-13 throw} (Undefined word).
13900: 
13901: @item a definition name exceeds the maximum length allowed:
13902: @cindex word name too long
13903: @code{-19 throw} (Word name too long)
13904: 
13905: @item addressing a region not inside the various data spaces of the forth system:
13906: @cindex Invalid memory address
13907: The stacks, code space and header space are accessible. Machine code space is
13908: typically readable. Accessing other addresses gives results dependent on
13909: the operating system. On decent systems: @code{-9 throw} (Invalid memory
13910: address).
13911: 
13912: @item argument type incompatible with parameter:
13913: @cindex argument type mismatch
13914: This is usually not caught. Some words perform checks, e.g., the control
13915: flow words, and issue a @code{ABORT"} or @code{-12 THROW} (Argument type
13916: mismatch).
13917: 
13918: @item attempting to obtain the execution token of a word with undefined execution semantics:
13919: @cindex Interpreting a compile-only word, for @code{'} etc.
13920: @cindex execution token of words with undefined execution semantics
13921: @code{-14 throw} (Interpreting a compile-only word). In some cases, you
13922: get an execution token for @code{compile-only-error} (which performs a
13923: @code{-14 throw} when executed).
13924: 
13925: @item dividing by zero:
13926: @cindex dividing by zero
13927: @cindex floating point unidentified fault, integer division
13928: On some platforms, this produces a @code{-10 throw} (Division by
13929: zero); on other systems, this typically results in a @code{-55 throw}
13930: (Floating-point unidentified fault).
13931: 
13932: @item insufficient data stack or return stack space:
13933: @cindex insufficient data stack or return stack space
13934: @cindex stack overflow
13935: @cindex address alignment exception, stack overflow
13936: @cindex Invalid memory address, stack overflow
13937: Depending on the operating system, the installation, and the invocation
13938: of Gforth, this is either checked by the memory management hardware, or
13939: it is not checked. If it is checked, you typically get a @code{-3 throw}
13940: (Stack overflow), @code{-5 throw} (Return stack overflow), or @code{-9
13941: throw} (Invalid memory address) (depending on the platform and how you
13942: achieved the overflow) as soon as the overflow happens. If it is not
13943: checked, overflows typically result in mysterious illegal memory
13944: accesses, producing @code{-9 throw} (Invalid memory address) or
13945: @code{-23 throw} (Address alignment exception); they might also destroy
13946: the internal data structure of @code{ALLOCATE} and friends, resulting in
13947: various errors in these words.
13948: 
13949: @item insufficient space for loop control parameters:
13950: @cindex insufficient space for loop control parameters
13951: Like other return stack overflows.
13952: 
13953: @item insufficient space in the dictionary:
13954: @cindex insufficient space in the dictionary
13955: @cindex dictionary overflow
13956: If you try to allot (either directly with @code{allot}, or indirectly
13957: with @code{,}, @code{create} etc.) more memory than available in the
13958: dictionary, you get a @code{-8 throw} (Dictionary overflow). If you try
13959: to access memory beyond the end of the dictionary, the results are
13960: similar to stack overflows.
13961: 
13962: @item interpreting a word with undefined interpretation semantics:
13963: @cindex interpreting a word with undefined interpretation semantics
13964: @cindex Interpreting a compile-only word
13965: For some words, we have defined interpretation semantics. For the
13966: others: @code{-14 throw} (Interpreting a compile-only word).
13967: 
13968: @item modifying the contents of the input buffer or a string literal:
13969: @cindex modifying the contents of the input buffer or a string literal
13970: These are located in writable memory and can be modified.
13971: 
13972: @item overflow of the pictured numeric output string:
13973: @cindex overflow of the pictured numeric output string
13974: @cindex pictured numeric output string, overflow
13975: @code{-17 throw} (Pictured numeric ouput string overflow).
13976: 
13977: @item parsed string overflow:
13978: @cindex parsed string overflow
13979: @code{PARSE} cannot overflow. @code{WORD} does not check for overflow.
13980: 
13981: @item producing a result out of range:
13982: @cindex result out of range
13983: On two's complement machines, arithmetic is performed modulo
13984: 2**bits-per-cell for single arithmetic and 4**bits-per-cell for double
13985: arithmetic (with appropriate mapping for signed types). Division by
13986: zero typically results in a @code{-10 throw} (divide by zero) or
13987: @code{-55 throw} (floating point unidentified fault). Overflow on
13988: division may result in these errors or in @code{-11 throw} (result out
13989: of range).  @code{Gforth-fast} may silently produce bogus results on
13990: division overflow or division by zero.  @code{Convert} and
13991: @code{>number} currently overflow silently.
13992: 
13993: @item reading from an empty data or return stack:
13994: @cindex stack empty
13995: @cindex stack underflow
13996: @cindex return stack underflow
13997: The data stack is checked by the outer (aka text) interpreter after
13998: every word executed. If it has underflowed, a @code{-4 throw} (Stack
13999: underflow) is performed. Apart from that, stacks may be checked or not,
14000: depending on operating system, installation, and invocation. If they are
14001: caught by a check, they typically result in @code{-4 throw} (Stack
14002: underflow), @code{-6 throw} (Return stack underflow) or @code{-9 throw}
14003: (Invalid memory address), depending on the platform and which stack
14004: underflows and by how much. Note that even if the system uses checking
14005: (through the MMU), your program may have to underflow by a significant
14006: number of stack items to trigger the reaction (the reason for this is
14007: that the MMU, and therefore the checking, works with a page-size
14008: granularity).  If there is no checking, the symptoms resulting from an
14009: underflow are similar to those from an overflow.  Unbalanced return
14010: stack errors can result in a variety of symptoms, including @code{-9 throw}
14011: (Invalid memory address) and Illegal Instruction (typically @code{-260
14012: throw}).
14013: 
14014: @item unexpected end of the input buffer, resulting in an attempt to use a zero-length string as a name:
14015: @cindex unexpected end of the input buffer
14016: @cindex zero-length string as a name
14017: @cindex Attempt to use zero-length string as a name
14018: @code{Create} and its descendants perform a @code{-16 throw} (Attempt to
14019: use zero-length string as a name). Words like @code{'} probably will not
14020: find what they search. Note that it is possible to create zero-length
14021: names with @code{nextname} (should it not?).
14022: 
14023: @item @code{>IN} greater than input buffer:
14024: @cindex @code{>IN} greater than input buffer
14025: The next invocation of a parsing word returns a string with length 0.
14026: 
14027: @item @code{RECURSE} appears after @code{DOES>}:
14028: @cindex @code{RECURSE} appears after @code{DOES>}
14029: Compiles a recursive call to the defining word, not to the defined word.
14030: 
14031: @item argument input source different than current input source for @code{RESTORE-INPUT}:
14032: @cindex argument input source different than current input source for @code{RESTORE-INPUT}
14033: @cindex argument type mismatch, @code{RESTORE-INPUT}
14034: @cindex @code{RESTORE-INPUT}, Argument type mismatch
14035: @code{-12 THROW}. Note that, once an input file is closed (e.g., because
14036: the end of the file was reached), its source-id may be
14037: reused. Therefore, restoring an input source specification referencing a
14038: closed file may lead to unpredictable results instead of a @code{-12
14039: THROW}.
14040: 
14041: In the future, Gforth may be able to restore input source specifications
14042: from other than the current input source.
14043: 
14044: @item data space containing definitions gets de-allocated:
14045: @cindex data space containing definitions gets de-allocated
14046: Deallocation with @code{allot} is not checked. This typically results in
14047: memory access faults or execution of illegal instructions.
14048: 
14049: @item data space read/write with incorrect alignment:
14050: @cindex data space read/write with incorrect alignment
14051: @cindex alignment faults
14052: @cindex address alignment exception
14053: Processor-dependent. Typically results in a @code{-23 throw} (Address
14054: alignment exception). Under Linux-Intel on a 486 or later processor with
14055: alignment turned on, incorrect alignment results in a @code{-9 throw}
14056: (Invalid memory address). There are reportedly some processors with
14057: alignment restrictions that do not report violations.
14058: 
14059: @item data space pointer not properly aligned, @code{,}, @code{C,}:
14060: @cindex data space pointer not properly aligned, @code{,}, @code{C,}
14061: Like other alignment errors.
14062: 
14063: @item less than u+2 stack items (@code{PICK} and @code{ROLL}):
14064: Like other stack underflows.
14065: 
14066: @item loop control parameters not available:
14067: @cindex loop control parameters not available
14068: Not checked. The counted loop words simply assume that the top of return
14069: stack items are loop control parameters and behave accordingly.
14070: 
14071: @item most recent definition does not have a name (@code{IMMEDIATE}):
14072: @cindex most recent definition does not have a name (@code{IMMEDIATE})
14073: @cindex last word was headerless
14074: @code{abort" last word was headerless"}.
14075: 
14076: @item name not defined by @code{VALUE} used by @code{TO}:
14077: @cindex name not defined by @code{VALUE} used by @code{TO}
14078: @cindex @code{TO} on non-@code{VALUE}s
14079: @cindex Invalid name argument, @code{TO}
14080: @code{-32 throw} (Invalid name argument) (unless name is a local or was
14081: defined by @code{CONSTANT}; in the latter case it just changes the constant).
14082: 
14083: @item name not found (@code{'}, @code{POSTPONE}, @code{[']}, @code{[COMPILE]}):
14084: @cindex name not found (@code{'}, @code{POSTPONE}, @code{[']}, @code{[COMPILE]})
14085: @cindex undefined word, @code{'}, @code{POSTPONE}, @code{[']}, @code{[COMPILE]}
14086: @code{-13 throw} (Undefined word)
14087: 
14088: @item parameters are not of the same type (@code{DO}, @code{?DO}, @code{WITHIN}):
14089: @cindex parameters are not of the same type (@code{DO}, @code{?DO}, @code{WITHIN})
14090: Gforth behaves as if they were of the same type. I.e., you can predict
14091: the behaviour by interpreting all parameters as, e.g., signed.
14092: 
14093: @item @code{POSTPONE} or @code{[COMPILE]} applied to @code{TO}:
14094: @cindex @code{POSTPONE} or @code{[COMPILE]} applied to @code{TO}
14095: Assume @code{: X POSTPONE TO ; IMMEDIATE}. @code{X} performs the
14096: compilation semantics of @code{TO}.
14097: 
14098: @item String longer than a counted string returned by @code{WORD}:
14099: @cindex string longer than a counted string returned by @code{WORD}
14100: @cindex @code{WORD}, string overflow
14101: Not checked. The string will be ok, but the count will, of course,
14102: contain only the least significant bits of the length.
14103: 
14104: @item u greater than or equal to the number of bits in a cell (@code{LSHIFT}, @code{RSHIFT}):
14105: @cindex @code{LSHIFT}, large shift counts
14106: @cindex @code{RSHIFT}, large shift counts
14107: Processor-dependent. Typical behaviours are returning 0 and using only
14108: the low bits of the shift count.
14109: 
14110: @item word not defined via @code{CREATE}:
14111: @cindex @code{>BODY} of non-@code{CREATE}d words
14112: @code{>BODY} produces the PFA of the word no matter how it was defined.
14113: 
14114: @cindex @code{DOES>} of non-@code{CREATE}d words
14115: @code{DOES>} changes the execution semantics of the last defined word no
14116: matter how it was defined. E.g., @code{CONSTANT DOES>} is equivalent to
14117: @code{CREATE , DOES>}.
14118: 
14119: @item words improperly used outside @code{<#} and @code{#>}:
14120: Not checked. As usual, you can expect memory faults.
14121: 
14122: @end table
14123: 
14124: 
14125: @c ---------------------------------------------------------------------
14126: @node core-other,  , core-ambcond, The Core Words
14127: @subsection Other system documentation
14128: @c ---------------------------------------------------------------------
14129: @cindex other system documentation, core words
14130: @cindex core words, other system documentation
14131: 
14132: @table @i
14133: @item nonstandard words using @code{PAD}:
14134: @cindex @code{PAD} use by nonstandard words
14135: None.
14136: 
14137: @item operator's terminal facilities available:
14138: @cindex operator's terminal facilities available
14139: After processing the OS's command line, Gforth goes into interactive mode,
14140: and you can give commands to Gforth interactively. The actual facilities
14141: available depend on how you invoke Gforth.
14142: 
14143: @item program data space available:
14144: @cindex program data space available
14145: @cindex data space available
14146: @code{UNUSED .} gives the remaining dictionary space. The total
14147: dictionary space can be specified with the @code{-m} switch
14148: (@pxref{Invoking Gforth}) when Gforth starts up.
14149: 
14150: @item return stack space available:
14151: @cindex return stack space available
14152: You can compute the total return stack space in cells with
14153: @code{s" RETURN-STACK-CELLS" environment? drop .}. You can specify it at
14154: startup time with the @code{-r} switch (@pxref{Invoking Gforth}).
14155: 
14156: @item stack space available:
14157: @cindex stack space available
14158: You can compute the total data stack space in cells with
14159: @code{s" STACK-CELLS" environment? drop .}. You can specify it at
14160: startup time with the @code{-d} switch (@pxref{Invoking Gforth}).
14161: 
14162: @item system dictionary space required, in address units:
14163: @cindex system dictionary space required, in address units
14164: Type @code{here forthstart - .} after startup. At the time of this
14165: writing, this gives 80080 (bytes) on a 32-bit system.
14166: @end table
14167: 
14168: 
14169: @c =====================================================================
14170: @node The optional Block word set, The optional Double Number word set, The Core Words, ANS conformance
14171: @section The optional Block word set
14172: @c =====================================================================
14173: @cindex system documentation, block words
14174: @cindex block words, system documentation
14175: 
14176: @menu
14177: * block-idef::                  Implementation Defined Options
14178: * block-ambcond::               Ambiguous Conditions               
14179: * block-other::                 Other System Documentation                 
14180: @end menu
14181: 
14182: 
14183: @c ---------------------------------------------------------------------
14184: @node block-idef, block-ambcond, The optional Block word set, The optional Block word set
14185: @subsection Implementation Defined Options
14186: @c ---------------------------------------------------------------------
14187: @cindex implementation-defined options, block words
14188: @cindex block words, implementation-defined options
14189: 
14190: @table @i
14191: @item the format for display by @code{LIST}:
14192: @cindex @code{LIST} display format
14193: First the screen number is displayed, then 16 lines of 64 characters,
14194: each line preceded by the line number.
14195: 
14196: @item the length of a line affected by @code{\}:
14197: @cindex length of a line affected by @code{\}
14198: @cindex @code{\}, line length in blocks
14199: 64 characters.
14200: @end table
14201: 
14202: 
14203: @c ---------------------------------------------------------------------
14204: @node block-ambcond, block-other, block-idef, The optional Block word set
14205: @subsection Ambiguous conditions
14206: @c ---------------------------------------------------------------------
14207: @cindex block words, ambiguous conditions
14208: @cindex ambiguous conditions, block words
14209: 
14210: @table @i
14211: @item correct block read was not possible:
14212: @cindex block read not possible
14213: Typically results in a @code{throw} of some OS-derived value (between
14214: -512 and -2048). If the blocks file was just not long enough, blanks are
14215: supplied for the missing portion.
14216: 
14217: @item I/O exception in block transfer:
14218: @cindex I/O exception in block transfer
14219: @cindex block transfer, I/O exception
14220: Typically results in a @code{throw} of some OS-derived value (between
14221: -512 and -2048).
14222: 
14223: @item invalid block number:
14224: @cindex invalid block number
14225: @cindex block number invalid
14226: @code{-35 throw} (Invalid block number)
14227: 
14228: @item a program directly alters the contents of @code{BLK}:
14229: @cindex @code{BLK}, altering @code{BLK}
14230: The input stream is switched to that other block, at the same
14231: position. If the storing to @code{BLK} happens when interpreting
14232: non-block input, the system will get quite confused when the block ends.
14233: 
14234: @item no current block buffer for @code{UPDATE}:
14235: @cindex @code{UPDATE}, no current block buffer
14236: @code{UPDATE} has no effect.
14237: 
14238: @end table
14239: 
14240: @c ---------------------------------------------------------------------
14241: @node block-other,  , block-ambcond, The optional Block word set
14242: @subsection Other system documentation
14243: @c ---------------------------------------------------------------------
14244: @cindex other system documentation, block words
14245: @cindex block words, other system documentation
14246: 
14247: @table @i
14248: @item any restrictions a multiprogramming system places on the use of buffer addresses:
14249: No restrictions (yet).
14250: 
14251: @item the number of blocks available for source and data:
14252: depends on your disk space.
14253: 
14254: @end table
14255: 
14256: 
14257: @c =====================================================================
14258: @node The optional Double Number word set, The optional Exception word set, The optional Block word set, ANS conformance
14259: @section The optional Double Number word set
14260: @c =====================================================================
14261: @cindex system documentation, double words
14262: @cindex double words, system documentation
14263: 
14264: @menu
14265: * double-ambcond::              Ambiguous Conditions              
14266: @end menu
14267: 
14268: 
14269: @c ---------------------------------------------------------------------
14270: @node double-ambcond,  , The optional Double Number word set, The optional Double Number word set
14271: @subsection Ambiguous conditions
14272: @c ---------------------------------------------------------------------
14273: @cindex double words, ambiguous conditions
14274: @cindex ambiguous conditions, double words
14275: 
14276: @table @i
14277: @item @i{d} outside of range of @i{n} in @code{D>S}:
14278: @cindex @code{D>S}, @i{d} out of range of @i{n} 
14279: The least significant cell of @i{d} is produced.
14280: 
14281: @end table
14282: 
14283: 
14284: @c =====================================================================
14285: @node The optional Exception word set, The optional Facility word set, The optional Double Number word set, ANS conformance
14286: @section The optional Exception word set
14287: @c =====================================================================
14288: @cindex system documentation, exception words
14289: @cindex exception words, system documentation
14290: 
14291: @menu
14292: * exception-idef::              Implementation Defined Options              
14293: @end menu
14294: 
14295: 
14296: @c ---------------------------------------------------------------------
14297: @node exception-idef,  , The optional Exception word set, The optional Exception word set
14298: @subsection Implementation Defined Options
14299: @c ---------------------------------------------------------------------
14300: @cindex implementation-defined options, exception words
14301: @cindex exception words, implementation-defined options
14302: 
14303: @table @i
14304: @item @code{THROW}-codes used in the system:
14305: @cindex @code{THROW}-codes used in the system
14306: The codes -256@minus{}-511 are used for reporting signals. The mapping
14307: from OS signal numbers to throw codes is -256@minus{}@i{signal}. The
14308: codes -512@minus{}-2047 are used for OS errors (for file and memory
14309: allocation operations). The mapping from OS error numbers to throw codes
14310: is -512@minus{}@code{errno}. One side effect of this mapping is that
14311: undefined OS errors produce a message with a strange number; e.g.,
14312: @code{-1000 THROW} results in @code{Unknown error 488} on my system.
14313: @end table
14314: 
14315: @c =====================================================================
14316: @node The optional Facility word set, The optional File-Access word set, The optional Exception word set, ANS conformance
14317: @section The optional Facility word set
14318: @c =====================================================================
14319: @cindex system documentation, facility words
14320: @cindex facility words, system documentation
14321: 
14322: @menu
14323: * facility-idef::               Implementation Defined Options               
14324: * facility-ambcond::            Ambiguous Conditions            
14325: @end menu
14326: 
14327: 
14328: @c ---------------------------------------------------------------------
14329: @node facility-idef, facility-ambcond, The optional Facility word set, The optional Facility word set
14330: @subsection Implementation Defined Options
14331: @c ---------------------------------------------------------------------
14332: @cindex implementation-defined options, facility words
14333: @cindex facility words, implementation-defined options
14334: 
14335: @table @i
14336: @item encoding of keyboard events (@code{EKEY}):
14337: @cindex keyboard events, encoding in @code{EKEY}
14338: @cindex @code{EKEY}, encoding of keyboard events
14339: Keys corresponding to ASCII characters are encoded as ASCII characters.
14340: Other keys are encoded with the constants @code{k-left}, @code{k-right},
14341: @code{k-up}, @code{k-down}, @code{k-home}, @code{k-end}, @code{k1},
14342: @code{k2}, @code{k3}, @code{k4}, @code{k5}, @code{k6}, @code{k7},
14343: @code{k8}, @code{k9}, @code{k10}, @code{k11}, @code{k12}.
14344: 
14345: 
14346: @item duration of a system clock tick:
14347: @cindex duration of a system clock tick
14348: @cindex clock tick duration
14349: System dependent. With respect to @code{MS}, the time is specified in
14350: microseconds. How well the OS and the hardware implement this, is
14351: another question.
14352: 
14353: @item repeatability to be expected from the execution of @code{MS}:
14354: @cindex repeatability to be expected from the execution of @code{MS}
14355: @cindex @code{MS}, repeatability to be expected
14356: System dependent. On Unix, a lot depends on load. If the system is
14357: lightly loaded, and the delay is short enough that Gforth does not get
14358: swapped out, the performance should be acceptable. Under MS-DOS and
14359: other single-tasking systems, it should be good.
14360: 
14361: @end table
14362: 
14363: 
14364: @c ---------------------------------------------------------------------
14365: @node facility-ambcond,  , facility-idef, The optional Facility word set
14366: @subsection Ambiguous conditions
14367: @c ---------------------------------------------------------------------
14368: @cindex facility words, ambiguous conditions
14369: @cindex ambiguous conditions, facility words
14370: 
14371: @table @i
14372: @item @code{AT-XY} can't be performed on user output device:
14373: @cindex @code{AT-XY} can't be performed on user output device
14374: Largely terminal dependent. No range checks are done on the arguments.
14375: No errors are reported. You may see some garbage appearing, you may see
14376: simply nothing happen.
14377: 
14378: @end table
14379: 
14380: 
14381: @c =====================================================================
14382: @node The optional File-Access word set, The optional Floating-Point word set, The optional Facility word set, ANS conformance
14383: @section The optional File-Access word set
14384: @c =====================================================================
14385: @cindex system documentation, file words
14386: @cindex file words, system documentation
14387: 
14388: @menu
14389: * file-idef::                   Implementation Defined Options
14390: * file-ambcond::                Ambiguous Conditions                
14391: @end menu
14392: 
14393: @c ---------------------------------------------------------------------
14394: @node file-idef, file-ambcond, The optional File-Access word set, The optional File-Access word set
14395: @subsection Implementation Defined Options
14396: @c ---------------------------------------------------------------------
14397: @cindex implementation-defined options, file words
14398: @cindex file words, implementation-defined options
14399: 
14400: @table @i
14401: @item file access methods used:
14402: @cindex file access methods used
14403: @code{R/O}, @code{R/W} and @code{BIN} work as you would
14404: expect. @code{W/O} translates into the C file opening mode @code{w} (or
14405: @code{wb}): The file is cleared, if it exists, and created, if it does
14406: not (with both @code{open-file} and @code{create-file}).  Under Unix
14407: @code{create-file} creates a file with 666 permissions modified by your
14408: umask.
14409: 
14410: @item file exceptions:
14411: @cindex file exceptions
14412: The file words do not raise exceptions (except, perhaps, memory access
14413: faults when you pass illegal addresses or file-ids).
14414: 
14415: @item file line terminator:
14416: @cindex file line terminator
14417: System-dependent. Gforth uses C's newline character as line
14418: terminator. What the actual character code(s) of this are is
14419: system-dependent.
14420: 
14421: @item file name format:
14422: @cindex file name format
14423: System dependent. Gforth just uses the file name format of your OS.
14424: 
14425: @item information returned by @code{FILE-STATUS}:
14426: @cindex @code{FILE-STATUS}, returned information
14427: @code{FILE-STATUS} returns the most powerful file access mode allowed
14428: for the file: Either @code{R/O}, @code{W/O} or @code{R/W}. If the file
14429: cannot be accessed, @code{R/O BIN} is returned. @code{BIN} is applicable
14430: along with the returned mode.
14431: 
14432: @item input file state after an exception when including source:
14433: @cindex exception when including source
14434: All files that are left via the exception are closed.
14435: 
14436: @item @i{ior} values and meaning:
14437: @cindex @i{ior} values and meaning
14438: @cindex @i{wior} values and meaning
14439: The @i{ior}s returned by the file and memory allocation words are
14440: intended as throw codes. They typically are in the range
14441: -512@minus{}-2047 of OS errors.  The mapping from OS error numbers to
14442: @i{ior}s is -512@minus{}@i{errno}.
14443: 
14444: @item maximum depth of file input nesting:
14445: @cindex maximum depth of file input nesting
14446: @cindex file input nesting, maximum depth
14447: limited by the amount of return stack, locals/TIB stack, and the number
14448: of open files available. This should not give you troubles.
14449: 
14450: @item maximum size of input line:
14451: @cindex maximum size of input line
14452: @cindex input line size, maximum
14453: @code{/line}. Currently 255.
14454: 
14455: @item methods of mapping block ranges to files:
14456: @cindex mapping block ranges to files
14457: @cindex files containing blocks
14458: @cindex blocks in files
14459: By default, blocks are accessed in the file @file{blocks.fb} in the
14460: current working directory. The file can be switched with @code{USE}.
14461: 
14462: @item number of string buffers provided by @code{S"}:
14463: @cindex @code{S"}, number of string buffers
14464: 1
14465: 
14466: @item size of string buffer used by @code{S"}:
14467: @cindex @code{S"}, size of string buffer
14468: @code{/line}. currently 255.
14469: 
14470: @end table
14471: 
14472: @c ---------------------------------------------------------------------
14473: @node file-ambcond,  , file-idef, The optional File-Access word set
14474: @subsection Ambiguous conditions
14475: @c ---------------------------------------------------------------------
14476: @cindex file words, ambiguous conditions
14477: @cindex ambiguous conditions, file words
14478: 
14479: @table @i
14480: @item attempting to position a file outside its boundaries:
14481: @cindex @code{REPOSITION-FILE}, outside the file's boundaries
14482: @code{REPOSITION-FILE} is performed as usual: Afterwards,
14483: @code{FILE-POSITION} returns the value given to @code{REPOSITION-FILE}.
14484: 
14485: @item attempting to read from file positions not yet written:
14486: @cindex reading from file positions not yet written
14487: End-of-file, i.e., zero characters are read and no error is reported.
14488: 
14489: @item @i{file-id} is invalid (@code{INCLUDE-FILE}):
14490: @cindex @code{INCLUDE-FILE}, @i{file-id} is invalid 
14491: An appropriate exception may be thrown, but a memory fault or other
14492: problem is more probable.
14493: 
14494: @item I/O exception reading or closing @i{file-id} (@code{INCLUDE-FILE}, @code{INCLUDED}):
14495: @cindex @code{INCLUDE-FILE}, I/O exception reading or closing @i{file-id}
14496: @cindex @code{INCLUDED}, I/O exception reading or closing @i{file-id}
14497: The @i{ior} produced by the operation, that discovered the problem, is
14498: thrown.
14499: 
14500: @item named file cannot be opened (@code{INCLUDED}):
14501: @cindex @code{INCLUDED}, named file cannot be opened
14502: The @i{ior} produced by @code{open-file} is thrown.
14503: 
14504: @item requesting an unmapped block number:
14505: @cindex unmapped block numbers
14506: There are no unmapped legal block numbers. On some operating systems,
14507: writing a block with a large number may overflow the file system and
14508: have an error message as consequence.
14509: 
14510: @item using @code{source-id} when @code{blk} is non-zero:
14511: @cindex @code{SOURCE-ID}, behaviour when @code{BLK} is non-zero
14512: @code{source-id} performs its function. Typically it will give the id of
14513: the source which loaded the block. (Better ideas?)
14514: 
14515: @end table
14516: 
14517: 
14518: @c =====================================================================
14519: @node  The optional Floating-Point word set, The optional Locals word set, The optional File-Access word set, ANS conformance
14520: @section The optional Floating-Point word set
14521: @c =====================================================================
14522: @cindex system documentation, floating-point words
14523: @cindex floating-point words, system documentation
14524: 
14525: @menu
14526: * floating-idef::               Implementation Defined Options
14527: * floating-ambcond::            Ambiguous Conditions            
14528: @end menu
14529: 
14530: 
14531: @c ---------------------------------------------------------------------
14532: @node floating-idef, floating-ambcond, The optional Floating-Point word set, The optional Floating-Point word set
14533: @subsection Implementation Defined Options
14534: @c ---------------------------------------------------------------------
14535: @cindex implementation-defined options, floating-point words
14536: @cindex floating-point words, implementation-defined options
14537: 
14538: @table @i
14539: @item format and range of floating point numbers:
14540: @cindex format and range of floating point numbers
14541: @cindex floating point numbers, format and range
14542: System-dependent; the @code{double} type of C.
14543: 
14544: @item results of @code{REPRESENT} when @i{float} is out of range:
14545: @cindex  @code{REPRESENT}, results when @i{float} is out of range
14546: System dependent; @code{REPRESENT} is implemented using the C library
14547: function @code{ecvt()} and inherits its behaviour in this respect.
14548: 
14549: @item rounding or truncation of floating-point numbers:
14550: @cindex rounding of floating-point numbers
14551: @cindex truncation of floating-point numbers
14552: @cindex floating-point numbers, rounding or truncation
14553: System dependent; the rounding behaviour is inherited from the hosting C
14554: compiler. IEEE-FP-based (i.e., most) systems by default round to
14555: nearest, and break ties by rounding to even (i.e., such that the last
14556: bit of the mantissa is 0).
14557: 
14558: @item size of floating-point stack:
14559: @cindex floating-point stack size
14560: @code{s" FLOATING-STACK" environment? drop .} gives the total size of
14561: the floating-point stack (in floats). You can specify this on startup
14562: with the command-line option @code{-f} (@pxref{Invoking Gforth}).
14563: 
14564: @item width of floating-point stack:
14565: @cindex floating-point stack width 
14566: @code{1 floats}.
14567: 
14568: @end table
14569: 
14570: 
14571: @c ---------------------------------------------------------------------
14572: @node floating-ambcond,  , floating-idef, The optional Floating-Point word set
14573: @subsection Ambiguous conditions
14574: @c ---------------------------------------------------------------------
14575: @cindex floating-point words, ambiguous conditions
14576: @cindex ambiguous conditions, floating-point words
14577: 
14578: @table @i
14579: @item @code{df@@} or @code{df!} used with an address that is not double-float  aligned:
14580: @cindex @code{df@@} or @code{df!} used with an address that is not double-float  aligned
14581: System-dependent. Typically results in a @code{-23 THROW} like other
14582: alignment violations.
14583: 
14584: @item @code{f@@} or @code{f!} used with an address that is not float  aligned:
14585: @cindex @code{f@@} used with an address that is not float aligned
14586: @cindex @code{f!} used with an address that is not float aligned
14587: System-dependent. Typically results in a @code{-23 THROW} like other
14588: alignment violations.
14589: 
14590: @item floating-point result out of range:
14591: @cindex floating-point result out of range
14592: System-dependent. Can result in a @code{-43 throw} (floating point
14593: overflow), @code{-54 throw} (floating point underflow), @code{-41 throw}
14594: (floating point inexact result), @code{-55 THROW} (Floating-point
14595: unidentified fault), or can produce a special value representing, e.g.,
14596: Infinity.
14597: 
14598: @item @code{sf@@} or @code{sf!} used with an address that is not single-float  aligned:
14599: @cindex @code{sf@@} or @code{sf!} used with an address that is not single-float  aligned
14600: System-dependent. Typically results in an alignment fault like other
14601: alignment violations.
14602: 
14603: @item @code{base} is not decimal (@code{REPRESENT}, @code{F.}, @code{FE.}, @code{FS.}):
14604: @cindex @code{base} is not decimal (@code{REPRESENT}, @code{F.}, @code{FE.}, @code{FS.})
14605: The floating-point number is converted into decimal nonetheless.
14606: 
14607: @item Both arguments are equal to zero (@code{FATAN2}):
14608: @cindex @code{FATAN2}, both arguments are equal to zero
14609: System-dependent. @code{FATAN2} is implemented using the C library
14610: function @code{atan2()}.
14611: 
14612: @item Using @code{FTAN} on an argument @i{r1} where cos(@i{r1}) is zero:
14613: @cindex @code{FTAN} on an argument @i{r1} where cos(@i{r1}) is zero
14614: System-dependent. Anyway, typically the cos of @i{r1} will not be zero
14615: because of small errors and the tan will be a very large (or very small)
14616: but finite number.
14617: 
14618: @item @i{d} cannot be presented precisely as a float in @code{D>F}:
14619: @cindex @code{D>F}, @i{d} cannot be presented precisely as a float
14620: The result is rounded to the nearest float.
14621: 
14622: @item dividing by zero:
14623: @cindex dividing by zero, floating-point
14624: @cindex floating-point dividing by zero
14625: @cindex floating-point unidentified fault, FP divide-by-zero
14626: Platform-dependent; can produce an Infinity, NaN, @code{-42 throw}
14627: (floating point divide by zero) or @code{-55 throw} (Floating-point
14628: unidentified fault).
14629: 
14630: @item exponent too big for conversion (@code{DF!}, @code{DF@@}, @code{SF!}, @code{SF@@}):
14631: @cindex exponent too big for conversion (@code{DF!}, @code{DF@@}, @code{SF!}, @code{SF@@})
14632: System dependent. On IEEE-FP based systems the number is converted into
14633: an infinity.
14634: 
14635: @item @i{float}<1 (@code{FACOSH}):
14636: @cindex @code{FACOSH}, @i{float}<1
14637: @cindex floating-point unidentified fault, @code{FACOSH}
14638: Platform-dependent; on IEEE-FP systems typically produces a NaN.
14639: 
14640: @item @i{float}=<-1 (@code{FLNP1}):
14641: @cindex @code{FLNP1}, @i{float}=<-1
14642: @cindex floating-point unidentified fault, @code{FLNP1}
14643: Platform-dependent; on IEEE-FP systems typically produces a NaN (or a
14644: negative infinity for @i{float}=-1).
14645: 
14646: @item @i{float}=<0 (@code{FLN}, @code{FLOG}):
14647: @cindex @code{FLN}, @i{float}=<0
14648: @cindex @code{FLOG}, @i{float}=<0
14649: @cindex floating-point unidentified fault, @code{FLN} or @code{FLOG}
14650: Platform-dependent; on IEEE-FP systems typically produces a NaN (or a
14651: negative infinity for @i{float}=0).
14652: 
14653: @item @i{float}<0 (@code{FASINH}, @code{FSQRT}):
14654: @cindex @code{FASINH}, @i{float}<0
14655: @cindex @code{FSQRT}, @i{float}<0
14656: @cindex floating-point unidentified fault, @code{FASINH} or @code{FSQRT}
14657: Platform-dependent; for @code{fsqrt} this typically gives a NaN, for
14658: @code{fasinh} some platforms produce a NaN, others a number (bug in the
14659: C library?).
14660: 
14661: @item |@i{float}|>1 (@code{FACOS}, @code{FASIN}, @code{FATANH}):
14662: @cindex @code{FACOS}, |@i{float}|>1
14663: @cindex @code{FASIN}, |@i{float}|>1
14664: @cindex @code{FATANH}, |@i{float}|>1
14665: @cindex floating-point unidentified fault, @code{FACOS}, @code{FASIN} or @code{FATANH}
14666: Platform-dependent; IEEE-FP systems typically produce a NaN.
14667: 
14668: @item integer part of float cannot be represented by @i{d} in @code{F>D}:
14669: @cindex @code{F>D}, integer part of float cannot be represented by @i{d}
14670: @cindex floating-point unidentified fault, @code{F>D}
14671: Platform-dependent; typically, some double number is produced and no
14672: error is reported.
14673: 
14674: @item string larger than pictured numeric output area (@code{f.}, @code{fe.}, @code{fs.}):
14675: @cindex string larger than pictured numeric output area (@code{f.}, @code{fe.}, @code{fs.})
14676: @code{Precision} characters of the numeric output area are used.  If
14677: @code{precision} is too high, these words will smash the data or code
14678: close to @code{here}.
14679: @end table
14680: 
14681: @c =====================================================================
14682: @node  The optional Locals word set, The optional Memory-Allocation word set, The optional Floating-Point word set, ANS conformance
14683: @section The optional Locals word set
14684: @c =====================================================================
14685: @cindex system documentation, locals words
14686: @cindex locals words, system documentation
14687: 
14688: @menu
14689: * locals-idef::                 Implementation Defined Options                 
14690: * locals-ambcond::              Ambiguous Conditions              
14691: @end menu
14692: 
14693: 
14694: @c ---------------------------------------------------------------------
14695: @node locals-idef, locals-ambcond, The optional Locals word set, The optional Locals word set
14696: @subsection Implementation Defined Options
14697: @c ---------------------------------------------------------------------
14698: @cindex implementation-defined options, locals words
14699: @cindex locals words, implementation-defined options
14700: 
14701: @table @i
14702: @item maximum number of locals in a definition:
14703: @cindex maximum number of locals in a definition
14704: @cindex locals, maximum number in a definition
14705: @code{s" #locals" environment? drop .}. Currently 15. This is a lower
14706: bound, e.g., on a 32-bit machine there can be 41 locals of up to 8
14707: characters. The number of locals in a definition is bounded by the size
14708: of locals-buffer, which contains the names of the locals.
14709: 
14710: @end table
14711: 
14712: 
14713: @c ---------------------------------------------------------------------
14714: @node locals-ambcond,  , locals-idef, The optional Locals word set
14715: @subsection Ambiguous conditions
14716: @c ---------------------------------------------------------------------
14717: @cindex locals words, ambiguous conditions
14718: @cindex ambiguous conditions, locals words
14719: 
14720: @table @i
14721: @item executing a named local in interpretation state:
14722: @cindex local in interpretation state
14723: @cindex Interpreting a compile-only word, for a local
14724: Locals have no interpretation semantics. If you try to perform the
14725: interpretation semantics, you will get a @code{-14 throw} somewhere
14726: (Interpreting a compile-only word). If you perform the compilation
14727: semantics, the locals access will be compiled (irrespective of state).
14728: 
14729: @item @i{name} not defined by @code{VALUE} or @code{(LOCAL)} (@code{TO}):
14730: @cindex name not defined by @code{VALUE} or @code{(LOCAL)} used by @code{TO}
14731: @cindex @code{TO} on non-@code{VALUE}s and non-locals
14732: @cindex Invalid name argument, @code{TO}
14733: @code{-32 throw} (Invalid name argument)
14734: 
14735: @end table
14736: 
14737: 
14738: @c =====================================================================
14739: @node  The optional Memory-Allocation word set, The optional Programming-Tools word set, The optional Locals word set, ANS conformance
14740: @section The optional Memory-Allocation word set
14741: @c =====================================================================
14742: @cindex system documentation, memory-allocation words
14743: @cindex memory-allocation words, system documentation
14744: 
14745: @menu
14746: * memory-idef::                 Implementation Defined Options                 
14747: @end menu
14748: 
14749: 
14750: @c ---------------------------------------------------------------------
14751: @node memory-idef,  , The optional Memory-Allocation word set, The optional Memory-Allocation word set
14752: @subsection Implementation Defined Options
14753: @c ---------------------------------------------------------------------
14754: @cindex implementation-defined options, memory-allocation words
14755: @cindex memory-allocation words, implementation-defined options
14756: 
14757: @table @i
14758: @item values and meaning of @i{ior}:
14759: @cindex  @i{ior} values and meaning
14760: The @i{ior}s returned by the file and memory allocation words are
14761: intended as throw codes. They typically are in the range
14762: -512@minus{}-2047 of OS errors.  The mapping from OS error numbers to
14763: @i{ior}s is -512@minus{}@i{errno}.
14764: 
14765: @end table
14766: 
14767: @c =====================================================================
14768: @node  The optional Programming-Tools word set, The optional Search-Order word set, The optional Memory-Allocation word set, ANS conformance
14769: @section The optional Programming-Tools word set
14770: @c =====================================================================
14771: @cindex system documentation, programming-tools words
14772: @cindex programming-tools words, system documentation
14773: 
14774: @menu
14775: * programming-idef::            Implementation Defined Options            
14776: * programming-ambcond::         Ambiguous Conditions         
14777: @end menu
14778: 
14779: 
14780: @c ---------------------------------------------------------------------
14781: @node programming-idef, programming-ambcond, The optional Programming-Tools word set, The optional Programming-Tools word set
14782: @subsection Implementation Defined Options
14783: @c ---------------------------------------------------------------------
14784: @cindex implementation-defined options, programming-tools words
14785: @cindex programming-tools words, implementation-defined options
14786: 
14787: @table @i
14788: @item ending sequence for input following @code{;CODE} and @code{CODE}:
14789: @cindex @code{;CODE} ending sequence
14790: @cindex @code{CODE} ending sequence
14791: @code{END-CODE}
14792: 
14793: @item manner of processing input following @code{;CODE} and @code{CODE}:
14794: @cindex @code{;CODE}, processing input
14795: @cindex @code{CODE}, processing input
14796: The @code{ASSEMBLER} vocabulary is pushed on the search order stack, and
14797: the input is processed by the text interpreter, (starting) in interpret
14798: state.
14799: 
14800: @item search order capability for @code{EDITOR} and @code{ASSEMBLER}:
14801: @cindex @code{ASSEMBLER}, search order capability
14802: The ANS Forth search order word set.
14803: 
14804: @item source and format of display by @code{SEE}:
14805: @cindex @code{SEE}, source and format of output
14806: The source for @code{see} is the executable code used by the inner
14807: interpreter.  The current @code{see} tries to output Forth source code
14808: (and on some platforms, assembly code for primitives) as well as
14809: possible.
14810: 
14811: @end table
14812: 
14813: @c ---------------------------------------------------------------------
14814: @node programming-ambcond,  , programming-idef, The optional Programming-Tools word set
14815: @subsection Ambiguous conditions
14816: @c ---------------------------------------------------------------------
14817: @cindex programming-tools words, ambiguous conditions
14818: @cindex ambiguous conditions, programming-tools words
14819: 
14820: @table @i
14821: 
14822: @item deleting the compilation word list (@code{FORGET}):
14823: @cindex @code{FORGET}, deleting the compilation word list
14824: Not implemented (yet).
14825: 
14826: @item fewer than @i{u}+1 items on the control-flow stack (@code{CS-PICK}, @code{CS-ROLL}):
14827: @cindex @code{CS-PICK}, fewer than @i{u}+1 items on the control flow-stack
14828: @cindex @code{CS-ROLL}, fewer than @i{u}+1 items on the control flow-stack
14829: @cindex control-flow stack underflow
14830: This typically results in an @code{abort"} with a descriptive error
14831: message (may change into a @code{-22 throw} (Control structure mismatch)
14832: in the future). You may also get a memory access error. If you are
14833: unlucky, this ambiguous condition is not caught.
14834: 
14835: @item @i{name} can't be found (@code{FORGET}):
14836: @cindex @code{FORGET}, @i{name} can't be found
14837: Not implemented (yet).
14838: 
14839: @item @i{name} not defined via @code{CREATE}:
14840: @cindex @code{;CODE}, @i{name} not defined via @code{CREATE}
14841: @code{;CODE} behaves like @code{DOES>} in this respect, i.e., it changes
14842: the execution semantics of the last defined word no matter how it was
14843: defined.
14844: 
14845: @item @code{POSTPONE} applied to @code{[IF]}:
14846: @cindex @code{POSTPONE} applied to @code{[IF]}
14847: @cindex @code{[IF]} and @code{POSTPONE}
14848: After defining @code{: X POSTPONE [IF] ; IMMEDIATE}. @code{X} is
14849: equivalent to @code{[IF]}.
14850: 
14851: @item reaching the end of the input source before matching @code{[ELSE]} or @code{[THEN]}:
14852: @cindex @code{[IF]}, end of the input source before matching @code{[ELSE]} or @code{[THEN]}
14853: Continue in the same state of conditional compilation in the next outer
14854: input source. Currently there is no warning to the user about this.
14855: 
14856: @item removing a needed definition (@code{FORGET}):
14857: @cindex @code{FORGET}, removing a needed definition
14858: Not implemented (yet).
14859: 
14860: @end table
14861: 
14862: 
14863: @c =====================================================================
14864: @node  The optional Search-Order word set,  , The optional Programming-Tools word set, ANS conformance
14865: @section The optional Search-Order word set
14866: @c =====================================================================
14867: @cindex system documentation, search-order words
14868: @cindex search-order words, system documentation
14869: 
14870: @menu
14871: * search-idef::                 Implementation Defined Options                 
14872: * search-ambcond::              Ambiguous Conditions              
14873: @end menu
14874: 
14875: 
14876: @c ---------------------------------------------------------------------
14877: @node search-idef, search-ambcond, The optional Search-Order word set, The optional Search-Order word set
14878: @subsection Implementation Defined Options
14879: @c ---------------------------------------------------------------------
14880: @cindex implementation-defined options, search-order words
14881: @cindex search-order words, implementation-defined options
14882: 
14883: @table @i
14884: @item maximum number of word lists in search order:
14885: @cindex maximum number of word lists in search order
14886: @cindex search order, maximum depth
14887: @code{s" wordlists" environment? drop .}. Currently 16.
14888: 
14889: @item minimum search order:
14890: @cindex minimum search order
14891: @cindex search order, minimum
14892: @code{root root}.
14893: 
14894: @end table
14895: 
14896: @c ---------------------------------------------------------------------
14897: @node search-ambcond,  , search-idef, The optional Search-Order word set
14898: @subsection Ambiguous conditions
14899: @c ---------------------------------------------------------------------
14900: @cindex search-order words, ambiguous conditions
14901: @cindex ambiguous conditions, search-order words
14902: 
14903: @table @i
14904: @item changing the compilation word list (during compilation):
14905: @cindex changing the compilation word list (during compilation)
14906: @cindex compilation word list, change before definition ends
14907: The word is entered into the word list that was the compilation word list
14908: at the start of the definition. Any changes to the name field (e.g.,
14909: @code{immediate}) or the code field (e.g., when executing @code{DOES>})
14910: are applied to the latest defined word (as reported by @code{latest} or
14911: @code{latestxt}), if possible, irrespective of the compilation word list.
14912: 
14913: @item search order empty (@code{previous}):
14914: @cindex @code{previous}, search order empty
14915: @cindex vocstack empty, @code{previous}
14916: @code{abort" Vocstack empty"}.
14917: 
14918: @item too many word lists in search order (@code{also}):
14919: @cindex @code{also}, too many word lists in search order
14920: @cindex vocstack full, @code{also}
14921: @code{abort" Vocstack full"}.
14922: 
14923: @end table
14924: 
14925: @c ***************************************************************
14926: @node Standard vs Extensions, Model, ANS conformance, Top
14927: @chapter Should I use Gforth extensions?
14928: @cindex Gforth extensions
14929: 
14930: As you read through the rest of this manual, you will see documentation
14931: for @i{Standard} words, and documentation for some appealing Gforth
14932: @i{extensions}. You might ask yourself the question: @i{``Should I
14933: restrict myself to the standard, or should I use the extensions?''}
14934: 
14935: The answer depends on the goals you have for the program you are working
14936: on:
14937: 
14938: @itemize @bullet
14939: 
14940: @item Is it just for yourself or do you want to share it with others?
14941: 
14942: @item
14943: If you want to share it, do the others all use Gforth?
14944: 
14945: @item
14946: If it is just for yourself, do you want to restrict yourself to Gforth?
14947: 
14948: @end itemize
14949: 
14950: If restricting the program to Gforth is ok, then there is no reason not
14951: to use extensions.  It is still a good idea to keep to the standard
14952: where it is easy, in case you want to reuse these parts in another
14953: program that you want to be portable.
14954: 
14955: If you want to be able to port the program to other Forth systems, there
14956: are the following points to consider:
14957: 
14958: @itemize @bullet
14959: 
14960: @item
14961: Most Forth systems that are being maintained support the ANS Forth
14962: standard.  So if your program complies with the standard, it will be
14963: portable among many systems.
14964: 
14965: @item
14966: A number of the Gforth extensions can be implemented in ANS Forth using
14967: public-domain files provided in the @file{compat/} directory. These are
14968: mentioned in the text in passing.  There is no reason not to use these
14969: extensions, your program will still be ANS Forth compliant; just include
14970: the appropriate compat files with your program.
14971: 
14972: @item
14973: The tool @file{ans-report.fs} (@pxref{ANS Report}) makes it easy to
14974: analyse your program and determine what non-Standard words it relies
14975: upon.  However, it does not check whether you use standard words in a
14976: non-standard way.
14977: 
14978: @item
14979: Some techniques are not standardized by ANS Forth, and are hard or
14980: impossible to implement in a standard way, but can be implemented in
14981: most Forth systems easily, and usually in similar ways (e.g., accessing
14982: word headers).  Forth has a rich historical precedent for programmers
14983: taking advantage of implementation-dependent features of their tools
14984: (for example, relying on a knowledge of the dictionary
14985: structure). Sometimes these techniques are necessary to extract every
14986: last bit of performance from the hardware, sometimes they are just a
14987: programming shorthand.
14988: 
14989: @item
14990: Does using a Gforth extension save more work than the porting this part
14991: to other Forth systems (if any) will cost?
14992: 
14993: @item
14994: Is the additional functionality worth the reduction in portability and
14995: the additional porting problems?
14996: 
14997: @end itemize
14998: 
14999: In order to perform these considerations, you need to know what's
15000: standard and what's not.  This manual generally states if something is
15001: non-standard, but the authoritative source is the
15002: @uref{http://www.taygeta.com/forth/dpans.html,standard document}.
15003: Appendix A of the Standard (@var{Rationale}) provides a valuable insight
15004: into the thought processes of the technical committee.
15005: 
15006: Note also that portability between Forth systems is not the only
15007: portability issue; there is also the issue of portability between
15008: different platforms (processor/OS combinations).
15009: 
15010: @c ***************************************************************
15011: @node Model, Integrating Gforth, Standard vs Extensions, Top
15012: @chapter Model
15013: 
15014: This chapter has yet to be written. It will contain information, on
15015: which internal structures you can rely.
15016: 
15017: @c ***************************************************************
15018: @node Integrating Gforth, Emacs and Gforth, Model, Top
15019: @chapter Integrating Gforth into C programs
15020: 
15021: This is not yet implemented.
15022: 
15023: Several people like to use Forth as scripting language for applications
15024: that are otherwise written in C, C++, or some other language.
15025: 
15026: The Forth system ATLAST provides facilities for embedding it into
15027: applications; unfortunately it has several disadvantages: most
15028: importantly, it is not based on ANS Forth, and it is apparently dead
15029: (i.e., not developed further and not supported). The facilities
15030: provided by Gforth in this area are inspired by ATLAST's facilities, so
15031: making the switch should not be hard.
15032: 
15033: We also tried to design the interface such that it can easily be
15034: implemented by other Forth systems, so that we may one day arrive at a
15035: standardized interface. Such a standard interface would allow you to
15036: replace the Forth system without having to rewrite C code.
15037: 
15038: You embed the Gforth interpreter by linking with the library
15039: @code{libgforth.a} (give the compiler the option @code{-lgforth}).  All
15040: global symbols in this library that belong to the interface, have the
15041: prefix @code{forth_}. (Global symbols that are used internally have the
15042: prefix @code{gforth_}).
15043: 
15044: You can include the declarations of Forth types and the functions and
15045: variables of the interface with @code{#include <forth.h>}.
15046: 
15047: Types.
15048: 
15049: Variables.
15050: 
15051: Data and FP Stack pointer. Area sizes.
15052: 
15053: functions.
15054: 
15055: forth_init(imagefile)
15056: forth_evaluate(string) exceptions?
15057: forth_goto(address) (or forth_execute(xt)?)
15058: forth_continue() (a corountining mechanism)
15059: 
15060: Adding primitives.
15061: 
15062: No checking.
15063: 
15064: Signals?
15065: 
15066: Accessing the Stacks
15067: 
15068: @c ******************************************************************
15069: @node Emacs and Gforth, Image Files, Integrating Gforth, Top
15070: @chapter Emacs and Gforth
15071: @cindex Emacs and Gforth
15072: 
15073: @cindex @file{gforth.el}
15074: @cindex @file{forth.el}
15075: @cindex Rydqvist, Goran
15076: @cindex Kuehling, David
15077: @cindex comment editing commands
15078: @cindex @code{\}, editing with Emacs
15079: @cindex debug tracer editing commands
15080: @cindex @code{~~}, removal with Emacs
15081: @cindex Forth mode in Emacs
15082: 
15083: Gforth comes with @file{gforth.el}, an improved version of
15084: @file{forth.el} by Goran Rydqvist (included in the TILE package). The
15085: improvements are:
15086: 
15087: @itemize @bullet
15088: @item
15089: A better handling of indentation.
15090: @item
15091: A custom hilighting engine for Forth-code.
15092: @item
15093: Comment paragraph filling (@kbd{M-q})
15094: @item
15095: Commenting (@kbd{C-x \}) and uncommenting (@kbd{C-u C-x \}) of regions
15096: @item
15097: Removal of debugging tracers (@kbd{C-x ~}, @pxref{Debugging}).
15098: @item
15099: Support of the @code{info-lookup} feature for looking up the
15100: documentation of a word.
15101: @item
15102: Support for reading and writing blocks files.
15103: @end itemize
15104: 
15105: To get a basic description of these features, enter Forth mode and
15106: type @kbd{C-h m}.
15107: 
15108: @cindex source location of error or debugging output in Emacs
15109: @cindex error output, finding the source location in Emacs
15110: @cindex debugging output, finding the source location in Emacs
15111: In addition, Gforth supports Emacs quite well: The source code locations
15112: given in error messages, debugging output (from @code{~~}) and failed
15113: assertion messages are in the right format for Emacs' compilation mode
15114: (@pxref{Compilation, , Running Compilations under Emacs, emacs, Emacs
15115: Manual}) so the source location corresponding to an error or other
15116: message is only a few keystrokes away (@kbd{C-x `} for the next error,
15117: @kbd{C-c C-c} for the error under the cursor).
15118: 
15119: @cindex viewing the documentation of a word in Emacs
15120: @cindex context-sensitive help
15121: Moreover, for words documented in this manual, you can look up the
15122: glossary entry quickly by using @kbd{C-h TAB}
15123: (@code{info-lookup-symbol}, @pxref{Documentation, ,Documentation
15124: Commands, emacs, Emacs Manual}).  This feature requires Emacs 20.3 or
15125: later and does not work for words containing @code{:}.
15126: 
15127: @menu
15128: * Installing gforth.el::        Making Emacs aware of Forth.
15129: * Emacs Tags::                  Viewing the source of a word in Emacs.
15130: * Hilighting::                  Making Forth code look prettier.
15131: * Auto-Indentation::            Customizing auto-indentation.
15132: * Blocks Files::                Reading and writing blocks files.
15133: @end menu
15134: 
15135: @c ----------------------------------
15136: @node Installing gforth.el, Emacs Tags, Emacs and Gforth, Emacs and Gforth
15137: @section Installing gforth.el
15138: @cindex @file{.emacs}
15139: @cindex @file{gforth.el}, installation
15140: To make the features from @file{gforth.el} available in Emacs, add
15141: the following lines to your @file{.emacs} file:
15142: 
15143: @example
15144: (autoload 'forth-mode "gforth.el")
15145: (setq auto-mode-alist (cons '("\\.fs\\'" . forth-mode) 
15146: 			    auto-mode-alist))
15147: (autoload 'forth-block-mode "gforth.el")
15148: (setq auto-mode-alist (cons '("\\.fb\\'" . forth-block-mode) 
15149: 			    auto-mode-alist))
15150: (add-hook 'forth-mode-hook (function (lambda ()
15151:    ;; customize variables here:
15152:    (setq forth-indent-level 4)
15153:    (setq forth-minor-indent-level 2)
15154:    (setq forth-hilight-level 3)
15155:    ;;; ...
15156: )))
15157: @end example
15158: 
15159: @c ----------------------------------
15160: @node Emacs Tags, Hilighting, Installing gforth.el, Emacs and Gforth
15161: @section Emacs Tags
15162: @cindex @file{TAGS} file
15163: @cindex @file{etags.fs}
15164: @cindex viewing the source of a word in Emacs
15165: @cindex @code{require}, placement in files
15166: @cindex @code{include}, placement in files
15167: If you @code{require} @file{etags.fs}, a new @file{TAGS} file will be
15168: produced (@pxref{Tags, , Tags Tables, emacs, Emacs Manual}) that
15169: contains the definitions of all words defined afterwards. You can then
15170: find the source for a word using @kbd{M-.}. Note that Emacs can use
15171: several tags files at the same time (e.g., one for the Gforth sources
15172: and one for your program, @pxref{Select Tags Table,,Selecting a Tags
15173: Table,emacs, Emacs Manual}). The TAGS file for the preloaded words is
15174: @file{$(datadir)/gforth/$(VERSION)/TAGS} (e.g.,
15175: @file{/usr/local/share/gforth/0.2.0/TAGS}).  To get the best behaviour
15176: with @file{etags.fs}, you should avoid putting definitions both before
15177: and after @code{require} etc., otherwise you will see the same file
15178: visited several times by commands like @code{tags-search}.
15179: 
15180: @c ----------------------------------
15181: @node Hilighting, Auto-Indentation, Emacs Tags, Emacs and Gforth
15182: @section Hilighting
15183: @cindex hilighting Forth code in Emacs
15184: @cindex highlighting Forth code in Emacs
15185: @file{gforth.el} comes with a custom source hilighting engine.  When
15186: you open a file in @code{forth-mode}, it will be completely parsed,
15187: assigning faces to keywords, comments, strings etc.  While you edit
15188: the file, modified regions get parsed and updated on-the-fly. 
15189: 
15190: Use the variable `forth-hilight-level' to change the level of
15191: decoration from 0 (no hilighting at all) to 3 (the default).  Even if
15192: you set the hilighting level to 0, the parser will still work in the
15193: background, collecting information about whether regions of text are
15194: ``compiled'' or ``interpreted''.  Those information are required for
15195: auto-indentation to work properly.  Set `forth-disable-parser' to
15196: non-nil if your computer is too slow to handle parsing.  This will
15197: have an impact on the smartness of the auto-indentation engine,
15198: though.
15199: 
15200: Sometimes Forth sources define new features that should be hilighted,
15201: new control structures, defining-words etc.  You can use the variable
15202: `forth-custom-words' to make @code{forth-mode} hilight additional
15203: words and constructs.  See the docstring of `forth-words' for details
15204: (in Emacs, type @kbd{C-h v forth-words}).
15205: 
15206: `forth-custom-words' is meant to be customized in your
15207: @file{.emacs} file.  To customize hilighing in a file-specific manner,
15208: set `forth-local-words' in a local-variables section at the end of
15209: your source file (@pxref{Local Variables in Files,, Variables, emacs, Emacs Manual}).
15210: 
15211: Example:
15212: @example
15213: 0 [IF]
15214:    Local Variables:
15215:    forth-local-words:
15216:       ((("t:") definition-starter (font-lock-keyword-face . 1)
15217:         "[ \t\n]" t name (font-lock-function-name-face . 3))
15218:        ((";t") definition-ender (font-lock-keyword-face . 1)))
15219:    End:
15220: [THEN]
15221: @end example
15222: 
15223: @c ----------------------------------
15224: @node Auto-Indentation, Blocks Files, Hilighting, Emacs and Gforth
15225: @section Auto-Indentation
15226: @cindex auto-indentation of Forth code in Emacs
15227: @cindex indentation of Forth code in Emacs
15228: @code{forth-mode} automatically tries to indent lines in a smart way,
15229: whenever you type @key{TAB} or break a line with @kbd{C-m}.
15230: 
15231: Simple customization can be achieved by setting
15232: `forth-indent-level' and `forth-minor-indent-level' in your
15233: @file{.emacs} file. For historical reasons @file{gforth.el} indents
15234: per default by multiples of 4 columns.  To use the more traditional
15235: 3-column indentation, add the following lines to your @file{.emacs}:
15236: 
15237: @example
15238: (add-hook 'forth-mode-hook (function (lambda ()
15239:    ;; customize variables here:
15240:    (setq forth-indent-level 3)
15241:    (setq forth-minor-indent-level 1)
15242: )))
15243: @end example
15244: 
15245: If you want indentation to recognize non-default words, customize it
15246: by setting `forth-custom-indent-words' in your @file{.emacs}.  See the
15247: docstring of `forth-indent-words' for details (in Emacs, type @kbd{C-h
15248: v forth-indent-words}).
15249: 
15250: To customize indentation in a file-specific manner, set
15251: `forth-local-indent-words' in a local-variables section at the end of
15252: your source file (@pxref{Local Variables in Files, Variables,,emacs,
15253: Emacs Manual}).
15254: 
15255: Example:
15256: @example
15257: 0 [IF]
15258:    Local Variables:
15259:    forth-local-indent-words:
15260:       ((("t:") (0 . 2) (0 . 2))
15261:        ((";t") (-2 . 0) (0 . -2)))
15262:    End:
15263: [THEN]
15264: @end example
15265: 
15266: @c ----------------------------------
15267: @node Blocks Files,  , Auto-Indentation, Emacs and Gforth
15268: @section Blocks Files
15269: @cindex blocks files, use with Emacs
15270: @code{forth-mode} Autodetects blocks files by checking whether the
15271: length of the first line exceeds 1023 characters.  It then tries to
15272: convert the file into normal text format.  When you save the file, it
15273: will be written to disk as normal stream-source file.
15274: 
15275: If you want to write blocks files, use @code{forth-blocks-mode}.  It
15276: inherits all the features from @code{forth-mode}, plus some additions:
15277: 
15278: @itemize @bullet
15279: @item
15280: Files are written to disk in blocks file format.
15281: @item
15282: Screen numbers are displayed in the mode line (enumerated beginning
15283: with the value of `forth-block-base')
15284: @item
15285: Warnings are displayed when lines exceed 64 characters.
15286: @item
15287: The beginning of the currently edited block is marked with an
15288: overlay-arrow. 
15289: @end itemize
15290: 
15291: There are some restrictions you should be aware of.  When you open a
15292: blocks file that contains tabulator or newline characters, these
15293: characters will be translated into spaces when the file is written
15294: back to disk.  If tabs or newlines are encountered during blocks file
15295: reading, an error is output to the echo area. So have a look at the
15296: `*Messages*' buffer, when Emacs' bell rings during reading.
15297: 
15298: Please consult the docstring of @code{forth-blocks-mode} for more
15299: information by typing @kbd{C-h v forth-blocks-mode}).
15300: 
15301: @c ******************************************************************
15302: @node Image Files, Engine, Emacs and Gforth, Top
15303: @chapter Image Files
15304: @cindex image file
15305: @cindex @file{.fi} files
15306: @cindex precompiled Forth code
15307: @cindex dictionary in persistent form
15308: @cindex persistent form of dictionary
15309: 
15310: An image file is a file containing an image of the Forth dictionary,
15311: i.e., compiled Forth code and data residing in the dictionary.  By
15312: convention, we use the extension @code{.fi} for image files.
15313: 
15314: @menu
15315: * Image Licensing Issues::      Distribution terms for images.
15316: * Image File Background::       Why have image files?
15317: * Non-Relocatable Image Files::  don't always work.
15318: * Data-Relocatable Image Files::  are better.
15319: * Fully Relocatable Image Files::  better yet.
15320: * Stack and Dictionary Sizes::  Setting the default sizes for an image.
15321: * Running Image Files::         @code{gforth -i @i{file}} or @i{file}.
15322: * Modifying the Startup Sequence::  and turnkey applications.
15323: @end menu
15324: 
15325: @node Image Licensing Issues, Image File Background, Image Files, Image Files
15326: @section Image Licensing Issues
15327: @cindex license for images
15328: @cindex image license
15329: 
15330: An image created with @code{gforthmi} (@pxref{gforthmi}) or
15331: @code{savesystem} (@pxref{Non-Relocatable Image Files}) includes the
15332: original image; i.e., according to copyright law it is a derived work of
15333: the original image.
15334: 
15335: Since Gforth is distributed under the GNU GPL, the newly created image
15336: falls under the GNU GPL, too. In particular, this means that if you
15337: distribute the image, you have to make all of the sources for the image
15338: available, including those you wrote.  For details see @ref{Copying, ,
15339: GNU General Public License (Section 3)}.
15340: 
15341: If you create an image with @code{cross} (@pxref{cross.fs}), the image
15342: contains only code compiled from the sources you gave it; if none of
15343: these sources is under the GPL, the terms discussed above do not apply
15344: to the image. However, if your image needs an engine (a gforth binary)
15345: that is under the GPL, you should make sure that you distribute both in
15346: a way that is at most a @emph{mere aggregation}, if you don't want the
15347: terms of the GPL to apply to the image.
15348: 
15349: @node Image File Background, Non-Relocatable Image Files, Image Licensing Issues, Image Files
15350: @section Image File Background
15351: @cindex image file background
15352: 
15353: Gforth consists not only of primitives (in the engine), but also of
15354: definitions written in Forth. Since the Forth compiler itself belongs to
15355: those definitions, it is not possible to start the system with the
15356: engine and the Forth source alone. Therefore we provide the Forth
15357: code as an image file in nearly executable form. When Gforth starts up,
15358: a C routine loads the image file into memory, optionally relocates the
15359: addresses, then sets up the memory (stacks etc.) according to
15360: information in the image file, and (finally) starts executing Forth
15361: code.
15362: 
15363: The default image file is @file{gforth.fi} (in the @code{GFORTHPATH}).
15364: You can use a different image by using the @code{-i},
15365: @code{--image-file} or @code{--appl-image} options (@pxref{Invoking
15366: Gforth}), e.g.:
15367: 
15368: @example
15369: gforth-fast -i myimage.fi
15370: @end example
15371: 
15372: There are different variants of image files, and they represent
15373: different compromises between the goals of making it easy to generate
15374: image files and making them portable.
15375: 
15376: @cindex relocation at run-time
15377: Win32Forth 3.4 and Mitch Bradley's @code{cforth} use relocation at
15378: run-time. This avoids many of the complications discussed below (image
15379: files are data relocatable without further ado), but costs performance
15380: (one addition per memory access) and makes it difficult to pass
15381: addresses between Forth and library calls or other programs.
15382: 
15383: @cindex relocation at load-time
15384: By contrast, the Gforth loader performs relocation at image load time. The
15385: loader also has to replace tokens that represent primitive calls with the
15386: appropriate code-field addresses (or code addresses in the case of
15387: direct threading).
15388: 
15389: There are three kinds of image files, with different degrees of
15390: relocatability: non-relocatable, data-relocatable, and fully relocatable
15391: image files.
15392: 
15393: @cindex image file loader
15394: @cindex relocating loader
15395: @cindex loader for image files
15396: These image file variants have several restrictions in common; they are
15397: caused by the design of the image file loader:
15398: 
15399: @itemize @bullet
15400: @item
15401: There is only one segment; in particular, this means, that an image file
15402: cannot represent @code{ALLOCATE}d memory chunks (and pointers to
15403: them). The contents of the stacks are not represented, either.
15404: 
15405: @item
15406: The only kinds of relocation supported are: adding the same offset to
15407: all cells that represent data addresses; and replacing special tokens
15408: with code addresses or with pieces of machine code.
15409: 
15410: If any complex computations involving addresses are performed, the
15411: results cannot be represented in the image file. Several applications that
15412: use such computations come to mind:
15413: 
15414: @itemize @minus
15415: @item
15416: Hashing addresses (or data structures which contain addresses) for table
15417: lookup. If you use Gforth's @code{table}s or @code{wordlist}s for this
15418: purpose, you will have no problem, because the hash tables are
15419: recomputed automatically when the system is started. If you use your own
15420: hash tables, you will have to do something similar.
15421: 
15422: @item
15423: There's a cute implementation of doubly-linked lists that uses
15424: @code{XOR}ed addresses. You could represent such lists as singly-linked
15425: in the image file, and restore the doubly-linked representation on
15426: startup.@footnote{In my opinion, though, you should think thrice before
15427: using a doubly-linked list (whatever implementation).}
15428: 
15429: @item
15430: The code addresses of run-time routines like @code{docol:} cannot be
15431: represented in the image file (because their tokens would be replaced by
15432: machine code in direct threaded implementations). As a workaround,
15433: compute these addresses at run-time with @code{>code-address} from the
15434: executions tokens of appropriate words (see the definitions of
15435: @code{docol:} and friends in @file{kernel/getdoers.fs}).
15436: 
15437: @item
15438: On many architectures addresses are represented in machine code in some
15439: shifted or mangled form. You cannot put @code{CODE} words that contain
15440: absolute addresses in this form in a relocatable image file. Workarounds
15441: are representing the address in some relative form (e.g., relative to
15442: the CFA, which is present in some register), or loading the address from
15443: a place where it is stored in a non-mangled form.
15444: @end itemize
15445: @end itemize
15446: 
15447: @node  Non-Relocatable Image Files, Data-Relocatable Image Files, Image File Background, Image Files
15448: @section Non-Relocatable Image Files
15449: @cindex non-relocatable image files
15450: @cindex image file, non-relocatable
15451: 
15452: These files are simple memory dumps of the dictionary. They are
15453: specific to the executable (i.e., @file{gforth} file) they were
15454: created with. What's worse, they are specific to the place on which
15455: the dictionary resided when the image was created. Now, there is no
15456: guarantee that the dictionary will reside at the same place the next
15457: time you start Gforth, so there's no guarantee that a non-relocatable
15458: image will work the next time (Gforth will complain instead of
15459: crashing, though).  Indeed, on OSs with (enabled) address-space
15460: randomization non-relocatable images are unlikely to work.
15461: 
15462: You can create a non-relocatable image file with @code{savesystem}, e.g.:
15463: 
15464: @example
15465: gforth app.fs -e "savesystem app.fi bye"
15466: @end example
15467: 
15468: doc-savesystem
15469: 
15470: 
15471: @node Data-Relocatable Image Files, Fully Relocatable Image Files, Non-Relocatable Image Files, Image Files
15472: @section Data-Relocatable Image Files
15473: @cindex data-relocatable image files
15474: @cindex image file, data-relocatable
15475: 
15476: These files contain relocatable data addresses, but fixed code
15477: addresses (instead of tokens). They are specific to the executable
15478: (i.e., @file{gforth} file) they were created with.  Also, they disable
15479: dynamic native code generation (typically a factor of 2 in speed).
15480: You get a data-relocatable image, if you pass the engine you want to
15481: use through the @code{GFORTHD} environment variable to @file{gforthmi}
15482: (@pxref{gforthmi}), e.g.
15483: 
15484: @example
15485: GFORTHD="/usr/bin/gforth-fast --no-dynamic" gforthmi myimage.fi source.fs
15486: @end example
15487: 
15488: Note that the @code{--no-dynamic} is required here for the image to
15489: work (otherwise it will contain references to dynamically generated
15490: code that is not saved in the image).
15491: 
15492: 
15493: @node Fully Relocatable Image Files, Stack and Dictionary Sizes, Data-Relocatable Image Files, Image Files
15494: @section Fully Relocatable Image Files
15495: @cindex fully relocatable image files
15496: @cindex image file, fully relocatable
15497: 
15498: @cindex @file{kern*.fi}, relocatability
15499: @cindex @file{gforth.fi}, relocatability
15500: These image files have relocatable data addresses, and tokens for code
15501: addresses. They can be used with different binaries (e.g., with and
15502: without debugging) on the same machine, and even across machines with
15503: the same data formats (byte order, cell size, floating point format),
15504: and they work with dynamic native code generation.  However, they are
15505: usually specific to the version of Gforth they were created with. The
15506: files @file{gforth.fi} and @file{kernl*.fi} are fully relocatable.
15507: 
15508: There are two ways to create a fully relocatable image file:
15509: 
15510: @menu
15511: * gforthmi::                    The normal way
15512: * cross.fs::                    The hard way
15513: @end menu
15514: 
15515: @node gforthmi, cross.fs, Fully Relocatable Image Files, Fully Relocatable Image Files
15516: @subsection @file{gforthmi}
15517: @cindex @file{comp-i.fs}
15518: @cindex @file{gforthmi}
15519: 
15520: You will usually use @file{gforthmi}. If you want to create an
15521: image @i{file} that contains everything you would load by invoking
15522: Gforth with @code{gforth @i{options}}, you simply say:
15523: @example
15524: gforthmi @i{file} @i{options}
15525: @end example
15526: 
15527: E.g., if you want to create an image @file{asm.fi} that has the file
15528: @file{asm.fs} loaded in addition to the usual stuff, you could do it
15529: like this:
15530: 
15531: @example
15532: gforthmi asm.fi asm.fs
15533: @end example
15534: 
15535: @file{gforthmi} is implemented as a sh script and works like this: It
15536: produces two non-relocatable images for different addresses and then
15537: compares them. Its output reflects this: first you see the output (if
15538: any) of the two Gforth invocations that produce the non-relocatable image
15539: files, then you see the output of the comparing program: It displays the
15540: offset used for data addresses and the offset used for code addresses;
15541: moreover, for each cell that cannot be represented correctly in the
15542: image files, it displays a line like this:
15543: 
15544: @example
15545:      78DC         BFFFFA50         BFFFFA40
15546: @end example
15547: 
15548: This means that at offset $78dc from @code{forthstart}, one input image
15549: contains $bffffa50, and the other contains $bffffa40. Since these cells
15550: cannot be represented correctly in the output image, you should examine
15551: these places in the dictionary and verify that these cells are dead
15552: (i.e., not read before they are written).
15553: 
15554: @cindex --application, @code{gforthmi} option
15555: If you insert the option @code{--application} in front of the image file
15556: name, you will get an image that uses the @code{--appl-image} option
15557: instead of the @code{--image-file} option (@pxref{Invoking
15558: Gforth}). When you execute such an image on Unix (by typing the image
15559: name as command), the Gforth engine will pass all options to the image
15560: instead of trying to interpret them as engine options.
15561: 
15562: If you type @file{gforthmi} with no arguments, it prints some usage
15563: instructions.
15564: 
15565: @cindex @code{savesystem} during @file{gforthmi}
15566: @cindex @code{bye} during @file{gforthmi}
15567: @cindex doubly indirect threaded code
15568: @cindex environment variables
15569: @cindex @code{GFORTHD} -- environment variable
15570: @cindex @code{GFORTH} -- environment variable
15571: @cindex @code{gforth-ditc}
15572: There are a few wrinkles: After processing the passed @i{options}, the
15573: words @code{savesystem} and @code{bye} must be visible. A special
15574: doubly indirect threaded version of the @file{gforth} executable is
15575: used for creating the non-relocatable images; you can pass the exact
15576: filename of this executable through the environment variable
15577: @code{GFORTHD} (default: @file{gforth-ditc}); if you pass a version
15578: that is not doubly indirect threaded, you will not get a fully
15579: relocatable image, but a data-relocatable image
15580: (@pxref{Data-Relocatable Image Files}), because there is no code
15581: address offset). The normal @file{gforth} executable is used for
15582: creating the relocatable image; you can pass the exact filename of
15583: this executable through the environment variable @code{GFORTH}.
15584: 
15585: @node cross.fs,  , gforthmi, Fully Relocatable Image Files
15586: @subsection @file{cross.fs}
15587: @cindex @file{cross.fs}
15588: @cindex cross-compiler
15589: @cindex metacompiler
15590: @cindex target compiler
15591: 
15592: You can also use @code{cross}, a batch compiler that accepts a Forth-like
15593: programming language (@pxref{Cross Compiler}).
15594: 
15595: @code{cross} allows you to create image files for machines with
15596: different data sizes and data formats than the one used for generating
15597: the image file. You can also use it to create an application image that
15598: does not contain a Forth compiler. These features are bought with
15599: restrictions and inconveniences in programming. E.g., addresses have to
15600: be stored in memory with special words (@code{A!}, @code{A,}, etc.) in
15601: order to make the code relocatable.
15602: 
15603: 
15604: @node Stack and Dictionary Sizes, Running Image Files, Fully Relocatable Image Files, Image Files
15605: @section Stack and Dictionary Sizes
15606: @cindex image file, stack and dictionary sizes
15607: @cindex dictionary size default
15608: @cindex stack size default
15609: 
15610: If you invoke Gforth with a command line flag for the size
15611: (@pxref{Invoking Gforth}), the size you specify is stored in the
15612: dictionary. If you save the dictionary with @code{savesystem} or create
15613: an image with @file{gforthmi}, this size will become the default
15614: for the resulting image file. E.g., the following will create a
15615: fully relocatable version of @file{gforth.fi} with a 1MB dictionary:
15616: 
15617: @example
15618: gforthmi gforth.fi -m 1M
15619: @end example
15620: 
15621: In other words, if you want to set the default size for the dictionary
15622: and the stacks of an image, just invoke @file{gforthmi} with the
15623: appropriate options when creating the image.
15624: 
15625: @cindex stack size, cache-friendly
15626: Note: For cache-friendly behaviour (i.e., good performance), you should
15627: make the sizes of the stacks modulo, say, 2K, somewhat different. E.g.,
15628: the default stack sizes are: data: 16k (mod 2k=0); fp: 15.5k (mod
15629: 2k=1.5k); return: 15k(mod 2k=1k); locals: 14.5k (mod 2k=0.5k).
15630: 
15631: @node Running Image Files, Modifying the Startup Sequence, Stack and Dictionary Sizes, Image Files
15632: @section Running Image Files
15633: @cindex running image files
15634: @cindex invoking image files
15635: @cindex image file invocation
15636: 
15637: @cindex -i, invoke image file
15638: @cindex --image file, invoke image file
15639: You can invoke Gforth with an image file @i{image} instead of the
15640: default @file{gforth.fi} with the @code{-i} flag (@pxref{Invoking Gforth}):
15641: @example
15642: gforth -i @i{image}
15643: @end example
15644: 
15645: @cindex executable image file
15646: @cindex image file, executable
15647: If your operating system supports starting scripts with a line of the
15648: form @code{#! ...}, you just have to type the image file name to start
15649: Gforth with this image file (note that the file extension @code{.fi} is
15650: just a convention). I.e., to run Gforth with the image file @i{image},
15651: you can just type @i{image} instead of @code{gforth -i @i{image}}.
15652: This works because every @code{.fi} file starts with a line of this
15653: format:
15654: 
15655: @example
15656: #! /usr/local/bin/gforth-0.4.0 -i
15657: @end example
15658: 
15659: The file and pathname for the Gforth engine specified on this line is
15660: the specific Gforth executable that it was built against; i.e. the value
15661: of the environment variable @code{GFORTH} at the time that
15662: @file{gforthmi} was executed.
15663: 
15664: You can make use of the same shell capability to make a Forth source
15665: file into an executable. For example, if you place this text in a file:
15666: 
15667: @example
15668: #! /usr/local/bin/gforth
15669: 
15670: ." Hello, world" CR
15671: bye
15672: @end example
15673: 
15674: @noindent
15675: and then make the file executable (chmod +x in Unix), you can run it
15676: directly from the command line. The sequence @code{#!} is used in two
15677: ways; firstly, it is recognised as a ``magic sequence'' by the operating
15678: system@footnote{The Unix kernel actually recognises two types of files:
15679: executable files and files of data, where the data is processed by an
15680: interpreter that is specified on the ``interpreter line'' -- the first
15681: line of the file, starting with the sequence #!. There may be a small
15682: limit (e.g., 32) on the number of characters that may be specified on
15683: the interpreter line.} secondly it is treated as a comment character by
15684: Gforth. Because of the second usage, a space is required between
15685: @code{#!} and the path to the executable (moreover, some Unixes
15686: require the sequence @code{#! /}).
15687: 
15688: The disadvantage of this latter technique, compared with using
15689: @file{gforthmi}, is that it is slightly slower; the Forth source code is
15690: compiled on-the-fly, each time the program is invoked.
15691: 
15692: doc-#!
15693: 
15694: 
15695: @node Modifying the Startup Sequence,  , Running Image Files, Image Files
15696: @section Modifying the Startup Sequence
15697: @cindex startup sequence for image file
15698: @cindex image file initialization sequence
15699: @cindex initialization sequence of image file
15700: 
15701: You can add your own initialization to the startup sequence of an image
15702: through the deferred word @code{'cold}. @code{'cold} is invoked just
15703: before the image-specific command line processing (i.e., loading files
15704: and evaluating (@code{-e}) strings) starts.
15705: 
15706: A sequence for adding your initialization usually looks like this:
15707: 
15708: @example
15709: :noname
15710:     Defers 'cold \ do other initialization stuff (e.g., rehashing wordlists)
15711:     ... \ your stuff
15712: ; IS 'cold
15713: @end example
15714: 
15715: After @code{'cold}, Gforth processes the image options
15716: (@pxref{Invoking Gforth}), and then it performs @code{bootmessage},
15717: another deferred word.  This normally prints Gforth's startup message
15718: and does nothing else.
15719: 
15720: @cindex turnkey image files
15721: @cindex image file, turnkey applications
15722: So, if you want to make a turnkey image (i.e., an image for an
15723: application instead of an extended Forth system), you can do this in
15724: two ways:
15725: 
15726: @itemize @bullet
15727: 
15728: @item
15729: If you want to do your interpretation of the OS command-line
15730: arguments, hook into @code{'cold}.  In that case you probably also
15731: want to build the image with @code{gforthmi --application}
15732: (@pxref{gforthmi}) to keep the engine from processing OS command line
15733: options.  You can then do your own command-line processing with
15734: @code{next-arg} 
15735: 
15736: @item
15737: If you want to have the normal Gforth processing of OS command-line
15738: arguments, hook into @code{bootmessage}.
15739: 
15740: @end itemize
15741: 
15742: In either case, you probably do not want the word that you execute in
15743: these hooks to exit normally, but use @code{bye} or @code{throw}.
15744: Otherwise the Gforth startup process would continue and eventually
15745: present the Forth command line to the user.
15746: 
15747: doc-'cold
15748: doc-bootmessage
15749: 
15750: @c ******************************************************************
15751: @node Engine, Cross Compiler, Image Files, Top
15752: @chapter Engine
15753: @cindex engine
15754: @cindex virtual machine
15755: 
15756: Reading this chapter is not necessary for programming with Gforth. It
15757: may be helpful for finding your way in the Gforth sources.
15758: 
15759: The ideas in this section have also been published in the following
15760: papers: Bernd Paysan, @cite{ANS fig/GNU/??? Forth} (in German),
15761: Forth-Tagung '93; M. Anton Ertl,
15762: @cite{@uref{http://www.complang.tuwien.ac.at/papers/ertl93.ps.Z, A
15763: Portable Forth Engine}}, EuroForth '93; M. Anton Ertl,
15764: @cite{@uref{http://www.complang.tuwien.ac.at/papers/ertl02.ps.gz,
15765: Threaded code variations and optimizations (extended version)}},
15766: Forth-Tagung '02.
15767: 
15768: @menu
15769: * Portability::                 
15770: * Threading::                   
15771: * Primitives::                  
15772: * Performance::                 
15773: @end menu
15774: 
15775: @node Portability, Threading, Engine, Engine
15776: @section Portability
15777: @cindex engine portability
15778: 
15779: An important goal of the Gforth Project is availability across a wide
15780: range of personal machines. fig-Forth, and, to a lesser extent, F83,
15781: achieved this goal by manually coding the engine in assembly language
15782: for several then-popular processors. This approach is very
15783: labor-intensive and the results are short-lived due to progress in
15784: computer architecture.
15785: 
15786: @cindex C, using C for the engine
15787: Others have avoided this problem by coding in C, e.g., Mitch Bradley
15788: (cforth), Mikael Patel (TILE) and Dirk Zoller (pfe). This approach is
15789: particularly popular for UNIX-based Forths due to the large variety of
15790: architectures of UNIX machines. Unfortunately an implementation in C
15791: does not mix well with the goals of efficiency and with using
15792: traditional techniques: Indirect or direct threading cannot be expressed
15793: in C, and switch threading, the fastest technique available in C, is
15794: significantly slower. Another problem with C is that it is very
15795: cumbersome to express double integer arithmetic.
15796: 
15797: @cindex GNU C for the engine
15798: @cindex long long
15799: Fortunately, there is a portable language that does not have these
15800: limitations: GNU C, the version of C processed by the GNU C compiler
15801: (@pxref{C Extensions, , Extensions to the C Language Family, gcc.info,
15802: GNU C Manual}). Its labels as values feature (@pxref{Labels as Values, ,
15803: Labels as Values, gcc.info, GNU C Manual}) makes direct and indirect
15804: threading possible, its @code{long long} type (@pxref{Long Long, ,
15805: Double-Word Integers, gcc.info, GNU C Manual}) corresponds to Forth's
15806: double numbers on many systems.  GNU C is freely available on all
15807: important (and many unimportant) UNIX machines, VMS, 80386s running
15808: MS-DOS, the Amiga, and the Atari ST, so a Forth written in GNU C can run
15809: on all these machines.
15810: 
15811: Writing in a portable language has the reputation of producing code that
15812: is slower than assembly. For our Forth engine we repeatedly looked at
15813: the code produced by the compiler and eliminated most compiler-induced
15814: inefficiencies by appropriate changes in the source code.
15815: 
15816: @cindex explicit register declarations
15817: @cindex --enable-force-reg, configuration flag
15818: @cindex -DFORCE_REG
15819: However, register allocation cannot be portably influenced by the
15820: programmer, leading to some inefficiencies on register-starved
15821: machines. We use explicit register declarations (@pxref{Explicit Reg
15822: Vars, , Variables in Specified Registers, gcc.info, GNU C Manual}) to
15823: improve the speed on some machines. They are turned on by using the
15824: configuration flag @code{--enable-force-reg} (@code{gcc} switch
15825: @code{-DFORCE_REG}). Unfortunately, this feature not only depends on the
15826: machine, but also on the compiler version: On some machines some
15827: compiler versions produce incorrect code when certain explicit register
15828: declarations are used. So by default @code{-DFORCE_REG} is not used.
15829: 
15830: @node Threading, Primitives, Portability, Engine
15831: @section Threading
15832: @cindex inner interpreter implementation
15833: @cindex threaded code implementation
15834: 
15835: @cindex labels as values
15836: GNU C's labels as values extension (available since @code{gcc-2.0},
15837: @pxref{Labels as Values, , Labels as Values, gcc.info, GNU C Manual})
15838: makes it possible to take the address of @i{label} by writing
15839: @code{&&@i{label}}.  This address can then be used in a statement like
15840: @code{goto *@i{address}}. I.e., @code{goto *&&x} is the same as
15841: @code{goto x}.
15842: 
15843: @cindex @code{NEXT}, indirect threaded
15844: @cindex indirect threaded inner interpreter
15845: @cindex inner interpreter, indirect threaded
15846: With this feature an indirect threaded @code{NEXT} looks like:
15847: @example
15848: cfa = *ip++;
15849: ca = *cfa;
15850: goto *ca;
15851: @end example
15852: @cindex instruction pointer
15853: For those unfamiliar with the names: @code{ip} is the Forth instruction
15854: pointer; the @code{cfa} (code-field address) corresponds to ANS Forths
15855: execution token and points to the code field of the next word to be
15856: executed; The @code{ca} (code address) fetched from there points to some
15857: executable code, e.g., a primitive or the colon definition handler
15858: @code{docol}.
15859: 
15860: @cindex @code{NEXT}, direct threaded
15861: @cindex direct threaded inner interpreter
15862: @cindex inner interpreter, direct threaded
15863: Direct threading is even simpler:
15864: @example
15865: ca = *ip++;
15866: goto *ca;
15867: @end example
15868: 
15869: Of course we have packaged the whole thing neatly in macros called
15870: @code{NEXT} and @code{NEXT1} (the part of @code{NEXT} after fetching the cfa).
15871: 
15872: @menu
15873: * Scheduling::                  
15874: * Direct or Indirect Threaded?::  
15875: * Dynamic Superinstructions::   
15876: * DOES>::                       
15877: @end menu
15878: 
15879: @node Scheduling, Direct or Indirect Threaded?, Threading, Threading
15880: @subsection Scheduling
15881: @cindex inner interpreter optimization
15882: 
15883: There is a little complication: Pipelined and superscalar processors,
15884: i.e., RISC and some modern CISC machines can process independent
15885: instructions while waiting for the results of an instruction. The
15886: compiler usually reorders (schedules) the instructions in a way that
15887: achieves good usage of these delay slots. However, on our first tries
15888: the compiler did not do well on scheduling primitives. E.g., for
15889: @code{+} implemented as
15890: @example
15891: n=sp[0]+sp[1];
15892: sp++;
15893: sp[0]=n;
15894: NEXT;
15895: @end example
15896: the @code{NEXT} comes strictly after the other code, i.e., there is
15897: nearly no scheduling. After a little thought the problem becomes clear:
15898: The compiler cannot know that @code{sp} and @code{ip} point to different
15899: addresses (and the version of @code{gcc} we used would not know it even
15900: if it was possible), so it could not move the load of the cfa above the
15901: store to the TOS. Indeed the pointers could be the same, if code on or
15902: very near the top of stack were executed. In the interest of speed we
15903: chose to forbid this probably unused ``feature'' and helped the compiler
15904: in scheduling: @code{NEXT} is divided into several parts:
15905: @code{NEXT_P0}, @code{NEXT_P1} and @code{NEXT_P2}). @code{+} now looks
15906: like:
15907: @example
15908: NEXT_P0;
15909: n=sp[0]+sp[1];
15910: sp++;
15911: NEXT_P1;
15912: sp[0]=n;
15913: NEXT_P2;
15914: @end example
15915: 
15916: There are various schemes that distribute the different operations of
15917: NEXT between these parts in several ways; in general, different schemes
15918: perform best on different processors.  We use a scheme for most
15919: architectures that performs well for most processors of this
15920: architecture; in the future we may switch to benchmarking and chosing
15921: the scheme on installation time.
15922: 
15923: 
15924: @node Direct or Indirect Threaded?, Dynamic Superinstructions, Scheduling, Threading
15925: @subsection Direct or Indirect Threaded?
15926: @cindex threading, direct or indirect?
15927: 
15928: Threaded forth code consists of references to primitives (simple machine
15929: code routines like @code{+}) and to non-primitives (e.g., colon
15930: definitions, variables, constants); for a specific class of
15931: non-primitives (e.g., variables) there is one code routine (e.g.,
15932: @code{dovar}), but each variable needs a separate reference to its data.
15933: 
15934: Traditionally Forth has been implemented as indirect threaded code,
15935: because this allows to use only one cell to reference a non-primitive
15936: (basically you point to the data, and find the code address there).
15937: 
15938: @cindex primitive-centric threaded code
15939: However, threaded code in Gforth (since 0.6.0) uses two cells for
15940: non-primitives, one for the code address, and one for the data address;
15941: the data pointer is an immediate argument for the virtual machine
15942: instruction represented by the code address.  We call this
15943: @emph{primitive-centric} threaded code, because all code addresses point
15944: to simple primitives.  E.g., for a variable, the code address is for
15945: @code{lit} (also used for integer literals like @code{99}).
15946: 
15947: Primitive-centric threaded code allows us to use (faster) direct
15948: threading as dispatch method, completely portably (direct threaded code
15949: in Gforth before 0.6.0 required architecture-specific code).  It also
15950: eliminates the performance problems related to I-cache consistency that
15951: 386 implementations have with direct threaded code, and allows
15952: additional optimizations.
15953: 
15954: @cindex hybrid direct/indirect threaded code
15955: There is a catch, however: the @var{xt} parameter of @code{execute} can
15956: occupy only one cell, so how do we pass non-primitives with their code
15957: @emph{and} data addresses to them?  Our answer is to use indirect
15958: threaded dispatch for @code{execute} and other words that use a
15959: single-cell xt.  So, normal threaded code in colon definitions uses
15960: direct threading, and @code{execute} and similar words, which dispatch
15961: to xts on the data stack, use indirect threaded code.  We call this
15962: @emph{hybrid direct/indirect} threaded code.
15963: 
15964: @cindex engines, gforth vs. gforth-fast vs. gforth-itc
15965: @cindex gforth engine
15966: @cindex gforth-fast engine
15967: The engines @command{gforth} and @command{gforth-fast} use hybrid
15968: direct/indirect threaded code.  This means that with these engines you
15969: cannot use @code{,} to compile an xt.  Instead, you have to use
15970: @code{compile,}.
15971: 
15972: @cindex gforth-itc engine
15973: If you want to compile xts with @code{,}, use @command{gforth-itc}.
15974: This engine uses plain old indirect threaded code.  It still compiles in
15975: a primitive-centric style, so you cannot use @code{compile,} instead of
15976: @code{,} (e.g., for producing tables of xts with @code{] word1 word2
15977: ... [}).  If you want to do that, you have to use @command{gforth-itc}
15978: and execute @code{' , is compile,}.  Your program can check if it is
15979: running on a hybrid direct/indirect threaded engine or a pure indirect
15980: threaded engine with @code{threading-method} (@pxref{Threading Words}).
15981: 
15982: 
15983: @node Dynamic Superinstructions, DOES>, Direct or Indirect Threaded?, Threading
15984: @subsection Dynamic Superinstructions
15985: @cindex Dynamic superinstructions with replication
15986: @cindex Superinstructions
15987: @cindex Replication
15988: 
15989: The engines @command{gforth} and @command{gforth-fast} use another
15990: optimization: Dynamic superinstructions with replication.  As an
15991: example, consider the following colon definition:
15992: 
15993: @example
15994: : squared ( n1 -- n2 )
15995:   dup * ;
15996: @end example
15997: 
15998: Gforth compiles this into the threaded code sequence
15999: 
16000: @example
16001: dup
16002: *
16003: ;s
16004: @end example
16005: 
16006: In normal direct threaded code there is a code address occupying one
16007: cell for each of these primitives.  Each code address points to a
16008: machine code routine, and the interpreter jumps to this machine code in
16009: order to execute the primitive.  The routines for these three
16010: primitives are (in @command{gforth-fast} on the 386):
16011: 
16012: @example
16013: Code dup  
16014: ( $804B950 )  add     esi , # -4  \ $83 $C6 $FC 
16015: ( $804B953 )  add     ebx , # 4  \ $83 $C3 $4 
16016: ( $804B956 )  mov     dword ptr 4 [esi] , ecx  \ $89 $4E $4 
16017: ( $804B959 )  jmp     dword ptr FC [ebx]  \ $FF $63 $FC 
16018: end-code
16019: Code *  
16020: ( $804ACC4 )  mov     eax , dword ptr 4 [esi]  \ $8B $46 $4 
16021: ( $804ACC7 )  add     esi , # 4  \ $83 $C6 $4 
16022: ( $804ACCA )  add     ebx , # 4  \ $83 $C3 $4 
16023: ( $804ACCD )  imul    ecx , eax  \ $F $AF $C8 
16024: ( $804ACD0 )  jmp     dword ptr FC [ebx]  \ $FF $63 $FC 
16025: end-code
16026: Code ;s  
16027: ( $804A693 )  mov     eax , dword ptr [edi]  \ $8B $7 
16028: ( $804A695 )  add     edi , # 4  \ $83 $C7 $4 
16029: ( $804A698 )  lea     ebx , dword ptr 4 [eax]  \ $8D $58 $4 
16030: ( $804A69B )  jmp     dword ptr FC [ebx]  \ $FF $63 $FC 
16031: end-code
16032: @end example
16033: 
16034: With dynamic superinstructions and replication the compiler does not
16035: just lay down the threaded code, but also copies the machine code
16036: fragments, usually without the jump at the end.
16037: 
16038: @example
16039: ( $4057D27D )  add     esi , # -4  \ $83 $C6 $FC 
16040: ( $4057D280 )  add     ebx , # 4  \ $83 $C3 $4 
16041: ( $4057D283 )  mov     dword ptr 4 [esi] , ecx  \ $89 $4E $4 
16042: ( $4057D286 )  mov     eax , dword ptr 4 [esi]  \ $8B $46 $4 
16043: ( $4057D289 )  add     esi , # 4  \ $83 $C6 $4 
16044: ( $4057D28C )  add     ebx , # 4  \ $83 $C3 $4 
16045: ( $4057D28F )  imul    ecx , eax  \ $F $AF $C8 
16046: ( $4057D292 )  mov     eax , dword ptr [edi]  \ $8B $7 
16047: ( $4057D294 )  add     edi , # 4  \ $83 $C7 $4 
16048: ( $4057D297 )  lea     ebx , dword ptr 4 [eax]  \ $8D $58 $4 
16049: ( $4057D29A )  jmp     dword ptr FC [ebx]  \ $FF $63 $FC 
16050: @end example
16051: 
16052: Only when a threaded-code control-flow change happens (e.g., in
16053: @code{;s}), the jump is appended.  This optimization eliminates many of
16054: these jumps and makes the rest much more predictable.  The speedup
16055: depends on the processor and the application; on the Athlon and Pentium
16056: III this optimization typically produces a speedup by a factor of 2.
16057: 
16058: The code addresses in the direct-threaded code are set to point to the
16059: appropriate points in the copied machine code, in this example like
16060: this:
16061: 
16062: @example
16063: primitive  code address
16064:    dup       $4057D27D
16065:    *         $4057D286
16066:    ;s        $4057D292
16067: @end example
16068: 
16069: Thus there can be threaded-code jumps to any place in this piece of
16070: code.  This also simplifies decompilation quite a bit.
16071: 
16072: @cindex --no-dynamic command-line option
16073: @cindex --no-super command-line option
16074: You can disable this optimization with @option{--no-dynamic}.  You can
16075: use the copying without eliminating the jumps (i.e., dynamic
16076: replication, but without superinstructions) with @option{--no-super};
16077: this gives the branch prediction benefit alone; the effect on
16078: performance depends on the CPU; on the Athlon and Pentium III the
16079: speedup is a little less than for dynamic superinstructions with
16080: replication.
16081: 
16082: @cindex patching threaded code
16083: One use of these options is if you want to patch the threaded code.
16084: With superinstructions, many of the dispatch jumps are eliminated, so
16085: patching often has no effect.  These options preserve all the dispatch
16086: jumps.
16087: 
16088: @cindex --dynamic command-line option
16089: On some machines dynamic superinstructions are disabled by default,
16090: because it is unsafe on these machines.  However, if you feel
16091: adventurous, you can enable it with @option{--dynamic}.
16092: 
16093: @node DOES>,  , Dynamic Superinstructions, Threading
16094: @subsection DOES>
16095: @cindex @code{DOES>} implementation
16096: 
16097: @cindex @code{dodoes} routine
16098: @cindex @code{DOES>}-code
16099: One of the most complex parts of a Forth engine is @code{dodoes}, i.e.,
16100: the chunk of code executed by every word defined by a
16101: @code{CREATE}...@code{DOES>} pair; actually with primitive-centric code,
16102: this is only needed if the xt of the word is @code{execute}d. The main
16103: problem here is: How to find the Forth code to be executed, i.e. the
16104: code after the @code{DOES>} (the @code{DOES>}-code)? There are two
16105: solutions:
16106: 
16107: In fig-Forth the code field points directly to the @code{dodoes} and the
16108: @code{DOES>}-code address is stored in the cell after the code address
16109: (i.e. at @code{@i{CFA} cell+}). It may seem that this solution is
16110: illegal in the Forth-79 and all later standards, because in fig-Forth
16111: this address lies in the body (which is illegal in these
16112: standards). However, by making the code field larger for all words this
16113: solution becomes legal again.  We use this approach.  Leaving a cell
16114: unused in most words is a bit wasteful, but on the machines we are
16115: targeting this is hardly a problem.
16116: 
16117: 
16118: @node Primitives, Performance, Threading, Engine
16119: @section Primitives
16120: @cindex primitives, implementation
16121: @cindex virtual machine instructions, implementation
16122: 
16123: @menu
16124: * Automatic Generation::        
16125: * TOS Optimization::            
16126: * Produced code::               
16127: @end menu
16128: 
16129: @node Automatic Generation, TOS Optimization, Primitives, Primitives
16130: @subsection Automatic Generation
16131: @cindex primitives, automatic generation
16132: 
16133: @cindex @file{prims2x.fs}
16134: 
16135: Since the primitives are implemented in a portable language, there is no
16136: longer any need to minimize the number of primitives. On the contrary,
16137: having many primitives has an advantage: speed. In order to reduce the
16138: number of errors in primitives and to make programming them easier, we
16139: provide a tool, the primitive generator (@file{prims2x.fs} aka Vmgen,
16140: @pxref{Top, Vmgen, Introduction, vmgen, Vmgen}), that automatically
16141: generates most (and sometimes all) of the C code for a primitive from
16142: the stack effect notation.  The source for a primitive has the following
16143: form:
16144: 
16145: @cindex primitive source format
16146: @format
16147: @i{Forth-name}  ( @i{stack-effect} )        @i{category}    [@i{pronounc.}]
16148: [@code{""}@i{glossary entry}@code{""}]
16149: @i{C code}
16150: [@code{:}
16151: @i{Forth code}]
16152: @end format
16153: 
16154: The items in brackets are optional. The category and glossary fields
16155: are there for generating the documentation, the Forth code is there
16156: for manual implementations on machines without GNU C. E.g., the source
16157: for the primitive @code{+} is:
16158: @example
16159: +    ( n1 n2 -- n )   core    plus
16160: n = n1+n2;
16161: @end example
16162: 
16163: This looks like a specification, but in fact @code{n = n1+n2} is C
16164: code. Our primitive generation tool extracts a lot of information from
16165: the stack effect notations@footnote{We use a one-stack notation, even
16166: though we have separate data and floating-point stacks; The separate
16167: notation can be generated easily from the unified notation.}: The number
16168: of items popped from and pushed on the stack, their type, and by what
16169: name they are referred to in the C code. It then generates a C code
16170: prelude and postlude for each primitive. The final C code for @code{+}
16171: looks like this:
16172: 
16173: @example
16174: I_plus: /* + ( n1 n2 -- n ) */  /* label, stack effect */
16175: /*  */                          /* documentation */
16176: NAME("+")                       /* debugging output (with -DDEBUG) */
16177: @{
16178: DEF_CA                          /* definition of variable ca (indirect threading) */
16179: Cell n1;                        /* definitions of variables */
16180: Cell n2;
16181: Cell n;
16182: NEXT_P0;                        /* NEXT part 0 */
16183: n1 = (Cell) sp[1];              /* input */
16184: n2 = (Cell) TOS;
16185: sp += 1;                        /* stack adjustment */
16186: @{
16187: n = n1+n2;                      /* C code taken from the source */
16188: @}
16189: NEXT_P1;                        /* NEXT part 1 */
16190: TOS = (Cell)n;                  /* output */
16191: NEXT_P2;                        /* NEXT part 2 */
16192: @}
16193: @end example
16194: 
16195: This looks long and inefficient, but the GNU C compiler optimizes quite
16196: well and produces optimal code for @code{+} on, e.g., the R3000 and the
16197: HP RISC machines: Defining the @code{n}s does not produce any code, and
16198: using them as intermediate storage also adds no cost.
16199: 
16200: There are also other optimizations that are not illustrated by this
16201: example: assignments between simple variables are usually for free (copy
16202: propagation). If one of the stack items is not used by the primitive
16203: (e.g.  in @code{drop}), the compiler eliminates the load from the stack
16204: (dead code elimination). On the other hand, there are some things that
16205: the compiler does not do, therefore they are performed by
16206: @file{prims2x.fs}: The compiler does not optimize code away that stores
16207: a stack item to the place where it just came from (e.g., @code{over}).
16208: 
16209: While programming a primitive is usually easy, there are a few cases
16210: where the programmer has to take the actions of the generator into
16211: account, most notably @code{?dup}, but also words that do not (always)
16212: fall through to @code{NEXT}.
16213: 
16214: For more information
16215: 
16216: @node TOS Optimization, Produced code, Automatic Generation, Primitives
16217: @subsection TOS Optimization
16218: @cindex TOS optimization for primitives
16219: @cindex primitives, keeping the TOS in a register
16220: 
16221: An important optimization for stack machine emulators, e.g., Forth
16222: engines, is keeping  one or more of the top stack items in
16223: registers.  If a word has the stack effect @i{in1}...@i{inx} @code{--}
16224: @i{out1}...@i{outy}, keeping the top @i{n} items in registers
16225: @itemize @bullet
16226: @item
16227: is better than keeping @i{n-1} items, if @i{x>=n} and @i{y>=n},
16228: due to fewer loads from and stores to the stack.
16229: @item is slower than keeping @i{n-1} items, if @i{x<>y} and @i{x<n} and
16230: @i{y<n}, due to additional moves between registers.
16231: @end itemize
16232: 
16233: @cindex -DUSE_TOS
16234: @cindex -DUSE_NO_TOS
16235: In particular, keeping one item in a register is never a disadvantage,
16236: if there are enough registers. Keeping two items in registers is a
16237: disadvantage for frequent words like @code{?branch}, constants,
16238: variables, literals and @code{i}. Therefore our generator only produces
16239: code that keeps zero or one items in registers. The generated C code
16240: covers both cases; the selection between these alternatives is made at
16241: C-compile time using the switch @code{-DUSE_TOS}. @code{TOS} in the C
16242: code for @code{+} is just a simple variable name in the one-item case,
16243: otherwise it is a macro that expands into @code{sp[0]}. Note that the
16244: GNU C compiler tries to keep simple variables like @code{TOS} in
16245: registers, and it usually succeeds, if there are enough registers.
16246: 
16247: @cindex -DUSE_FTOS
16248: @cindex -DUSE_NO_FTOS
16249: The primitive generator performs the TOS optimization for the
16250: floating-point stack, too (@code{-DUSE_FTOS}). For floating-point
16251: operations the benefit of this optimization is even larger:
16252: floating-point operations take quite long on most processors, but can be
16253: performed in parallel with other operations as long as their results are
16254: not used. If the FP-TOS is kept in a register, this works. If
16255: it is kept on the stack, i.e., in memory, the store into memory has to
16256: wait for the result of the floating-point operation, lengthening the
16257: execution time of the primitive considerably.
16258: 
16259: The TOS optimization makes the automatic generation of primitives a
16260: bit more complicated. Just replacing all occurrences of @code{sp[0]} by
16261: @code{TOS} is not sufficient. There are some special cases to
16262: consider:
16263: @itemize @bullet
16264: @item In the case of @code{dup ( w -- w w )} the generator must not
16265: eliminate the store to the original location of the item on the stack,
16266: if the TOS optimization is turned on.
16267: @item Primitives with stack effects of the form @code{--}
16268: @i{out1}...@i{outy} must store the TOS to the stack at the start.
16269: Likewise, primitives with the stack effect @i{in1}...@i{inx} @code{--}
16270: must load the TOS from the stack at the end. But for the null stack
16271: effect @code{--} no stores or loads should be generated.
16272: @end itemize
16273: 
16274: @node Produced code,  , TOS Optimization, Primitives
16275: @subsection Produced code
16276: @cindex primitives, assembly code listing
16277: 
16278: @cindex @file{engine.s}
16279: To see what assembly code is produced for the primitives on your machine
16280: with your compiler and your flag settings, type @code{make engine.s} and
16281: look at the resulting file @file{engine.s}.  Alternatively, you can also
16282: disassemble the code of primitives with @code{see} on some architectures.
16283: 
16284: @node  Performance,  , Primitives, Engine
16285: @section Performance
16286: @cindex performance of some Forth interpreters
16287: @cindex engine performance
16288: @cindex benchmarking Forth systems
16289: @cindex Gforth performance
16290: 
16291: On RISCs the Gforth engine is very close to optimal; i.e., it is usually
16292: impossible to write a significantly faster threaded-code engine.
16293: 
16294: On register-starved machines like the 386 architecture processors
16295: improvements are possible, because @code{gcc} does not utilize the
16296: registers as well as a human, even with explicit register declarations;
16297: e.g., Bernd Beuster wrote a Forth system fragment in assembly language
16298: and hand-tuned it for the 486; this system is 1.19 times faster on the
16299: Sieve benchmark on a 486DX2/66 than Gforth compiled with
16300: @code{gcc-2.6.3} with @code{-DFORCE_REG}.  The situation has improved
16301: with gcc-2.95 and gforth-0.4.9; now the most important virtual machine
16302: registers fit in real registers (and we can even afford to use the TOS
16303: optimization), resulting in a speedup of 1.14 on the sieve over the
16304: earlier results.  And dynamic superinstructions provide another speedup
16305: (but only around a factor 1.2 on the 486).
16306: 
16307: @cindex Win32Forth performance
16308: @cindex NT Forth performance
16309: @cindex eforth performance
16310: @cindex ThisForth performance
16311: @cindex PFE performance
16312: @cindex TILE performance
16313: The potential advantage of assembly language implementations is not
16314: necessarily realized in complete Forth systems: We compared Gforth-0.5.9
16315: (direct threaded, compiled with @code{gcc-2.95.1} and
16316: @code{-DFORCE_REG}) with Win32Forth 1.2093 (newer versions are
16317: reportedly much faster), LMI's NT Forth (Beta, May 1994) and Eforth
16318: (with and without peephole (aka pinhole) optimization of the threaded
16319: code); all these systems were written in assembly language. We also
16320: compared Gforth with three systems written in C: PFE-0.9.14 (compiled
16321: with @code{gcc-2.6.3} with the default configuration for Linux:
16322: @code{-O2 -fomit-frame-pointer -DUSE_REGS -DUNROLL_NEXT}), ThisForth
16323: Beta (compiled with @code{gcc-2.6.3 -O3 -fomit-frame-pointer}; ThisForth
16324: employs peephole optimization of the threaded code) and TILE (compiled
16325: with @code{make opt}). We benchmarked Gforth, PFE, ThisForth and TILE on
16326: a 486DX2/66 under Linux. Kenneth O'Heskin kindly provided the results
16327: for Win32Forth and NT Forth on a 486DX2/66 with similar memory
16328: performance under Windows NT. Marcel Hendrix ported Eforth to Linux,
16329: then extended it to run the benchmarks, added the peephole optimizer,
16330: ran the benchmarks and reported the results.
16331: 
16332: We used four small benchmarks: the ubiquitous Sieve; bubble-sorting and
16333: matrix multiplication come from the Stanford integer benchmarks and have
16334: been translated into Forth by Martin Fraeman; we used the versions
16335: included in the TILE Forth package, but with bigger data set sizes; and
16336: a recursive Fibonacci number computation for benchmarking calling
16337: performance. The following table shows the time taken for the benchmarks
16338: scaled by the time taken by Gforth (in other words, it shows the speedup
16339: factor that Gforth achieved over the other systems).
16340: 
16341: @example
16342: relative       Win32-    NT       eforth       This-      
16343: time     Gforth Forth Forth eforth  +opt   PFE Forth  TILE
16344: sieve      1.00  2.16  1.78   2.16  1.32  2.46  4.96 13.37
16345: bubble     1.00  1.93  2.07   2.18  1.29  2.21        5.70
16346: matmul     1.00  1.92  1.76   1.90  0.96  2.06        5.32
16347: fib        1.00  2.32  2.03   1.86  1.31  2.64  4.55  6.54
16348: @end example
16349: 
16350: You may be quite surprised by the good performance of Gforth when
16351: compared with systems written in assembly language. One important reason
16352: for the disappointing performance of these other systems is probably
16353: that they are not written optimally for the 486 (e.g., they use the
16354: @code{lods} instruction). In addition, Win32Forth uses a comfortable,
16355: but costly method for relocating the Forth image: like @code{cforth}, it
16356: computes the actual addresses at run time, resulting in two address
16357: computations per @code{NEXT} (@pxref{Image File Background}).
16358: 
16359: The speedup of Gforth over PFE, ThisForth and TILE can be easily
16360: explained with the self-imposed restriction of the latter systems to
16361: standard C, which makes efficient threading impossible (however, the
16362: measured implementation of PFE uses a GNU C extension: @pxref{Global Reg
16363: Vars, , Defining Global Register Variables, gcc.info, GNU C Manual}).
16364: Moreover, current C compilers have a hard time optimizing other aspects
16365: of the ThisForth and the TILE source.
16366: 
16367: The performance of Gforth on 386 architecture processors varies widely
16368: with the version of @code{gcc} used. E.g., @code{gcc-2.5.8} failed to
16369: allocate any of the virtual machine registers into real machine
16370: registers by itself and would not work correctly with explicit register
16371: declarations, giving a significantly slower engine (on a 486DX2/66
16372: running the Sieve) than the one measured above.
16373: 
16374: Note that there have been several releases of Win32Forth since the
16375: release presented here, so the results presented above may have little
16376: predictive value for the performance of Win32Forth today (results for
16377: the current release on an i486DX2/66 are welcome).
16378: 
16379: @cindex @file{Benchres}
16380: In
16381: @cite{@uref{http://www.complang.tuwien.ac.at/papers/ertl&maierhofer95.ps.gz,
16382: Translating Forth to Efficient C}} by M. Anton Ertl and Martin
16383: Maierhofer (presented at EuroForth '95), an indirect threaded version of
16384: Gforth is compared with Win32Forth, NT Forth, PFE, ThisForth, and
16385: several native code systems; that version of Gforth is slower on a 486
16386: than the version used here. You can find a newer version of these
16387: measurements at
16388: @uref{http://www.complang.tuwien.ac.at/forth/performance.html}. You can
16389: find numbers for Gforth on various machines in @file{Benchres}.
16390: 
16391: @c ******************************************************************
16392: @c @node Binding to System Library, Cross Compiler, Engine, Top
16393: @c @chapter Binding to System Library
16394: 
16395: @c ****************************************************************
16396: @node Cross Compiler, Bugs, Engine, Top
16397: @chapter Cross Compiler
16398: @cindex @file{cross.fs}
16399: @cindex cross-compiler
16400: @cindex metacompiler
16401: @cindex target compiler
16402: 
16403: The cross compiler is used to bootstrap a Forth kernel. Since Gforth is
16404: mostly written in Forth, including crucial parts like the outer
16405: interpreter and compiler, it needs compiled Forth code to get
16406: started. The cross compiler allows to create new images for other
16407: architectures, even running under another Forth system.
16408: 
16409: @menu
16410: * Using the Cross Compiler::    
16411: * How the Cross Compiler Works::  
16412: @end menu
16413: 
16414: @node Using the Cross Compiler, How the Cross Compiler Works, Cross Compiler, Cross Compiler
16415: @section Using the Cross Compiler
16416: 
16417: The cross compiler uses a language that resembles Forth, but isn't. The
16418: main difference is that you can execute Forth code after definition,
16419: while you usually can't execute the code compiled by cross, because the
16420: code you are compiling is typically for a different computer than the
16421: one you are compiling on.
16422: 
16423: @c anton: This chapter is somewhat different from waht I would expect: I
16424: @c would expect an explanation of the cross language and how to create an
16425: @c application image with it.  The section explains some aspects of
16426: @c creating a Gforth kernel.
16427: 
16428: The Makefile is already set up to allow you to create kernels for new
16429: architectures with a simple make command. The generic kernels using the
16430: GCC compiled virtual machine are created in the normal build process
16431: with @code{make}. To create a embedded Gforth executable for e.g. the
16432: 8086 processor (running on a DOS machine), type
16433: 
16434: @example
16435: make kernl-8086.fi
16436: @end example
16437: 
16438: This will use the machine description from the @file{arch/8086}
16439: directory to create a new kernel. A machine file may look like that:
16440: 
16441: @example
16442: \ Parameter for target systems                         06oct92py
16443: 
16444:     4 Constant cell             \ cell size in bytes
16445:     2 Constant cell<<           \ cell shift to bytes
16446:     5 Constant cell>bit         \ cell shift to bits
16447:     8 Constant bits/char        \ bits per character
16448:     8 Constant bits/byte        \ bits per byte [default: 8]
16449:     8 Constant float            \ bytes per float
16450:     8 Constant /maxalign        \ maximum alignment in bytes
16451: false Constant bigendian        \ byte order
16452: ( true=big, false=little )
16453: 
16454: include machpc.fs               \ feature list
16455: @end example
16456: 
16457: This part is obligatory for the cross compiler itself, the feature list
16458: is used by the kernel to conditionally compile some features in and out,
16459: depending on whether the target supports these features.
16460: 
16461: There are some optional features, if you define your own primitives,
16462: have an assembler, or need special, nonstandard preparation to make the
16463: boot process work. @code{asm-include} includes an assembler,
16464: @code{prims-include} includes primitives, and @code{>boot} prepares for
16465: booting.
16466: 
16467: @example
16468: : asm-include    ." Include assembler" cr
16469:   s" arch/8086/asm.fs" included ;
16470: 
16471: : prims-include  ." Include primitives" cr
16472:   s" arch/8086/prim.fs" included ;
16473: 
16474: : >boot          ." Prepare booting" cr
16475:   s" ' boot >body into-forth 1+ !" evaluate ;
16476: @end example
16477: 
16478: These words are used as sort of macro during the cross compilation in
16479: the file @file{kernel/main.fs}. Instead of using these macros, it would
16480: be possible --- but more complicated --- to write a new kernel project
16481: file, too.
16482: 
16483: @file{kernel/main.fs} expects the machine description file name on the
16484: stack; the cross compiler itself (@file{cross.fs}) assumes that either
16485: @code{mach-file} leaves a counted string on the stack, or
16486: @code{machine-file} leaves an address, count pair of the filename on the
16487: stack.
16488: 
16489: The feature list is typically controlled using @code{SetValue}, generic
16490: files that are used by several projects can use @code{DefaultValue}
16491: instead. Both functions work like @code{Value}, when the value isn't
16492: defined, but @code{SetValue} works like @code{to} if the value is
16493: defined, and @code{DefaultValue} doesn't set anything, if the value is
16494: defined.
16495: 
16496: @example
16497: \ generic mach file for pc gforth                       03sep97jaw
16498: 
16499: true DefaultValue NIL  \ relocating
16500: 
16501: >ENVIRON
16502: 
16503: true DefaultValue file          \ controls the presence of the
16504:                                 \ file access wordset
16505: true DefaultValue OS            \ flag to indicate a operating system
16506: 
16507: true DefaultValue prims         \ true: primitives are c-code
16508: 
16509: true DefaultValue floating      \ floating point wordset is present
16510: 
16511: true DefaultValue glocals       \ gforth locals are present
16512:                                 \ will be loaded
16513: true DefaultValue dcomps        \ double number comparisons
16514: 
16515: true DefaultValue hash          \ hashing primitives are loaded/present
16516: 
16517: true DefaultValue xconds        \ used together with glocals,
16518:                                 \ special conditionals supporting gforths'
16519:                                 \ local variables
16520: true DefaultValue header        \ save a header information
16521: 
16522: true DefaultValue backtrace     \ enables backtrace code
16523: 
16524: false DefaultValue ec
16525: false DefaultValue crlf
16526: 
16527: cell 2 = [IF] &32 [ELSE] &256 [THEN] KB DefaultValue kernel-size
16528: 
16529: &16 KB          DefaultValue stack-size
16530: &15 KB &512 +   DefaultValue fstack-size
16531: &15 KB          DefaultValue rstack-size
16532: &14 KB &512 +   DefaultValue lstack-size
16533: @end example
16534: 
16535: @node How the Cross Compiler Works,  , Using the Cross Compiler, Cross Compiler
16536: @section How the Cross Compiler Works
16537: 
16538: @node Bugs, Origin, Cross Compiler, Top
16539: @appendix Bugs
16540: @cindex bug reporting
16541: 
16542: Known bugs are described in the file @file{BUGS} in the Gforth distribution.
16543: 
16544: If you find a bug, please submit a bug report through
16545: @uref{https://savannah.gnu.org/bugs/?func=addbug&group=gforth}.
16546: 
16547: @itemize @bullet
16548: @item
16549: A program (or a sequence of keyboard commands) that reproduces the bug.
16550: @item
16551: A description of what you think constitutes the buggy behaviour.
16552: @item
16553: The Gforth version used (it is announced at the start of an
16554: interactive Gforth session).
16555: @item
16556: The machine and operating system (on Unix
16557: systems @code{uname -a} will report this information).
16558: @item
16559: The installation options (you can find the configure options at the
16560: start of @file{config.status}) and configuration (@code{configure}
16561: output or @file{config.cache}).
16562: @item
16563: A complete list of changes (if any) you (or your installer) have made to the
16564: Gforth sources.
16565: @end itemize
16566: 
16567: For a thorough guide on reporting bugs read @ref{Bug Reporting, , How
16568: to Report Bugs, gcc.info, GNU C Manual}.
16569: 
16570: 
16571: @node Origin, Forth-related information, Bugs, Top
16572: @appendix Authors and Ancestors of Gforth
16573: 
16574: @section Authors and Contributors
16575: @cindex authors of Gforth
16576: @cindex contributors to Gforth
16577: 
16578: The Gforth project was started in mid-1992 by Bernd Paysan and Anton
16579: Ertl. The third major author was Jens Wilke.  Neal Crook contributed a
16580: lot to the manual.  Assemblers and disassemblers were contributed by
16581: Andrew McKewan, Christian Pirker, Bernd Thallner, and Michal Revucky.
16582: Lennart Benschop (who was one of Gforth's first users, in mid-1993)
16583: and Stuart Ramsden inspired us with their continuous feedback. Lennart
16584: Benshop contributed @file{glosgen.fs}, while Stuart Ramsden has been
16585: working on automatic support for calling C libraries. Helpful comments
16586: also came from Paul Kleinrubatscher, Christian Pirker, Dirk Zoller,
16587: Marcel Hendrix, John Wavrik, Barrie Stott, Marc de Groot, Jorge
16588: Acerada, Bruce Hoyt, Robert Epprecht, Dennis Ruffer and David
16589: N. Williams. Since the release of Gforth-0.2.1 there were also helpful
16590: comments from many others; thank you all, sorry for not listing you
16591: here (but digging through my mailbox to extract your names is on my
16592: to-do list).
16593: 
16594: Gforth also owes a lot to the authors of the tools we used (GCC, CVS,
16595: and autoconf, among others), and to the creators of the Internet: Gforth
16596: was developed across the Internet, and its authors did not meet
16597: physically for the first 4 years of development.
16598: 
16599: @section Pedigree
16600: @cindex pedigree of Gforth
16601: 
16602: Gforth descends from bigFORTH (1993) and fig-Forth.  Of course, a
16603: significant part of the design of Gforth was prescribed by ANS Forth.
16604: 
16605: Bernd Paysan wrote bigFORTH, a descendent from TurboForth, an unreleased
16606: 32 bit native code version of VolksForth for the Atari ST, written
16607: mostly by Dietrich Weineck.
16608: 
16609: VolksForth was written by Klaus Schleisiek, Bernd Pennemann, Georg
16610: Rehfeld and Dietrich Weineck for the C64 (called UltraForth there) in
16611: the mid-80s and ported to the Atari ST in 1986.  It descends from fig-Forth.
16612: 
16613: @c Henry Laxen and Mike Perry wrote F83 as a model implementation of the
16614: @c Forth-83 standard. !! Pedigree? When?
16615: 
16616: A team led by Bill Ragsdale implemented fig-Forth on many processors in
16617: 1979. Robert Selzer and Bill Ragsdale developed the original
16618: implementation of fig-Forth for the 6502 based on microForth.
16619: 
16620: The principal architect of microForth was Dean Sanderson. microForth was
16621: FORTH, Inc.'s first off-the-shelf product. It was developed in 1976 for
16622: the 1802, and subsequently implemented on the 8080, the 6800 and the
16623: Z80.
16624: 
16625: All earlier Forth systems were custom-made, usually by Charles Moore,
16626: who discovered (as he puts it) Forth during the late 60s. The first full
16627: Forth existed in 1971.
16628: 
16629: A part of the information in this section comes from
16630: @cite{@uref{http://www.forth.com/resources/evolution/index.html,The
16631: Evolution of Forth}} by Elizabeth D. Rather, Donald R. Colburn and
16632: Charles H. Moore, presented at the HOPL-II conference and preprinted
16633: in SIGPLAN Notices 28(3), 1993.  You can find more historical and
16634: genealogical information about Forth there.  For a more general (and
16635: graphical) Forth family tree look see
16636: @cite{@uref{http://www.complang.tuwien.ac.at/forth/family-tree/},
16637: Forth Family Tree and Timeline}.
16638: 
16639: @c ------------------------------------------------------------------
16640: @node Forth-related information, Licenses, Origin, Top
16641: @appendix Other Forth-related information
16642: @cindex Forth-related information
16643: 
16644: @c anton: I threw most of this stuff out, because it can be found through
16645: @c the FAQ and the FAQ is more likely to be up-to-date.
16646: 
16647: @cindex comp.lang.forth
16648: @cindex frequently asked questions
16649: There is an active news group (comp.lang.forth) discussing Forth
16650: (including Gforth) and Forth-related issues. Its
16651: @uref{http://www.complang.tuwien.ac.at/forth/faq/faq-general-2.html,FAQs}
16652: (frequently asked questions and their answers) contains a lot of
16653: information on Forth.  You should read it before posting to
16654: comp.lang.forth.
16655: 
16656: The ANS Forth standard is most usable in its
16657: @uref{http://www.taygeta.com/forth/dpans.html, HTML form}.
16658: 
16659: @c ---------------------------------------------------
16660: @node  Licenses, Word Index, Forth-related information, Top
16661: @appendix Licenses
16662: 
16663: @menu
16664: * GNU Free Documentation License::  License for copying this manual.
16665: * Copying::                     GPL (for copying this software).
16666: @end menu
16667: 
16668: @node GNU Free Documentation License, Copying, Licenses, Licenses
16669: @appendixsec GNU Free Documentation License
16670: @include fdl.texi
16671: 
16672: @node Copying,  , GNU Free Documentation License, Licenses
16673: @appendixsec GNU GENERAL PUBLIC LICENSE
16674: @include gpl.texi
16675: 
16676: 
16677: 
16678: @c ------------------------------------------------------------------
16679: @node Word Index, Concept Index, Licenses, Top
16680: @unnumbered Word Index
16681: 
16682: This index is a list of Forth words that have ``glossary'' entries
16683: within this manual. Each word is listed with its stack effect and
16684: wordset.
16685: 
16686: @printindex fn
16687: 
16688: @c anton: the name index seems superfluous given the word and concept indices.
16689: 
16690: @c @node Name Index, Concept Index, Word Index, Top
16691: @c @unnumbered Name Index
16692: 
16693: @c This index is a list of Forth words that have ``glossary'' entries
16694: @c within this manual.
16695: 
16696: @c @printindex ky
16697: 
16698: @c -------------------------------------------------------
16699: @node Concept Index,  , Word Index, Top
16700: @unnumbered Concept and Word Index
16701: 
16702: Not all entries listed in this index are present verbatim in the
16703: text. This index also duplicates, in abbreviated form, all of the words
16704: listed in the Word Index (only the names are listed for the words here).
16705: 
16706: @printindex cp
16707: 
16708: @bye
16709: 
16710: 
16711: 

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