File:  [gforth] / gforth / doc / gforth.ds
Revision 1.213: download - view: text, annotated - select for diffs
Sun Mar 7 21:19:22 2010 UTC (14 years, 1 month ago) by anton
Branches: MAIN
CVS tags: HEAD
modified CASE example (suggested by Terrence Brannon in
  <ccc961b91003071130m76be6d4fi999ef0e437d3d4f1@mail.gmail.com>)

    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 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: * Code and ;code::              
  422: * Common Assembler::            Assembler Syntax
  423: * Common Disassembler::         
  424: * 386 Assembler::               Deviations and special cases
  425: * Alpha Assembler::             Deviations and special cases
  426: * MIPS assembler::              Deviations and special cases
  427: * PowerPC assembler::           Deviations and special cases
  428: * ARM Assembler::               Deviations and special cases
  429: * Other assemblers::            How to write them
  430: 
  431: Tools
  432: 
  433: * ANS Report::                  Report the words used, sorted by wordset.
  434: * Stack depth changes::         Where does this stack item come from?
  435: 
  436: ANS conformance
  437: 
  438: * The Core Words::              
  439: * The optional Block word set::  
  440: * The optional Double Number word set::  
  441: * The optional Exception word set::  
  442: * The optional Facility word set::  
  443: * The optional File-Access word set::  
  444: * The optional Floating-Point word set::  
  445: * The optional Locals word set::  
  446: * The optional Memory-Allocation word set::  
  447: * The optional Programming-Tools word set::  
  448: * The optional Search-Order word set::  
  449: 
  450: The Core Words
  451: 
  452: * core-idef::                   Implementation Defined Options                   
  453: * core-ambcond::                Ambiguous Conditions                
  454: * core-other::                  Other System Documentation                  
  455: 
  456: The optional Block word set
  457: 
  458: * block-idef::                  Implementation Defined Options
  459: * block-ambcond::               Ambiguous Conditions               
  460: * block-other::                 Other System Documentation                 
  461: 
  462: The optional Double Number word set
  463: 
  464: * double-ambcond::              Ambiguous Conditions              
  465: 
  466: The optional Exception word set
  467: 
  468: * exception-idef::              Implementation Defined Options              
  469: 
  470: The optional Facility word set
  471: 
  472: * facility-idef::               Implementation Defined Options               
  473: * facility-ambcond::            Ambiguous Conditions            
  474: 
  475: The optional File-Access word set
  476: 
  477: * file-idef::                   Implementation Defined Options
  478: * file-ambcond::                Ambiguous Conditions                
  479: 
  480: The optional Floating-Point word set
  481: 
  482: * floating-idef::               Implementation Defined Options
  483: * floating-ambcond::            Ambiguous Conditions            
  484: 
  485: The optional Locals word set
  486: 
  487: * locals-idef::                 Implementation Defined Options                 
  488: * locals-ambcond::              Ambiguous Conditions              
  489: 
  490: The optional Memory-Allocation word set
  491: 
  492: * memory-idef::                 Implementation Defined Options                 
  493: 
  494: The optional Programming-Tools word set
  495: 
  496: * programming-idef::            Implementation Defined Options            
  497: * programming-ambcond::         Ambiguous Conditions         
  498: 
  499: The optional Search-Order word set
  500: 
  501: * search-idef::                 Implementation Defined Options                 
  502: * search-ambcond::              Ambiguous Conditions              
  503: 
  504: Emacs and Gforth
  505: 
  506: * Installing gforth.el::        Making Emacs aware of Forth.
  507: * Emacs Tags::                  Viewing the source of a word in Emacs.
  508: * Hilighting::                  Making Forth code look prettier.
  509: * Auto-Indentation::            Customizing auto-indentation.
  510: * Blocks Files::                Reading and writing blocks files.
  511: 
  512: Image Files
  513: 
  514: * Image Licensing Issues::      Distribution terms for images.
  515: * Image File Background::       Why have image files?
  516: * Non-Relocatable Image Files::  don't always work.
  517: * Data-Relocatable Image Files::  are better.
  518: * Fully Relocatable Image Files::  better yet.
  519: * Stack and Dictionary Sizes::  Setting the default sizes for an image.
  520: * Running Image Files::         @code{gforth -i @i{file}} or @i{file}.
  521: * Modifying the Startup Sequence::  and turnkey applications.
  522: 
  523: Fully Relocatable Image Files
  524: 
  525: * gforthmi::                    The normal way
  526: * cross.fs::                    The hard way
  527: 
  528: Engine
  529: 
  530: * Portability::                 
  531: * Threading::                   
  532: * Primitives::                  
  533: * Performance::                 
  534: 
  535: Threading
  536: 
  537: * Scheduling::                  
  538: * Direct or Indirect Threaded?::  
  539: * Dynamic Superinstructions::   
  540: * DOES>::                       
  541: 
  542: Primitives
  543: 
  544: * Automatic Generation::        
  545: * TOS Optimization::            
  546: * Produced code::               
  547: 
  548: Cross Compiler
  549: 
  550: * Using the Cross Compiler::    
  551: * How the Cross Compiler Works::  
  552: 
  553: Licenses
  554: 
  555: * GNU Free Documentation License::  License for copying this manual.
  556: * Copying::                     GPL (for copying this software).
  557: 
  558: @end detailmenu
  559: @end menu
  560: 
  561: @c ----------------------------------------------------------
  562: @iftex
  563: @unnumbered Preface
  564: @cindex Preface
  565: This manual documents Gforth. Some introductory material is provided for
  566: readers who are unfamiliar with Forth or who are migrating to Gforth
  567: from other Forth compilers. However, this manual is primarily a
  568: reference manual.
  569: @end iftex
  570: 
  571: @comment TODO much more blurb here.
  572: 
  573: @c ******************************************************************
  574: @node Goals, Gforth Environment, Top, Top
  575: @comment node-name,     next,           previous, up
  576: @chapter Goals of Gforth
  577: @cindex goals of the Gforth project
  578: The goal of the Gforth Project is to develop a standard model for
  579: ANS Forth. This can be split into several subgoals:
  580: 
  581: @itemize @bullet
  582: @item
  583: Gforth should conform to the ANS Forth Standard.
  584: @item
  585: It should be a model, i.e. it should define all the
  586: implementation-dependent things.
  587: @item
  588: It should become standard, i.e. widely accepted and used. This goal
  589: is the most difficult one.
  590: @end itemize
  591: 
  592: To achieve these goals Gforth should be
  593: @itemize @bullet
  594: @item
  595: Similar to previous models (fig-Forth, F83)
  596: @item
  597: Powerful. It should provide for all the things that are considered
  598: necessary today and even some that are not yet considered necessary.
  599: @item
  600: Efficient. It should not get the reputation of being exceptionally
  601: slow.
  602: @item
  603: Free.
  604: @item
  605: Available on many machines/easy to port.
  606: @end itemize
  607: 
  608: Have we achieved these goals? Gforth conforms to the ANS Forth
  609: standard. It may be considered a model, but we have not yet documented
  610: which parts of the model are stable and which parts we are likely to
  611: change. It certainly has not yet become a de facto standard, but it
  612: appears to be quite popular. It has some similarities to and some
  613: differences from previous models. It has some powerful features, but not
  614: yet everything that we envisioned. We certainly have achieved our
  615: execution speed goals (@pxref{Performance})@footnote{However, in 1998
  616: the bar was raised when the major commercial Forth vendors switched to
  617: native code compilers.}.  It is free and available on many machines.
  618: 
  619: @c ******************************************************************
  620: @node Gforth Environment, Tutorial, Goals, Top
  621: @chapter Gforth Environment
  622: @cindex Gforth environment
  623: 
  624: Note: ultimately, the Gforth man page will be auto-generated from the
  625: material in this chapter.
  626: 
  627: @menu
  628: * Invoking Gforth::             Getting in
  629: * Leaving Gforth::              Getting out
  630: * Command-line editing::        
  631: * Environment variables::       that affect how Gforth starts up
  632: * Gforth Files::                What gets installed and where
  633: * Gforth in pipes::             
  634: * Startup speed::               When 14ms is not fast enough ...
  635: @end menu
  636: 
  637: For related information about the creation of images see @ref{Image Files}.
  638: 
  639: @comment ----------------------------------------------
  640: @node Invoking Gforth, Leaving Gforth, Gforth Environment, Gforth Environment
  641: @section Invoking Gforth
  642: @cindex invoking Gforth
  643: @cindex running Gforth
  644: @cindex command-line options
  645: @cindex options on the command line
  646: @cindex flags on the command line
  647: 
  648: Gforth is made up of two parts; an executable ``engine'' (named
  649: @command{gforth} or @command{gforth-fast}) and an image file. To start it, you
  650: will usually just say @code{gforth} -- this automatically loads the
  651: default image file @file{gforth.fi}. In many other cases the default
  652: Gforth image will be invoked like this:
  653: @example
  654: gforth [file | -e forth-code] ...
  655: @end example
  656: @noindent
  657: This interprets the contents of the files and the Forth code in the order they
  658: are given.
  659: 
  660: In addition to the @command{gforth} engine, there is also an engine
  661: called @command{gforth-fast}, which is faster, but gives less
  662: informative error messages (@pxref{Error messages}) and may catch some
  663: errors (in particular, stack underflows and integer division errors)
  664: later or not at all.  You should use it for debugged,
  665: performance-critical programs.
  666: 
  667: Moreover, there is an engine called @command{gforth-itc}, which is
  668: useful in some backwards-compatibility situations (@pxref{Direct or
  669: Indirect Threaded?}).
  670: 
  671: In general, the command line looks like this:
  672: 
  673: @example
  674: gforth[-fast] [engine options] [image options]
  675: @end example
  676: 
  677: The engine options must come before the rest of the command
  678: line. They are:
  679: 
  680: @table @code
  681: @cindex -i, command-line option
  682: @cindex --image-file, command-line option
  683: @item --image-file @i{file}
  684: @itemx -i @i{file}
  685: Loads the Forth image @i{file} instead of the default
  686: @file{gforth.fi} (@pxref{Image Files}).
  687: 
  688: @cindex --appl-image, command-line option
  689: @item --appl-image @i{file}
  690: Loads the image @i{file} and leaves all further command-line arguments
  691: to the image (instead of processing them as engine options).  This is
  692: useful for building executable application images on Unix, built with
  693: @code{gforthmi --application ...}.
  694: 
  695: @cindex --path, command-line option
  696: @cindex -p, command-line option
  697: @item --path @i{path}
  698: @itemx -p @i{path}
  699: Uses @i{path} for searching the image file and Forth source code files
  700: instead of the default in the environment variable @code{GFORTHPATH} or
  701: the path specified at installation time (e.g.,
  702: @file{/usr/local/share/gforth/0.2.0:.}). A path is given as a list of
  703: directories, separated by @samp{:} (on Unix) or @samp{;} (on other OSs).
  704: 
  705: @cindex --dictionary-size, command-line option
  706: @cindex -m, command-line option
  707: @cindex @i{size} parameters for command-line options
  708: @cindex size of the dictionary and the stacks
  709: @item --dictionary-size @i{size}
  710: @itemx -m @i{size}
  711: Allocate @i{size} space for the Forth dictionary space instead of
  712: using the default specified in the image (typically 256K). The
  713: @i{size} specification for this and subsequent options consists of
  714: an integer and a unit (e.g.,
  715: @code{4M}). The unit can be one of @code{b} (bytes), @code{e} (element
  716: size, in this case Cells), @code{k} (kilobytes), @code{M} (Megabytes),
  717: @code{G} (Gigabytes), and @code{T} (Terabytes). If no unit is specified,
  718: @code{e} is used.
  719: 
  720: @cindex --data-stack-size, command-line option
  721: @cindex -d, command-line option
  722: @item --data-stack-size @i{size}
  723: @itemx -d @i{size}
  724: Allocate @i{size} space for the data stack instead of using the
  725: default specified in the image (typically 16K).
  726: 
  727: @cindex --return-stack-size, command-line option
  728: @cindex -r, command-line option
  729: @item --return-stack-size @i{size}
  730: @itemx -r @i{size}
  731: Allocate @i{size} space for the return stack instead of using the
  732: default specified in the image (typically 15K).
  733: 
  734: @cindex --fp-stack-size, command-line option
  735: @cindex -f, command-line option
  736: @item --fp-stack-size @i{size}
  737: @itemx -f @i{size}
  738: Allocate @i{size} space for the floating point stack instead of
  739: using the default specified in the image (typically 15.5K). In this case
  740: the unit specifier @code{e} refers to floating point numbers.
  741: 
  742: @cindex --locals-stack-size, command-line option
  743: @cindex -l, command-line option
  744: @item --locals-stack-size @i{size}
  745: @itemx -l @i{size}
  746: Allocate @i{size} space for the locals stack instead of using the
  747: default specified in the image (typically 14.5K).
  748: 
  749: @cindex --vm-commit, command-line option
  750: @cindex overcommit memory for dictionary and stacks
  751: @cindex memory overcommit for dictionary and stacks
  752: @item --vm-commit
  753: Normally, Gforth tries to start up even if there is not enough virtual
  754: memory for the dictionary and the stacks (using @code{MAP_NORESERVE}
  755: on OSs that support it); so you can ask for a really big dictionary
  756: and/or stacks, and as long as you don't use more virtual memory than
  757: is available, everything will be fine (but if you use more, processes
  758: get killed).  With this option you just use the default allocation
  759: policy of the OS; for OSs that don't overcommit (e.g., Solaris), this
  760: means that you cannot and should not ask for as big dictionary and
  761: stacks, but once Gforth successfully starts up, out-of-memory won't
  762: kill it.
  763: 
  764: @cindex -h, command-line option
  765: @cindex --help, command-line option
  766: @item --help
  767: @itemx -h
  768: Print a message about the command-line options
  769: 
  770: @cindex -v, command-line option
  771: @cindex --version, command-line option
  772: @item --version
  773: @itemx -v
  774: Print version and exit
  775: 
  776: @cindex --debug, command-line option
  777: @item --debug
  778: Print some information useful for debugging on startup.
  779: 
  780: @cindex --offset-image, command-line option
  781: @item --offset-image
  782: Start the dictionary at a slightly different position than would be used
  783: otherwise (useful for creating data-relocatable images,
  784: @pxref{Data-Relocatable Image Files}).
  785: 
  786: @cindex --no-offset-im, command-line option
  787: @item --no-offset-im
  788: Start the dictionary at the normal position.
  789: 
  790: @cindex --clear-dictionary, command-line option
  791: @item --clear-dictionary
  792: Initialize all bytes in the dictionary to 0 before loading the image
  793: (@pxref{Data-Relocatable Image Files}).
  794: 
  795: @cindex --die-on-signal, command-line-option
  796: @item --die-on-signal
  797: Normally Gforth handles most signals (e.g., the user interrupt SIGINT,
  798: or the segmentation violation SIGSEGV) by translating it into a Forth
  799: @code{THROW}. With this option, Gforth exits if it receives such a
  800: signal. This option is useful when the engine and/or the image might be
  801: severely broken (such that it causes another signal before recovering
  802: from the first); this option avoids endless loops in such cases.
  803: 
  804: @cindex --no-dynamic, command-line option
  805: @cindex --dynamic, command-line option
  806: @item --no-dynamic
  807: @item --dynamic
  808: Disable or enable dynamic superinstructions with replication
  809: (@pxref{Dynamic Superinstructions}).
  810: 
  811: @cindex --no-super, command-line option
  812: @item --no-super
  813: Disable dynamic superinstructions, use just dynamic replication; this is
  814: useful if you want to patch threaded code (@pxref{Dynamic
  815: Superinstructions}).
  816: 
  817: @cindex --ss-number, command-line option
  818: @item --ss-number=@var{N}
  819: Use only the first @var{N} static superinstructions compiled into the
  820: engine (default: use them all; note that only @code{gforth-fast} has
  821: any).  This option is useful for measuring the performance impact of
  822: static superinstructions.
  823: 
  824: @cindex --ss-min-..., command-line options
  825: @item --ss-min-codesize
  826: @item --ss-min-ls
  827: @item --ss-min-lsu
  828: @item --ss-min-nexts
  829: Use specified metric for determining the cost of a primitive or static
  830: superinstruction for static superinstruction selection.  @code{Codesize}
  831: is the native code size of the primive or static superinstruction,
  832: @code{ls} is the number of loads and stores, @code{lsu} is the number of
  833: loads, stores, and updates, and @code{nexts} is the number of dispatches
  834: (not taking dynamic superinstructions into account), i.e. every
  835: primitive or static superinstruction has cost 1. Default:
  836: @code{codesize} if you use dynamic code generation, otherwise
  837: @code{nexts}.
  838: 
  839: @cindex --ss-greedy, command-line option
  840: @item --ss-greedy
  841: This option is useful for measuring the performance impact of static
  842: superinstructions.  By default, an optimal shortest-path algorithm is
  843: used for selecting static superinstructions.  With @option{--ss-greedy}
  844: this algorithm is modified to assume that anything after the static
  845: superinstruction currently under consideration is not combined into
  846: static superinstructions.  With @option{--ss-min-nexts} this produces
  847: the same result as a greedy algorithm that always selects the longest
  848: superinstruction available at the moment.  E.g., if there are
  849: superinstructions AB and BCD, then for the sequence A B C D the optimal
  850: algorithm will select A BCD and the greedy algorithm will select AB C D.
  851: 
  852: @cindex --print-metrics, command-line option
  853: @item --print-metrics
  854: Prints some metrics used during static superinstruction selection:
  855: @code{code size} is the actual size of the dynamically generated code.
  856: @code{Metric codesize} is the sum of the codesize metrics as seen by
  857: static superinstruction selection; there is a difference from @code{code
  858: size}, because not all primitives and static superinstructions are
  859: compiled into dynamically generated code, and because of markers.  The
  860: other metrics correspond to the @option{ss-min-...} options.  This
  861: option is useful for evaluating the effects of the @option{--ss-...}
  862: options.
  863: 
  864: @end table
  865: 
  866: @cindex loading files at startup
  867: @cindex executing code on startup
  868: @cindex batch processing with Gforth
  869: As explained above, the image-specific command-line arguments for the
  870: default image @file{gforth.fi} consist of a sequence of filenames and
  871: @code{-e @var{forth-code}} options that are interpreted in the sequence
  872: in which they are given. The @code{-e @var{forth-code}} or
  873: @code{--evaluate @var{forth-code}} option evaluates the Forth code. This
  874: option takes only one argument; if you want to evaluate more Forth
  875: words, you have to quote them or use @code{-e} several times. To exit
  876: after processing the command line (instead of entering interactive mode)
  877: append @code{-e bye} to the command line.  You can also process the
  878: command-line arguments with a Forth program (@pxref{OS command line
  879: arguments}).
  880: 
  881: @cindex versions, invoking other versions of Gforth
  882: If you have several versions of Gforth installed, @code{gforth} will
  883: invoke the version that was installed last. @code{gforth-@i{version}}
  884: invokes a specific version. If your environment contains the variable
  885: @code{GFORTHPATH}, you may want to override it by using the
  886: @code{--path} option.
  887: 
  888: Not yet implemented:
  889: On startup the system first executes the system initialization file
  890: (unless the option @code{--no-init-file} is given; note that the system
  891: resulting from using this option may not be ANS Forth conformant). Then
  892: the user initialization file @file{.gforth.fs} is executed, unless the
  893: option @code{--no-rc} is given; this file is searched for in @file{.},
  894: then in @file{~}, then in the normal path (see above).
  895: 
  896: 
  897: 
  898: @comment ----------------------------------------------
  899: @node Leaving Gforth, Command-line editing, Invoking Gforth, Gforth Environment
  900: @section Leaving Gforth
  901: @cindex Gforth - leaving
  902: @cindex leaving Gforth
  903: 
  904: You can leave Gforth by typing @code{bye} or @kbd{Ctrl-d} (at the start
  905: of a line) or (if you invoked Gforth with the @code{--die-on-signal}
  906: option) @kbd{Ctrl-c}. When you leave Gforth, all of your definitions and
  907: data are discarded.  For ways of saving the state of the system before
  908: leaving Gforth see @ref{Image Files}.
  909: 
  910: doc-bye
  911: 
  912: 
  913: @comment ----------------------------------------------
  914: @node Command-line editing, Environment variables, Leaving Gforth, Gforth Environment
  915: @section Command-line editing
  916: @cindex command-line editing
  917: 
  918: Gforth maintains a history file that records every line that you type to
  919: the text interpreter. This file is preserved between sessions, and is
  920: used to provide a command-line recall facility; if you type @kbd{Ctrl-P}
  921: repeatedly you can recall successively older commands from this (or
  922: previous) session(s). The full list of command-line editing facilities is:
  923: 
  924: @itemize @bullet
  925: @item
  926: @kbd{Ctrl-p} (``previous'') (or up-arrow) to recall successively older
  927: commands from the history buffer.
  928: @item
  929: @kbd{Ctrl-n} (``next'') (or down-arrow) to recall successively newer commands
  930: from the history buffer.
  931: @item
  932: @kbd{Ctrl-f} (or right-arrow) to move the cursor right, non-destructively.
  933: @item
  934: @kbd{Ctrl-b} (or left-arrow) to move the cursor left, non-destructively.
  935: @item
  936: @kbd{Ctrl-h} (backspace) to delete the character to the left of the cursor,
  937: closing up the line.
  938: @item
  939: @kbd{Ctrl-k} to delete (``kill'') from the cursor to the end of the line.
  940: @item
  941: @kbd{Ctrl-a} to move the cursor to the start of the line.
  942: @item
  943: @kbd{Ctrl-e} to move the cursor to the end of the line.
  944: @item
  945: @key{RET} (@kbd{Ctrl-m}) or @key{LFD} (@kbd{Ctrl-j}) to submit the current
  946: line.
  947: @item
  948: @key{TAB} to step through all possible full-word completions of the word
  949: currently being typed.
  950: @item
  951: @kbd{Ctrl-d} on an empty line line to terminate Gforth (gracefully,
  952: using @code{bye}). 
  953: @item
  954: @kbd{Ctrl-x} (or @code{Ctrl-d} on a non-empty line) to delete the
  955: character under the cursor.
  956: @end itemize
  957: 
  958: When editing, displayable characters are inserted to the left of the
  959: cursor position; the line is always in ``insert'' (as opposed to
  960: ``overstrike'') mode.
  961: 
  962: @cindex history file
  963: @cindex @file{.gforth-history}
  964: On Unix systems, the history file is @file{~/.gforth-history} by
  965: default@footnote{i.e. it is stored in the user's home directory.}. You
  966: can find out the name and location of your history file using:
  967: 
  968: @example 
  969: history-file type \ Unix-class systems
  970: 
  971: history-file type \ Other systems
  972: history-dir  type
  973: @end example
  974: 
  975: If you enter long definitions by hand, you can use a text editor to
  976: paste them out of the history file into a Forth source file for reuse at
  977: a later time.
  978: 
  979: Gforth never trims the size of the history file, so you should do this
  980: periodically, if necessary.
  981: 
  982: @comment this is all defined in history.fs
  983: @comment NAC TODO the ctrl-D behaviour can either do a bye or a beep.. how is that option
  984: @comment chosen?
  985: 
  986: 
  987: @comment ----------------------------------------------
  988: @node Environment variables, Gforth Files, Command-line editing, Gforth Environment
  989: @section Environment variables
  990: @cindex environment variables
  991: 
  992: Gforth uses these environment variables:
  993: 
  994: @itemize @bullet
  995: @item
  996: @cindex @code{GFORTHHIST} -- environment variable
  997: @code{GFORTHHIST} -- (Unix systems only) specifies the directory in which to
  998: open/create the history file, @file{.gforth-history}. Default:
  999: @code{$HOME}.
 1000: 
 1001: @item
 1002: @cindex @code{GFORTHPATH} -- environment variable
 1003: @code{GFORTHPATH} -- specifies the path used when searching for the gforth image file and
 1004: for Forth source-code files.
 1005: 
 1006: @item
 1007: @cindex @code{LANG} -- environment variable
 1008: @code{LANG} -- see @code{LC_CTYPE}
 1009: 
 1010: @item
 1011: @cindex @code{LC_ALL} -- environment variable
 1012: @code{LC_ALL} -- see @code{LC_CTYPE}
 1013: 
 1014: @item
 1015: @cindex @code{LC_CTYPE} -- environment variable
 1016: @code{LC_CTYPE} -- If this variable contains ``UTF-8'' on Gforth
 1017: startup, Gforth uses the UTF-8 encoding for strings internally and
 1018: expects its input and produces its output in UTF-8 encoding, otherwise
 1019: the encoding is 8bit (see @pxref{Xchars and Unicode}).  If this
 1020: environment variable is unset, Gforth looks in @code{LC_ALL}, and if
 1021: that is unset, in @code{LANG}.
 1022: 
 1023: @item
 1024: @cindex @code{GFORTHSYSTEMPREFIX} -- environment variable
 1025: 
 1026: @code{GFORTHSYSTEMPREFIX} -- specifies what to prepend to the argument
 1027: of @code{system} before passing it to C's @code{system()}.  Default:
 1028: @code{"./$COMSPEC /c "} on Windows, @code{""} on other OSs.  The prefix
 1029: and the command are directly concatenated, so if a space between them is
 1030: necessary, append it to the prefix.
 1031: 
 1032: @item
 1033: @cindex @code{GFORTH} -- environment variable
 1034: @code{GFORTH} -- used by @file{gforthmi}, @xref{gforthmi}.
 1035: 
 1036: @item
 1037: @cindex @code{GFORTHD} -- environment variable
 1038: @code{GFORTHD} -- used by @file{gforthmi}, @xref{gforthmi}.
 1039: 
 1040: @item
 1041: @cindex @code{TMP}, @code{TEMP} - environment variable
 1042: @code{TMP}, @code{TEMP} - (non-Unix systems only) used as a potential
 1043: location for the history file.
 1044: @end itemize
 1045: 
 1046: @comment also POSIXELY_CORRECT LINES COLUMNS HOME but no interest in
 1047: @comment mentioning these.
 1048: 
 1049: All the Gforth environment variables default to sensible values if they
 1050: are not set.
 1051: 
 1052: 
 1053: @comment ----------------------------------------------
 1054: @node Gforth Files, Gforth in pipes, Environment variables, Gforth Environment
 1055: @section Gforth files
 1056: @cindex Gforth files
 1057: 
 1058: When you install Gforth on a Unix system, it installs files in these
 1059: locations by default:
 1060: 
 1061: @itemize @bullet
 1062: @item
 1063: @file{/usr/local/bin/gforth}
 1064: @item
 1065: @file{/usr/local/bin/gforthmi}
 1066: @item
 1067: @file{/usr/local/man/man1/gforth.1} - man page.
 1068: @item
 1069: @file{/usr/local/info} - the Info version of this manual.
 1070: @item
 1071: @file{/usr/local/lib/gforth/<version>/...} - Gforth @file{.fi} files.
 1072: @item
 1073: @file{/usr/local/share/gforth/<version>/TAGS} - Emacs TAGS file.
 1074: @item
 1075: @file{/usr/local/share/gforth/<version>/...} - Gforth source files.
 1076: @item
 1077: @file{.../emacs/site-lisp/gforth.el} - Emacs gforth mode.
 1078: @end itemize
 1079: 
 1080: You can select different places for installation by using
 1081: @code{configure} options (listed with @code{configure --help}).
 1082: 
 1083: @comment ----------------------------------------------
 1084: @node Gforth in pipes, Startup speed, Gforth Files, Gforth Environment
 1085: @section Gforth in pipes
 1086: @cindex pipes, Gforth as part of
 1087: 
 1088: Gforth can be used in pipes created elsewhere (described here).  It can
 1089: also create pipes on its own (@pxref{Pipes}).
 1090: 
 1091: @cindex input from pipes
 1092: If you pipe into Gforth, your program should read with @code{read-file}
 1093: or @code{read-line} from @code{stdin} (@pxref{General files}).
 1094: @code{Key} does not recognize the end of input.  Words like
 1095: @code{accept} echo the input and are therefore usually not useful for
 1096: reading from a pipe.  You have to invoke the Forth program with an OS
 1097: command-line option, as you have no chance to use the Forth command line
 1098: (the text interpreter would try to interpret the pipe input).
 1099: 
 1100: @cindex output in pipes
 1101: You can output to a pipe with @code{type}, @code{emit}, @code{cr} etc.
 1102: 
 1103: @cindex silent exiting from Gforth
 1104: When you write to a pipe that has been closed at the other end, Gforth
 1105: receives a SIGPIPE signal (``pipe broken'').  Gforth translates this
 1106: into the exception @code{broken-pipe-error}.  If your application does
 1107: not catch that exception, the system catches it and exits, usually
 1108: silently (unless you were working on the Forth command line; then it
 1109: prints an error message and exits).  This is usually the desired
 1110: behaviour.
 1111: 
 1112: If you do not like this behaviour, you have to catch the exception
 1113: yourself, and react to it.
 1114: 
 1115: Here's an example of an invocation of Gforth that is usable in a pipe:
 1116: 
 1117: @example
 1118: gforth -e ": foo begin pad dup 10 stdin read-file throw dup while \
 1119:  type repeat ; foo bye"
 1120: @end example
 1121: 
 1122: This example just copies the input verbatim to the output.  A very
 1123: simple pipe containing this example looks like this:
 1124: 
 1125: @example
 1126: cat startup.fs |
 1127: gforth -e ": foo begin pad dup 80 stdin read-file throw dup while \
 1128:  type repeat ; foo bye"|
 1129: head
 1130: @end example
 1131: 
 1132: @cindex stderr and pipes
 1133: Pipes involving Gforth's @code{stderr} output do not work.
 1134: 
 1135: @comment ----------------------------------------------
 1136: @node Startup speed,  , Gforth in pipes, Gforth Environment
 1137: @section Startup speed
 1138: @cindex Startup speed
 1139: @cindex speed, startup
 1140: 
 1141: If Gforth is used for CGI scripts or in shell scripts, its startup
 1142: speed may become a problem.  On a 3GHz Core 2 Duo E8400 under 64-bit
 1143: Linux 2.6.27.8 with libc-2.7, @code{gforth-fast -e bye} takes 13.1ms
 1144: user and 1.2ms system time (@code{gforth -e bye} is faster on startup
 1145: with about 3.4ms user time and 1.2ms system time, because it subsumes
 1146: some of the options discussed below).
 1147: 
 1148: If startup speed is a problem, you may consider the following ways to
 1149: improve it; or you may consider ways to reduce the number of startups
 1150: (for example, by using Fast-CGI).  Note that the first steps below
 1151: improve the startup time at the cost of run-time (including
 1152: compile-time), so whether they are profitable depends on the balance
 1153: of these times in your application.
 1154: 
 1155: An easy step that influences Gforth startup speed is the use of a
 1156: number of options that increase run-time, but decrease image-loading
 1157: time.
 1158: 
 1159: The first of these that you should try is @code{--ss-number=0
 1160: --ss-states=1} because this option buys relatively little run-time
 1161: speedup and costs quite a bit of time at startup.  @code{gforth-fast
 1162: --ss-number=0 --ss-states=1 -e bye} takes about 2.8ms user and 1.5ms
 1163: system time.
 1164: 
 1165: The next option is @code{--no-dynamic} which has a substantial impact
 1166: on run-time (about a factor of 2 on several platforms), but still
 1167: makes startup speed a little faster: @code{gforth-fast --ss-number=0
 1168: --ss-states=1 --no-dynamic -e bye} consumes about 2.6ms user and 1.2ms
 1169: system time.
 1170: 
 1171: The next step to improve startup speed is to use a data-relocatable
 1172: image (@pxref{Data-Relocatable Image Files}).  This avoids the
 1173: relocation cost for the code in the image (but not for the data).
 1174: Note that the image is then specific to the particular binary you are
 1175: using (i.e., whether it is @code{gforth}, @code{gforth-fast}, and even
 1176: the particular build).  You create the data-relocatable image that
 1177: works with @code{./gforth-fast} with @code{GFORTHD="./gforth-fast
 1178: --no-dynamic" gforthmi gforthdr.fi} (the @code{--no-dynamic} is
 1179: required here or the image will not work).  And you run it with
 1180: @code{gforth-fast -i gforthdr.fi ... -e bye} (the flags discussed
 1181: above don't matter here, because they only come into play on
 1182: relocatable code).  @code{gforth-fast -i gforthdr.fi -e bye} takes
 1183: about 1.1ms user and 1.2ms system time.
 1184: 
 1185: One step further is to avoid all relocation cost and part of the
 1186: copy-on-write cost through using a non-relocatable image
 1187: (@pxref{Non-Relocatable Image Files}).  However, this has the
 1188: disadvantage that it does not work on operating systems with address
 1189: space randomization (the default in, e.g., Linux nowadays), or if the
 1190: dictionary moves for any other reason (e.g., because of a change of
 1191: the OS kernel or an updated library), so we cannot really recommend
 1192: it.  You create a non-relocatable image with @code{gforth-fast
 1193: --no-dynamic -e "savesystem gforthnr.fi bye"} (the @code{--no-dynamic}
 1194: is required here, too).  And you run it with @code{gforth-fast -i
 1195: gforthnr.fi ... -e bye} (again the flags discussed above don't
 1196: matter).  @code{gforth-fast -i gforthdr.fi -e bye} takes
 1197: about 0.9ms user and 0.9ms system time.
 1198: 
 1199: If the script you want to execute contains a significant amount of
 1200: code, it may be profitable to compile it into the image to avoid the
 1201: cost of compiling it at startup time.
 1202: 
 1203: @c ******************************************************************
 1204: @node Tutorial, Introduction, Gforth Environment, Top
 1205: @chapter Forth Tutorial
 1206: @cindex Tutorial
 1207: @cindex Forth Tutorial
 1208: 
 1209: @c Topics from nac's Introduction that could be mentioned:
 1210: @c press <ret> after each line
 1211: @c Prompt
 1212: @c numbers vs. words in dictionary on text interpretation
 1213: @c what happens on redefinition
 1214: @c parsing words (in particular, defining words)
 1215: 
 1216: The difference of this chapter from the Introduction
 1217: (@pxref{Introduction}) is that this tutorial is more fast-paced, should
 1218: be used while sitting in front of a computer, and covers much more
 1219: material, but does not explain how the Forth system works.
 1220: 
 1221: This tutorial can be used with any ANS-compliant Forth; any
 1222: Gforth-specific features are marked as such and you can skip them if
 1223: you work with another Forth.  This tutorial does not explain all
 1224: features of Forth, just enough to get you started and give you some
 1225: ideas about the facilities available in Forth.  Read the rest of the
 1226: manual when you are through this.
 1227: 
 1228: The intended way to use this tutorial is that you work through it while
 1229: sitting in front of the console, take a look at the examples and predict
 1230: what they will do, then try them out; if the outcome is not as expected,
 1231: find out why (e.g., by trying out variations of the example), so you
 1232: understand what's going on.  There are also some assignments that you
 1233: should solve.
 1234: 
 1235: This tutorial assumes that you have programmed before and know what,
 1236: e.g., a loop is.
 1237: 
 1238: @c !! explain compat library
 1239: 
 1240: @menu
 1241: * Starting Gforth Tutorial::    
 1242: * Syntax Tutorial::             
 1243: * Crash Course Tutorial::       
 1244: * Stack Tutorial::              
 1245: * Arithmetics Tutorial::        
 1246: * Stack Manipulation Tutorial::  
 1247: * Using files for Forth code Tutorial::  
 1248: * Comments Tutorial::           
 1249: * Colon Definitions Tutorial::  
 1250: * Decompilation Tutorial::      
 1251: * Stack-Effect Comments Tutorial::  
 1252: * Types Tutorial::              
 1253: * Factoring Tutorial::          
 1254: * Designing the stack effect Tutorial::  
 1255: * Local Variables Tutorial::    
 1256: * Conditional execution Tutorial::  
 1257: * Flags and Comparisons Tutorial::  
 1258: * General Loops Tutorial::      
 1259: * Counted loops Tutorial::      
 1260: * Recursion Tutorial::          
 1261: * Leaving definitions or loops Tutorial::  
 1262: * Return Stack Tutorial::       
 1263: * Memory Tutorial::             
 1264: * Characters and Strings Tutorial::  
 1265: * Alignment Tutorial::          
 1266: * Floating Point Tutorial::     
 1267: * Files Tutorial::              
 1268: * Interpretation and Compilation Semantics and Immediacy Tutorial::  
 1269: * Execution Tokens Tutorial::   
 1270: * Exceptions Tutorial::         
 1271: * Defining Words Tutorial::     
 1272: * Arrays and Records Tutorial::  
 1273: * POSTPONE Tutorial::           
 1274: * Literal Tutorial::            
 1275: * Advanced macros Tutorial::    
 1276: * Compilation Tokens Tutorial::  
 1277: * Wordlists and Search Order Tutorial::  
 1278: @end menu
 1279: 
 1280: @node Starting Gforth Tutorial, Syntax Tutorial, Tutorial, Tutorial
 1281: @section Starting Gforth
 1282: @cindex starting Gforth tutorial
 1283: You can start Gforth by typing its name:
 1284: 
 1285: @example
 1286: gforth
 1287: @end example
 1288: 
 1289: That puts you into interactive mode; you can leave Gforth by typing
 1290: @code{bye}.  While in Gforth, you can edit the command line and access
 1291: the command line history with cursor keys, similar to bash.
 1292: 
 1293: 
 1294: @node Syntax Tutorial, Crash Course Tutorial, Starting Gforth Tutorial, Tutorial
 1295: @section Syntax
 1296: @cindex syntax tutorial
 1297: 
 1298: A @dfn{word} is a sequence of arbitrary characters (except white
 1299: space).  Words are separated by white space.  E.g., each of the
 1300: following lines contains exactly one word:
 1301: 
 1302: @example
 1303: word
 1304: !@@#$%^&*()
 1305: 1234567890
 1306: 5!a
 1307: @end example
 1308: 
 1309: A frequent beginner's error is to leave out necessary white space,
 1310: resulting in an error like @samp{Undefined word}; so if you see such an
 1311: error, check if you have put spaces wherever necessary.
 1312: 
 1313: @example
 1314: ." hello, world" \ correct
 1315: ."hello, world"  \ gives an "Undefined word" error
 1316: @end example
 1317: 
 1318: Gforth and most other Forth systems ignore differences in case (they are
 1319: case-insensitive), i.e., @samp{word} is the same as @samp{Word}.  If
 1320: your system is case-sensitive, you may have to type all the examples
 1321: given here in upper case.
 1322: 
 1323: 
 1324: @node Crash Course Tutorial, Stack Tutorial, Syntax Tutorial, Tutorial
 1325: @section Crash Course
 1326: 
 1327: Forth does not prevent you from shooting yourself in the foot.  Let's
 1328: try a few ways to crash Gforth:
 1329: 
 1330: @example
 1331: 0 0 !
 1332: here execute
 1333: ' catch >body 20 erase abort
 1334: ' (quit) >body 20 erase
 1335: @end example
 1336: 
 1337: The last two examples are guaranteed to destroy important parts of
 1338: Gforth (and most other systems), so you better leave Gforth afterwards
 1339: (if it has not finished by itself).  On some systems you may have to
 1340: kill gforth from outside (e.g., in Unix with @code{kill}).
 1341: 
 1342: You will find out later what these lines do and then you will get an
 1343: idea why they produce crashes.
 1344: 
 1345: Now that you know how to produce crashes (and that there's not much to
 1346: them), let's learn how to produce meaningful programs.
 1347: 
 1348: 
 1349: @node Stack Tutorial, Arithmetics Tutorial, Crash Course Tutorial, Tutorial
 1350: @section Stack
 1351: @cindex stack tutorial
 1352: 
 1353: The most obvious feature of Forth is the stack.  When you type in a
 1354: number, it is pushed on the stack.  You can display the contents of the
 1355: stack with @code{.s}.
 1356: 
 1357: @example
 1358: 1 2 .s
 1359: 3 .s
 1360: @end example
 1361: 
 1362: @code{.s} displays the top-of-stack to the right, i.e., the numbers
 1363: appear in @code{.s} output as they appeared in the input.
 1364: 
 1365: You can print the top element of the stack with @code{.}.
 1366: 
 1367: @example
 1368: 1 2 3 . . .
 1369: @end example
 1370: 
 1371: In general, words consume their stack arguments (@code{.s} is an
 1372: exception).
 1373: 
 1374: @quotation Assignment
 1375: What does the stack contain after @code{5 6 7 .}?
 1376: @end quotation
 1377: 
 1378: 
 1379: @node Arithmetics Tutorial, Stack Manipulation Tutorial, Stack Tutorial, Tutorial
 1380: @section Arithmetics
 1381: @cindex arithmetics tutorial
 1382: 
 1383: The words @code{+}, @code{-}, @code{*}, @code{/}, and @code{mod} always
 1384: operate on the top two stack items:
 1385: 
 1386: @example
 1387: 2 2 .s
 1388: + .s
 1389: .
 1390: 2 1 - .
 1391: 7 3 mod .
 1392: @end example
 1393: 
 1394: The operands of @code{-}, @code{/}, and @code{mod} are in the same order
 1395: as in the corresponding infix expression (this is generally the case in
 1396: Forth).
 1397: 
 1398: Parentheses are superfluous (and not available), because the order of
 1399: the words unambiguously determines the order of evaluation and the
 1400: operands:
 1401: 
 1402: @example
 1403: 3 4 + 5 * .
 1404: 3 4 5 * + .
 1405: @end example
 1406: 
 1407: @quotation Assignment
 1408: What are the infix expressions corresponding to the Forth code above?
 1409: Write @code{6-7*8+9} in Forth notation@footnote{This notation is also
 1410: known as Postfix or RPN (Reverse Polish Notation).}.
 1411: @end quotation
 1412: 
 1413: To change the sign, use @code{negate}:
 1414: 
 1415: @example
 1416: 2 negate .
 1417: @end example
 1418: 
 1419: @quotation Assignment
 1420: Convert -(-3)*4-5 to Forth.
 1421: @end quotation
 1422: 
 1423: @code{/mod} performs both @code{/} and @code{mod}.
 1424: 
 1425: @example
 1426: 7 3 /mod . .
 1427: @end example
 1428: 
 1429: Reference: @ref{Arithmetic}.
 1430: 
 1431: 
 1432: @node Stack Manipulation Tutorial, Using files for Forth code Tutorial, Arithmetics Tutorial, Tutorial
 1433: @section Stack Manipulation
 1434: @cindex stack manipulation tutorial
 1435: 
 1436: Stack manipulation words rearrange the data on the stack.
 1437: 
 1438: @example
 1439: 1 .s drop .s
 1440: 1 .s dup .s drop drop .s
 1441: 1 2 .s over .s drop drop drop
 1442: 1 2 .s swap .s drop drop
 1443: 1 2 3 .s rot .s drop drop drop
 1444: @end example
 1445: 
 1446: These are the most important stack manipulation words.  There are also
 1447: variants that manipulate twice as many stack items:
 1448: 
 1449: @example
 1450: 1 2 3 4 .s 2swap .s 2drop 2drop
 1451: @end example
 1452: 
 1453: Two more stack manipulation words are:
 1454: 
 1455: @example
 1456: 1 2 .s nip .s drop
 1457: 1 2 .s tuck .s 2drop drop
 1458: @end example
 1459: 
 1460: @quotation Assignment
 1461: Replace @code{nip} and @code{tuck} with combinations of other stack
 1462: manipulation words.
 1463: 
 1464: @example
 1465: Given:          How do you get:
 1466: 1 2 3           3 2 1           
 1467: 1 2 3           1 2 3 2                 
 1468: 1 2 3           1 2 3 3                 
 1469: 1 2 3           1 3 3           
 1470: 1 2 3           2 1 3           
 1471: 1 2 3 4         4 3 2 1         
 1472: 1 2 3           1 2 3 1 2 3             
 1473: 1 2 3 4         1 2 3 4 1 2             
 1474: 1 2 3
 1475: 1 2 3           1 2 3 4                 
 1476: 1 2 3           1 3             
 1477: @end example
 1478: @end quotation
 1479: 
 1480: @example
 1481: 5 dup * .
 1482: @end example
 1483: 
 1484: @quotation Assignment
 1485: Write 17^3 and 17^4 in Forth, without writing @code{17} more than once.
 1486: Write a piece of Forth code that expects two numbers on the stack
 1487: (@var{a} and @var{b}, with @var{b} on top) and computes
 1488: @code{(a-b)(a+1)}.
 1489: @end quotation
 1490: 
 1491: Reference: @ref{Stack Manipulation}.
 1492: 
 1493: 
 1494: @node Using files for Forth code Tutorial, Comments Tutorial, Stack Manipulation Tutorial, Tutorial
 1495: @section Using files for Forth code
 1496: @cindex loading Forth code, tutorial
 1497: @cindex files containing Forth code, tutorial
 1498: 
 1499: While working at the Forth command line is convenient for one-line
 1500: examples and short one-off code, you probably want to store your source
 1501: code in files for convenient editing and persistence.  You can use your
 1502: favourite editor (Gforth includes Emacs support, @pxref{Emacs and
 1503: Gforth}) to create @var{file.fs} and use
 1504: 
 1505: @example
 1506: s" @var{file.fs}" included
 1507: @end example
 1508: 
 1509: to load it into your Forth system.  The file name extension I use for
 1510: Forth files is @samp{.fs}.
 1511: 
 1512: You can easily start Gforth with some files loaded like this:
 1513: 
 1514: @example
 1515: gforth @var{file1.fs} @var{file2.fs}
 1516: @end example
 1517: 
 1518: If an error occurs during loading these files, Gforth terminates,
 1519: whereas an error during @code{INCLUDED} within Gforth usually gives you
 1520: a Gforth command line.  Starting the Forth system every time gives you a
 1521: clean start every time, without interference from the results of earlier
 1522: tries.
 1523: 
 1524: I often put all the tests in a file, then load the code and run the
 1525: tests with
 1526: 
 1527: @example
 1528: gforth @var{code.fs} @var{tests.fs} -e bye
 1529: @end example
 1530: 
 1531: (often by performing this command with @kbd{C-x C-e} in Emacs).  The
 1532: @code{-e bye} ensures that Gforth terminates afterwards so that I can
 1533: restart this command without ado.
 1534: 
 1535: The advantage of this approach is that the tests can be repeated easily
 1536: every time the program ist changed, making it easy to catch bugs
 1537: introduced by the change.
 1538: 
 1539: Reference: @ref{Forth source files}.
 1540: 
 1541: 
 1542: @node Comments Tutorial, Colon Definitions Tutorial, Using files for Forth code Tutorial, Tutorial
 1543: @section Comments
 1544: @cindex comments tutorial
 1545: 
 1546: @example
 1547: \ That's a comment; it ends at the end of the line
 1548: ( Another comment; it ends here: )  .s
 1549: @end example
 1550: 
 1551: @code{\} and @code{(} are ordinary Forth words and therefore have to be
 1552: separated with white space from the following text.
 1553: 
 1554: @example
 1555: \This gives an "Undefined word" error
 1556: @end example
 1557: 
 1558: The first @code{)} ends a comment started with @code{(}, so you cannot
 1559: nest @code{(}-comments; and you cannot comment out text containing a
 1560: @code{)} with @code{( ... )}@footnote{therefore it's a good idea to
 1561: avoid @code{)} in word names.}.
 1562: 
 1563: I use @code{\}-comments for descriptive text and for commenting out code
 1564: of one or more line; I use @code{(}-comments for describing the stack
 1565: effect, the stack contents, or for commenting out sub-line pieces of
 1566: code.
 1567: 
 1568: The Emacs mode @file{gforth.el} (@pxref{Emacs and Gforth}) supports
 1569: these uses by commenting out a region with @kbd{C-x \}, uncommenting a
 1570: region with @kbd{C-u C-x \}, and filling a @code{\}-commented region
 1571: with @kbd{M-q}.
 1572: 
 1573: Reference: @ref{Comments}.
 1574: 
 1575: 
 1576: @node Colon Definitions Tutorial, Decompilation Tutorial, Comments Tutorial, Tutorial
 1577: @section Colon Definitions
 1578: @cindex colon definitions, tutorial
 1579: @cindex definitions, tutorial
 1580: @cindex procedures, tutorial
 1581: @cindex functions, tutorial
 1582: 
 1583: are similar to procedures and functions in other programming languages.
 1584: 
 1585: @example
 1586: : squared ( n -- n^2 )
 1587:    dup * ;
 1588: 5 squared .
 1589: 7 squared .
 1590: @end example
 1591: 
 1592: @code{:} starts the colon definition; its name is @code{squared}.  The
 1593: following comment describes its stack effect.  The words @code{dup *}
 1594: are not executed, but compiled into the definition.  @code{;} ends the
 1595: colon definition.
 1596: 
 1597: The newly-defined word can be used like any other word, including using
 1598: it in other definitions:
 1599: 
 1600: @example
 1601: : cubed ( n -- n^3 )
 1602:    dup squared * ;
 1603: -5 cubed .
 1604: : fourth-power ( n -- n^4 )
 1605:    squared squared ;
 1606: 3 fourth-power .
 1607: @end example
 1608: 
 1609: @quotation Assignment
 1610: Write colon definitions for @code{nip}, @code{tuck}, @code{negate}, and
 1611: @code{/mod} in terms of other Forth words, and check if they work (hint:
 1612: test your tests on the originals first).  Don't let the
 1613: @samp{redefined}-Messages spook you, they are just warnings.
 1614: @end quotation
 1615: 
 1616: Reference: @ref{Colon Definitions}.
 1617: 
 1618: 
 1619: @node Decompilation Tutorial, Stack-Effect Comments Tutorial, Colon Definitions Tutorial, Tutorial
 1620: @section Decompilation
 1621: @cindex decompilation tutorial
 1622: @cindex see tutorial
 1623: 
 1624: You can decompile colon definitions with @code{see}:
 1625: 
 1626: @example
 1627: see squared
 1628: see cubed
 1629: @end example
 1630: 
 1631: In Gforth @code{see} shows you a reconstruction of the source code from
 1632: the executable code.  Informations that were present in the source, but
 1633: not in the executable code, are lost (e.g., comments).
 1634: 
 1635: You can also decompile the predefined words:
 1636: 
 1637: @example
 1638: see .
 1639: see +
 1640: @end example
 1641: 
 1642: 
 1643: @node Stack-Effect Comments Tutorial, Types Tutorial, Decompilation Tutorial, Tutorial
 1644: @section Stack-Effect Comments
 1645: @cindex stack-effect comments, tutorial
 1646: @cindex --, tutorial
 1647: By convention the comment after the name of a definition describes the
 1648: stack effect: The part in front of the @samp{--} describes the state of
 1649: the stack before the execution of the definition, i.e., the parameters
 1650: that are passed into the colon definition; the part behind the @samp{--}
 1651: is the state of the stack after the execution of the definition, i.e.,
 1652: the results of the definition.  The stack comment only shows the top
 1653: stack items that the definition accesses and/or changes.
 1654: 
 1655: You should put a correct stack effect on every definition, even if it is
 1656: just @code{( -- )}.  You should also add some descriptive comment to
 1657: more complicated words (I usually do this in the lines following
 1658: @code{:}).  If you don't do this, your code becomes unreadable (because
 1659: you have to work through every definition before you can understand
 1660: any).
 1661: 
 1662: @quotation Assignment
 1663: The stack effect of @code{swap} can be written like this: @code{x1 x2 --
 1664: x2 x1}.  Describe the stack effect of @code{-}, @code{drop}, @code{dup},
 1665: @code{over}, @code{rot}, @code{nip}, and @code{tuck}.  Hint: When you
 1666: are done, you can compare your stack effects to those in this manual
 1667: (@pxref{Word Index}).
 1668: @end quotation
 1669: 
 1670: Sometimes programmers put comments at various places in colon
 1671: definitions that describe the contents of the stack at that place (stack
 1672: comments); i.e., they are like the first part of a stack-effect
 1673: comment. E.g.,
 1674: 
 1675: @example
 1676: : cubed ( n -- n^3 )
 1677:    dup squared  ( n n^2 ) * ;
 1678: @end example
 1679: 
 1680: In this case the stack comment is pretty superfluous, because the word
 1681: is simple enough.  If you think it would be a good idea to add such a
 1682: comment to increase readability, you should also consider factoring the
 1683: word into several simpler words (@pxref{Factoring Tutorial,,
 1684: Factoring}), which typically eliminates the need for the stack comment;
 1685: however, if you decide not to refactor it, then having such a comment is
 1686: better than not having it.
 1687: 
 1688: The names of the stack items in stack-effect and stack comments in the
 1689: standard, in this manual, and in many programs specify the type through
 1690: a type prefix, similar to Fortran and Hungarian notation.  The most
 1691: frequent prefixes are:
 1692: 
 1693: @table @code
 1694: @item n
 1695: signed integer
 1696: @item u
 1697: unsigned integer
 1698: @item c
 1699: character
 1700: @item f
 1701: Boolean flags, i.e. @code{false} or @code{true}.
 1702: @item a-addr,a-
 1703: Cell-aligned address
 1704: @item c-addr,c-
 1705: Char-aligned address (note that a Char may have two bytes in Windows NT)
 1706: @item xt
 1707: Execution token, same size as Cell
 1708: @item w,x
 1709: Cell, can contain an integer or an address.  It usually takes 32, 64 or
 1710: 16 bits (depending on your platform and Forth system). A cell is more
 1711: commonly known as machine word, but the term @emph{word} already means
 1712: something different in Forth.
 1713: @item d
 1714: signed double-cell integer
 1715: @item ud
 1716: unsigned double-cell integer
 1717: @item r
 1718: Float (on the FP stack)
 1719: @end table
 1720: 
 1721: You can find a more complete list in @ref{Notation}.
 1722: 
 1723: @quotation Assignment
 1724: Write stack-effect comments for all definitions you have written up to
 1725: now.
 1726: @end quotation
 1727: 
 1728: 
 1729: @node Types Tutorial, Factoring Tutorial, Stack-Effect Comments Tutorial, Tutorial
 1730: @section Types
 1731: @cindex types tutorial
 1732: 
 1733: In Forth the names of the operations are not overloaded; so similar
 1734: operations on different types need different names; e.g., @code{+} adds
 1735: integers, and you have to use @code{f+} to add floating-point numbers.
 1736: The following prefixes are often used for related operations on
 1737: different types:
 1738: 
 1739: @table @code
 1740: @item (none)
 1741: signed integer
 1742: @item u
 1743: unsigned integer
 1744: @item c
 1745: character
 1746: @item d
 1747: signed double-cell integer
 1748: @item ud, du
 1749: unsigned double-cell integer
 1750: @item 2
 1751: two cells (not-necessarily double-cell numbers)
 1752: @item m, um
 1753: mixed single-cell and double-cell operations
 1754: @item f
 1755: floating-point (note that in stack comments @samp{f} represents flags,
 1756: and @samp{r} represents FP numbers; also, you need to include the
 1757: exponent part in literal FP numbers, @pxref{Floating Point Tutorial}).
 1758: @end table
 1759: 
 1760: If there are no differences between the signed and the unsigned variant
 1761: (e.g., for @code{+}), there is only the prefix-less variant.
 1762: 
 1763: Forth does not perform type checking, neither at compile time, nor at
 1764: run time.  If you use the wrong operation, the data are interpreted
 1765: incorrectly:
 1766: 
 1767: @example
 1768: -1 u.
 1769: @end example
 1770: 
 1771: If you have only experience with type-checked languages until now, and
 1772: have heard how important type-checking is, don't panic!  In my
 1773: experience (and that of other Forthers), type errors in Forth code are
 1774: usually easy to find (once you get used to it), the increased vigilance
 1775: of the programmer tends to catch some harder errors in addition to most
 1776: type errors, and you never have to work around the type system, so in
 1777: most situations the lack of type-checking seems to be a win (projects to
 1778: add type checking to Forth have not caught on).
 1779: 
 1780: 
 1781: @node Factoring Tutorial, Designing the stack effect Tutorial, Types Tutorial, Tutorial
 1782: @section Factoring
 1783: @cindex factoring tutorial
 1784: 
 1785: If you try to write longer definitions, you will soon find it hard to
 1786: keep track of the stack contents.  Therefore, good Forth programmers
 1787: tend to write only short definitions (e.g., three lines).  The art of
 1788: finding meaningful short definitions is known as factoring (as in
 1789: factoring polynomials).
 1790: 
 1791: Well-factored programs offer additional advantages: smaller, more
 1792: general words, are easier to test and debug and can be reused more and
 1793: better than larger, specialized words.
 1794: 
 1795: So, if you run into difficulties with stack management, when writing
 1796: code, try to define meaningful factors for the word, and define the word
 1797: in terms of those.  Even if a factor contains only two words, it is
 1798: often helpful.
 1799: 
 1800: Good factoring is not easy, and it takes some practice to get the knack
 1801: for it; but even experienced Forth programmers often don't find the
 1802: right solution right away, but only when rewriting the program.  So, if
 1803: you don't come up with a good solution immediately, keep trying, don't
 1804: despair.
 1805: 
 1806: @c example !!
 1807: 
 1808: 
 1809: @node Designing the stack effect Tutorial, Local Variables Tutorial, Factoring Tutorial, Tutorial
 1810: @section Designing the stack effect
 1811: @cindex Stack effect design, tutorial
 1812: @cindex design of stack effects, tutorial
 1813: 
 1814: In other languages you can use an arbitrary order of parameters for a
 1815: function; and since there is only one result, you don't have to deal with
 1816: the order of results, either.
 1817: 
 1818: In Forth (and other stack-based languages, e.g., PostScript) the
 1819: parameter and result order of a definition is important and should be
 1820: designed well.  The general guideline is to design the stack effect such
 1821: that the word is simple to use in most cases, even if that complicates
 1822: the implementation of the word.  Some concrete rules are:
 1823: 
 1824: @itemize @bullet
 1825: 
 1826: @item
 1827: Words consume all of their parameters (e.g., @code{.}).
 1828: 
 1829: @item
 1830: If there is a convention on the order of parameters (e.g., from
 1831: mathematics or another programming language), stick with it (e.g.,
 1832: @code{-}).
 1833: 
 1834: @item
 1835: If one parameter usually requires only a short computation (e.g., it is
 1836: a constant), pass it on the top of the stack.  Conversely, parameters
 1837: that usually require a long sequence of code to compute should be passed
 1838: as the bottom (i.e., first) parameter.  This makes the code easier to
 1839: read, because the reader does not need to keep track of the bottom item
 1840: through a long sequence of code (or, alternatively, through stack
 1841: manipulations). E.g., @code{!} (store, @pxref{Memory}) expects the
 1842: address on top of the stack because it is usually simpler to compute
 1843: than the stored value (often the address is just a variable).
 1844: 
 1845: @item
 1846: Similarly, results that are usually consumed quickly should be returned
 1847: on the top of stack, whereas a result that is often used in long
 1848: computations should be passed as bottom result.  E.g., the file words
 1849: like @code{open-file} return the error code on the top of stack, because
 1850: it is usually consumed quickly by @code{throw}; moreover, the error code
 1851: has to be checked before doing anything with the other results.
 1852: 
 1853: @end itemize
 1854: 
 1855: These rules are just general guidelines, don't lose sight of the overall
 1856: goal to make the words easy to use.  E.g., if the convention rule
 1857: conflicts with the computation-length rule, you might decide in favour
 1858: of the convention if the word will be used rarely, and in favour of the
 1859: computation-length rule if the word will be used frequently (because
 1860: with frequent use the cost of breaking the computation-length rule would
 1861: be quite high, and frequent use makes it easier to remember an
 1862: unconventional order).
 1863: 
 1864: @c example !! structure package
 1865: 
 1866: 
 1867: @node Local Variables Tutorial, Conditional execution Tutorial, Designing the stack effect Tutorial, Tutorial
 1868: @section Local Variables
 1869: @cindex local variables, tutorial
 1870: 
 1871: You can define local variables (@emph{locals}) in a colon definition:
 1872: 
 1873: @example
 1874: : swap @{ a b -- b a @}
 1875:   b a ;
 1876: 1 2 swap .s 2drop
 1877: @end example
 1878: 
 1879: (If your Forth system does not support this syntax, include
 1880: @file{compat/anslocal.fs} first).
 1881: 
 1882: In this example @code{@{ a b -- b a @}} is the locals definition; it
 1883: takes two cells from the stack, puts the top of stack in @code{b} and
 1884: the next stack element in @code{a}.  @code{--} starts a comment ending
 1885: with @code{@}}.  After the locals definition, using the name of the
 1886: local will push its value on the stack.  You can leave the comment
 1887: part (@code{-- b a}) away:
 1888: 
 1889: @example
 1890: : swap ( x1 x2 -- x2 x1 )
 1891:   @{ a b @} b a ;
 1892: @end example
 1893: 
 1894: In Gforth you can have several locals definitions, anywhere in a colon
 1895: definition; in contrast, in a standard program you can have only one
 1896: locals definition per colon definition, and that locals definition must
 1897: be outside any control structure.
 1898: 
 1899: With locals you can write slightly longer definitions without running
 1900: into stack trouble.  However, I recommend trying to write colon
 1901: definitions without locals for exercise purposes to help you gain the
 1902: essential factoring skills.
 1903: 
 1904: @quotation Assignment
 1905: Rewrite your definitions until now with locals
 1906: @end quotation
 1907: 
 1908: Reference: @ref{Locals}.
 1909: 
 1910: 
 1911: @node Conditional execution Tutorial, Flags and Comparisons Tutorial, Local Variables Tutorial, Tutorial
 1912: @section Conditional execution
 1913: @cindex conditionals, tutorial
 1914: @cindex if, tutorial
 1915: 
 1916: In Forth you can use control structures only inside colon definitions.
 1917: An @code{if}-structure looks like this:
 1918: 
 1919: @example
 1920: : abs ( n1 -- +n2 )
 1921:     dup 0 < if
 1922:         negate
 1923:     endif ;
 1924: 5 abs .
 1925: -5 abs .
 1926: @end example
 1927: 
 1928: @code{if} takes a flag from the stack.  If the flag is non-zero (true),
 1929: the following code is performed, otherwise execution continues after the
 1930: @code{endif} (or @code{else}).  @code{<} compares the top two stack
 1931: elements and produces a flag:
 1932: 
 1933: @example
 1934: 1 2 < .
 1935: 2 1 < .
 1936: 1 1 < .
 1937: @end example
 1938: 
 1939: Actually the standard name for @code{endif} is @code{then}.  This
 1940: tutorial presents the examples using @code{endif}, because this is often
 1941: less confusing for people familiar with other programming languages
 1942: where @code{then} has a different meaning.  If your system does not have
 1943: @code{endif}, define it with
 1944: 
 1945: @example
 1946: : endif postpone then ; immediate
 1947: @end example
 1948: 
 1949: You can optionally use an @code{else}-part:
 1950: 
 1951: @example
 1952: : min ( n1 n2 -- n )
 1953:   2dup < if
 1954:     drop
 1955:   else
 1956:     nip
 1957:   endif ;
 1958: 2 3 min .
 1959: 3 2 min .
 1960: @end example
 1961: 
 1962: @quotation Assignment
 1963: Write @code{min} without @code{else}-part (hint: what's the definition
 1964: of @code{nip}?).
 1965: @end quotation
 1966: 
 1967: Reference: @ref{Selection}.
 1968: 
 1969: 
 1970: @node Flags and Comparisons Tutorial, General Loops Tutorial, Conditional execution Tutorial, Tutorial
 1971: @section Flags and Comparisons
 1972: @cindex flags tutorial
 1973: @cindex comparison tutorial
 1974: 
 1975: In a false-flag all bits are clear (0 when interpreted as integer).  In
 1976: a canonical true-flag all bits are set (-1 as a twos-complement signed
 1977: integer); in many contexts (e.g., @code{if}) any non-zero value is
 1978: treated as true flag.
 1979: 
 1980: @example
 1981: false .
 1982: true .
 1983: true hex u. decimal
 1984: @end example
 1985: 
 1986: Comparison words produce canonical flags:
 1987: 
 1988: @example
 1989: 1 1 = .
 1990: 1 0= .
 1991: 0 1 < .
 1992: 0 0 < .
 1993: -1 1 u< . \ type error, u< interprets -1 as large unsigned number
 1994: -1 1 < .
 1995: @end example
 1996: 
 1997: Gforth supports all combinations of the prefixes @code{0 u d d0 du f f0}
 1998: (or none) and the comparisons @code{= <> < > <= >=}.  Only a part of
 1999: these combinations are standard (for details see the standard,
 2000: @ref{Numeric comparison}, @ref{Floating Point} or @ref{Word Index}).
 2001: 
 2002: You can use @code{and or xor invert} as operations on canonical flags.
 2003: Actually they are bitwise operations:
 2004: 
 2005: @example
 2006: 1 2 and .
 2007: 1 2 or .
 2008: 1 3 xor .
 2009: 1 invert .
 2010: @end example
 2011: 
 2012: You can convert a zero/non-zero flag into a canonical flag with
 2013: @code{0<>} (and complement it on the way with @code{0=}).
 2014: 
 2015: @example
 2016: 1 0= .
 2017: 1 0<> .
 2018: @end example
 2019: 
 2020: You can use the all-bits-set feature of canonical flags and the bitwise
 2021: operation of the Boolean operations to avoid @code{if}s:
 2022: 
 2023: @example
 2024: : foo ( n1 -- n2 )
 2025:   0= if
 2026:     14
 2027:   else
 2028:     0
 2029:   endif ;
 2030: 0 foo .
 2031: 1 foo .
 2032: 
 2033: : foo ( n1 -- n2 )
 2034:   0= 14 and ;
 2035: 0 foo .
 2036: 1 foo .
 2037: @end example
 2038: 
 2039: @quotation Assignment
 2040: Write @code{min} without @code{if}.
 2041: @end quotation
 2042: 
 2043: For reference, see @ref{Boolean Flags}, @ref{Numeric comparison}, and
 2044: @ref{Bitwise operations}.
 2045: 
 2046: 
 2047: @node General Loops Tutorial, Counted loops Tutorial, Flags and Comparisons Tutorial, Tutorial
 2048: @section General Loops
 2049: @cindex loops, indefinite, tutorial
 2050: 
 2051: The endless loop is the most simple one:
 2052: 
 2053: @example
 2054: : endless ( -- )
 2055:   0 begin
 2056:     dup . 1+
 2057:   again ;
 2058: endless
 2059: @end example
 2060: 
 2061: Terminate this loop by pressing @kbd{Ctrl-C} (in Gforth).  @code{begin}
 2062: does nothing at run-time, @code{again} jumps back to @code{begin}.
 2063: 
 2064: A loop with one exit at any place looks like this:
 2065: 
 2066: @example
 2067: : log2 ( +n1 -- n2 )
 2068: \ logarithmus dualis of n1>0, rounded down to the next integer
 2069:   assert( dup 0> )
 2070:   2/ 0 begin
 2071:     over 0> while
 2072:       1+ swap 2/ swap
 2073:   repeat
 2074:   nip ;
 2075: 7 log2 .
 2076: 8 log2 .
 2077: @end example
 2078: 
 2079: At run-time @code{while} consumes a flag; if it is 0, execution
 2080: continues behind the @code{repeat}; if the flag is non-zero, execution
 2081: continues behind the @code{while}.  @code{Repeat} jumps back to
 2082: @code{begin}, just like @code{again}.
 2083: 
 2084: In Forth there are a number of combinations/abbreviations, like
 2085: @code{1+}.  However, @code{2/} is not one of them; it shifts its
 2086: argument right by one bit (arithmetic shift right), and viewed as
 2087: division that always rounds towards negative infinity (floored
 2088: division).  In contrast, @code{/} rounds towards zero on some systems
 2089: (not on default installations of gforth (>=0.7.0), however).
 2090: 
 2091: @example
 2092: -5 2 / . \ -2 or -3
 2093: -5 2/ .  \ -3
 2094: @end example
 2095: 
 2096: @code{assert(} is no standard word, but you can get it on systems other
 2097: than Gforth by including @file{compat/assert.fs}.  You can see what it
 2098: does by trying
 2099: 
 2100: @example
 2101: 0 log2 .
 2102: @end example
 2103: 
 2104: Here's a loop with an exit at the end:
 2105: 
 2106: @example
 2107: : log2 ( +n1 -- n2 )
 2108: \ logarithmus dualis of n1>0, rounded down to the next integer
 2109:   assert( dup 0 > )
 2110:   -1 begin
 2111:     1+ swap 2/ swap
 2112:     over 0 <=
 2113:   until
 2114:   nip ;
 2115: @end example
 2116: 
 2117: @code{Until} consumes a flag; if it is non-zero, execution continues at
 2118: the @code{begin}, otherwise after the @code{until}.
 2119: 
 2120: @quotation Assignment
 2121: Write a definition for computing the greatest common divisor.
 2122: @end quotation
 2123: 
 2124: Reference: @ref{Simple Loops}.
 2125: 
 2126: 
 2127: @node Counted loops Tutorial, Recursion Tutorial, General Loops Tutorial, Tutorial
 2128: @section Counted loops
 2129: @cindex loops, counted, tutorial
 2130: 
 2131: @example
 2132: : ^ ( n1 u -- n )
 2133: \ n = the uth power of n1
 2134:   1 swap 0 u+do
 2135:     over *
 2136:   loop
 2137:   nip ;
 2138: 3 2 ^ .
 2139: 4 3 ^ .
 2140: @end example
 2141: 
 2142: @code{U+do} (from @file{compat/loops.fs}, if your Forth system doesn't
 2143: have it) takes two numbers of the stack @code{( u3 u4 -- )}, and then
 2144: performs the code between @code{u+do} and @code{loop} for @code{u3-u4}
 2145: times (or not at all, if @code{u3-u4<0}).
 2146: 
 2147: You can see the stack effect design rules at work in the stack effect of
 2148: the loop start words: Since the start value of the loop is more
 2149: frequently constant than the end value, the start value is passed on
 2150: the top-of-stack.
 2151: 
 2152: You can access the counter of a counted loop with @code{i}:
 2153: 
 2154: @example
 2155: : fac ( u -- u! )
 2156:   1 swap 1+ 1 u+do
 2157:     i *
 2158:   loop ;
 2159: 5 fac .
 2160: 7 fac .
 2161: @end example
 2162: 
 2163: There is also @code{+do}, which expects signed numbers (important for
 2164: deciding whether to enter the loop).
 2165: 
 2166: @quotation Assignment
 2167: Write a definition for computing the nth Fibonacci number.
 2168: @end quotation
 2169: 
 2170: You can also use increments other than 1:
 2171: 
 2172: @example
 2173: : up2 ( n1 n2 -- )
 2174:   +do
 2175:     i .
 2176:   2 +loop ;
 2177: 10 0 up2
 2178: 
 2179: : down2 ( n1 n2 -- )
 2180:   -do
 2181:     i .
 2182:   2 -loop ;
 2183: 0 10 down2
 2184: @end example
 2185: 
 2186: Reference: @ref{Counted Loops}.
 2187: 
 2188: 
 2189: @node Recursion Tutorial, Leaving definitions or loops Tutorial, Counted loops Tutorial, Tutorial
 2190: @section Recursion
 2191: @cindex recursion tutorial
 2192: 
 2193: Usually the name of a definition is not visible in the definition; but
 2194: earlier definitions are usually visible:
 2195: 
 2196: @example
 2197: 1 0 / . \ "Floating-point unidentified fault" in Gforth on some platforms
 2198: : / ( n1 n2 -- n )
 2199:   dup 0= if
 2200:     -10 throw \ report division by zero
 2201:   endif
 2202:   /           \ old version
 2203: ;
 2204: 1 0 /
 2205: @end example
 2206: 
 2207: For recursive definitions you can use @code{recursive} (non-standard) or
 2208: @code{recurse}:
 2209: 
 2210: @example
 2211: : fac1 ( n -- n! ) recursive
 2212:  dup 0> if
 2213:    dup 1- fac1 *
 2214:  else
 2215:    drop 1
 2216:  endif ;
 2217: 7 fac1 .
 2218: 
 2219: : fac2 ( n -- n! )
 2220:  dup 0> if
 2221:    dup 1- recurse *
 2222:  else
 2223:    drop 1
 2224:  endif ;
 2225: 8 fac2 .
 2226: @end example
 2227: 
 2228: @quotation Assignment
 2229: Write a recursive definition for computing the nth Fibonacci number.
 2230: @end quotation
 2231: 
 2232: Reference (including indirect recursion): @xref{Calls and returns}.
 2233: 
 2234: 
 2235: @node Leaving definitions or loops Tutorial, Return Stack Tutorial, Recursion Tutorial, Tutorial
 2236: @section Leaving definitions or loops
 2237: @cindex leaving definitions, tutorial
 2238: @cindex leaving loops, tutorial
 2239: 
 2240: @code{EXIT} exits the current definition right away.  For every counted
 2241: loop that is left in this way, an @code{UNLOOP} has to be performed
 2242: before the @code{EXIT}:
 2243: 
 2244: @c !! real examples
 2245: @example
 2246: : ...
 2247:  ... u+do
 2248:    ... if
 2249:      ... unloop exit
 2250:    endif
 2251:    ...
 2252:  loop
 2253:  ... ;
 2254: @end example
 2255: 
 2256: @code{LEAVE} leaves the innermost counted loop right away:
 2257: 
 2258: @example
 2259: : ...
 2260:  ... u+do
 2261:    ... if
 2262:      ... leave
 2263:    endif
 2264:    ...
 2265:  loop
 2266:  ... ;
 2267: @end example
 2268: 
 2269: @c !! example
 2270: 
 2271: Reference: @ref{Calls and returns}, @ref{Counted Loops}.
 2272: 
 2273: 
 2274: @node Return Stack Tutorial, Memory Tutorial, Leaving definitions or loops Tutorial, Tutorial
 2275: @section Return Stack
 2276: @cindex return stack tutorial
 2277: 
 2278: In addition to the data stack Forth also has a second stack, the return
 2279: stack; most Forth systems store the return addresses of procedure calls
 2280: there (thus its name).  Programmers can also use this stack:
 2281: 
 2282: @example
 2283: : foo ( n1 n2 -- )
 2284:  .s
 2285:  >r .s
 2286:  r@@ .
 2287:  >r .s
 2288:  r@@ .
 2289:  r> .
 2290:  r@@ .
 2291:  r> . ;
 2292: 1 2 foo
 2293: @end example
 2294: 
 2295: @code{>r} takes an element from the data stack and pushes it onto the
 2296: return stack; conversely, @code{r>} moves an elementm from the return to
 2297: the data stack; @code{r@@} pushes a copy of the top of the return stack
 2298: on the data stack.
 2299: 
 2300: Forth programmers usually use the return stack for storing data
 2301: temporarily, if using the data stack alone would be too complex, and
 2302: factoring and locals are not an option:
 2303: 
 2304: @example
 2305: : 2swap ( x1 x2 x3 x4 -- x3 x4 x1 x2 )
 2306:  rot >r rot r> ;
 2307: @end example
 2308: 
 2309: The return address of the definition and the loop control parameters of
 2310: counted loops usually reside on the return stack, so you have to take
 2311: all items, that you have pushed on the return stack in a colon
 2312: definition or counted loop, from the return stack before the definition
 2313: or loop ends.  You cannot access items that you pushed on the return
 2314: stack outside some definition or loop within the definition of loop.
 2315: 
 2316: If you miscount the return stack items, this usually ends in a crash:
 2317: 
 2318: @example
 2319: : crash ( n -- )
 2320:   >r ;
 2321: 5 crash
 2322: @end example
 2323: 
 2324: You cannot mix using locals and using the return stack (according to the
 2325: standard; Gforth has no problem).  However, they solve the same
 2326: problems, so this shouldn't be an issue.
 2327: 
 2328: @quotation Assignment
 2329: Can you rewrite any of the definitions you wrote until now in a better
 2330: way using the return stack?
 2331: @end quotation
 2332: 
 2333: Reference: @ref{Return stack}.
 2334: 
 2335: 
 2336: @node Memory Tutorial, Characters and Strings Tutorial, Return Stack Tutorial, Tutorial
 2337: @section Memory
 2338: @cindex memory access/allocation tutorial
 2339: 
 2340: You can create a global variable @code{v} with
 2341: 
 2342: @example
 2343: variable v ( -- addr )
 2344: @end example
 2345: 
 2346: @code{v} pushes the address of a cell in memory on the stack.  This cell
 2347: was reserved by @code{variable}.  You can use @code{!} (store) to store
 2348: values into this cell and @code{@@} (fetch) to load the value from the
 2349: stack into memory:
 2350: 
 2351: @example
 2352: v .
 2353: 5 v ! .s
 2354: v @@ .
 2355: @end example
 2356: 
 2357: You can see a raw dump of memory with @code{dump}:
 2358: 
 2359: @example
 2360: v 1 cells .s dump
 2361: @end example
 2362: 
 2363: @code{Cells ( n1 -- n2 )} gives you the number of bytes (or, more
 2364: generally, address units (aus)) that @code{n1 cells} occupy.  You can
 2365: also reserve more memory:
 2366: 
 2367: @example
 2368: create v2 20 cells allot
 2369: v2 20 cells dump
 2370: @end example
 2371: 
 2372: creates a variable-like word @code{v2} and reserves 20 uninitialized
 2373: cells; the address pushed by @code{v2} points to the start of these 20
 2374: cells (@pxref{CREATE}).  You can use address arithmetic to access
 2375: these cells:
 2376: 
 2377: @example
 2378: 3 v2 5 cells + !
 2379: v2 20 cells dump
 2380: @end example
 2381: 
 2382: You can reserve and initialize memory with @code{,}:
 2383: 
 2384: @example
 2385: create v3
 2386:   5 , 4 , 3 , 2 , 1 ,
 2387: v3 @@ .
 2388: v3 cell+ @@ .
 2389: v3 2 cells + @@ .
 2390: v3 5 cells dump
 2391: @end example
 2392: 
 2393: @quotation Assignment
 2394: Write a definition @code{vsum ( addr u -- n )} that computes the sum of
 2395: @code{u} cells, with the first of these cells at @code{addr}, the next
 2396: one at @code{addr cell+} etc.
 2397: @end quotation
 2398: 
 2399: You can also reserve memory without creating a new word:
 2400: 
 2401: @example
 2402: here 10 cells allot .
 2403: here .
 2404: @end example
 2405: 
 2406: The first @code{here} pushes the start address of the memory area, the
 2407: second @code{here} the address after the dictionary area.  You should
 2408: store the start address somewhere, or you will have a hard time
 2409: finding the memory area again.
 2410: 
 2411: @code{Allot} manages dictionary memory.  The dictionary memory contains
 2412: the system's data structures for words etc. on Gforth and most other
 2413: Forth systems.  It is managed like a stack: You can free the memory that
 2414: you have just @code{allot}ed with
 2415: 
 2416: @example
 2417: -10 cells allot
 2418: here .
 2419: @end example
 2420: 
 2421: Note that you cannot do this if you have created a new word in the
 2422: meantime (because then your @code{allot}ed memory is no longer on the
 2423: top of the dictionary ``stack'').
 2424: 
 2425: Alternatively, you can use @code{allocate} and @code{free} which allow
 2426: freeing memory in any order:
 2427: 
 2428: @example
 2429: 10 cells allocate throw .s
 2430: 20 cells allocate throw .s
 2431: swap
 2432: free throw
 2433: free throw
 2434: @end example
 2435: 
 2436: The @code{throw}s deal with errors (e.g., out of memory).
 2437: 
 2438: And there is also a
 2439: @uref{http://www.complang.tuwien.ac.at/forth/garbage-collection.zip,
 2440: garbage collector}, which eliminates the need to @code{free} memory
 2441: explicitly.
 2442: 
 2443: Reference: @ref{Memory}.
 2444: 
 2445: 
 2446: @node Characters and Strings Tutorial, Alignment Tutorial, Memory Tutorial, Tutorial
 2447: @section Characters and Strings
 2448: @cindex strings tutorial
 2449: @cindex characters tutorial
 2450: 
 2451: On the stack characters take up a cell, like numbers.  In memory they
 2452: have their own size (one 8-bit byte on most systems), and therefore
 2453: require their own words for memory access:
 2454: 
 2455: @example
 2456: create v4 
 2457:   104 c, 97 c, 108 c, 108 c, 111 c,
 2458: v4 4 chars + c@@ .
 2459: v4 5 chars dump
 2460: @end example
 2461: 
 2462: The preferred representation of strings on the stack is @code{addr
 2463: u-count}, where @code{addr} is the address of the first character and
 2464: @code{u-count} is the number of characters in the string.
 2465: 
 2466: @example
 2467: v4 5 type
 2468: @end example
 2469: 
 2470: You get a string constant with
 2471: 
 2472: @example
 2473: s" hello, world" .s
 2474: type
 2475: @end example
 2476: 
 2477: Make sure you have a space between @code{s"} and the string; @code{s"}
 2478: is a normal Forth word and must be delimited with white space (try what
 2479: happens when you remove the space).
 2480: 
 2481: However, this interpretive use of @code{s"} is quite restricted: the
 2482: string exists only until the next call of @code{s"} (some Forth systems
 2483: keep more than one of these strings, but usually they still have a
 2484: limited lifetime).
 2485: 
 2486: @example
 2487: s" hello," s" world" .s
 2488: type
 2489: type
 2490: @end example
 2491: 
 2492: You can also use @code{s"} in a definition, and the resulting
 2493: strings then live forever (well, for as long as the definition):
 2494: 
 2495: @example
 2496: : foo s" hello," s" world" ;
 2497: foo .s
 2498: type
 2499: type
 2500: @end example
 2501: 
 2502: @quotation Assignment
 2503: @code{Emit ( c -- )} types @code{c} as character (not a number).
 2504: Implement @code{type ( addr u -- )}.
 2505: @end quotation
 2506: 
 2507: Reference: @ref{Memory Blocks}.
 2508: 
 2509: 
 2510: @node Alignment Tutorial, Floating Point Tutorial, Characters and Strings Tutorial, Tutorial
 2511: @section Alignment
 2512: @cindex alignment tutorial
 2513: @cindex memory alignment tutorial
 2514: 
 2515: On many processors cells have to be aligned in memory, if you want to
 2516: access them with @code{@@} and @code{!} (and even if the processor does
 2517: not require alignment, access to aligned cells is faster).
 2518: 
 2519: @code{Create} aligns @code{here} (i.e., the place where the next
 2520: allocation will occur, and that the @code{create}d word points to).
 2521: Likewise, the memory produced by @code{allocate} starts at an aligned
 2522: address.  Adding a number of @code{cells} to an aligned address produces
 2523: another aligned address.
 2524: 
 2525: However, address arithmetic involving @code{char+} and @code{chars} can
 2526: create an address that is not cell-aligned.  @code{Aligned ( addr --
 2527: a-addr )} produces the next aligned address:
 2528: 
 2529: @example
 2530: v3 char+ aligned .s @@ .
 2531: v3 char+ .s @@ .
 2532: @end example
 2533: 
 2534: Similarly, @code{align} advances @code{here} to the next aligned
 2535: address:
 2536: 
 2537: @example
 2538: create v5 97 c,
 2539: here .
 2540: align here .
 2541: 1000 ,
 2542: @end example
 2543: 
 2544: Note that you should use aligned addresses even if your processor does
 2545: not require them, if you want your program to be portable.
 2546: 
 2547: Reference: @ref{Address arithmetic}.
 2548: 
 2549: @node Floating Point Tutorial, Files Tutorial, Alignment Tutorial, Tutorial
 2550: @section Floating Point
 2551: @cindex floating point tutorial
 2552: @cindex FP tutorial
 2553: 
 2554: Floating-point (FP) numbers and arithmetic in Forth works mostly as one
 2555: might expect, but there are a few things worth noting:
 2556: 
 2557: The first point is not specific to Forth, but so important and yet not
 2558: universally known that I mention it here: FP numbers are not reals.
 2559: Many properties (e.g., arithmetic laws) that reals have and that one
 2560: expects of all kinds of numbers do not hold for FP numbers.  If you
 2561: want to use FP computations, you should learn about their problems and
 2562: how to avoid them; a good starting point is @cite{David Goldberg,
 2563: @uref{http://docs.sun.com/source/806-3568/ncg_goldberg.html,What Every
 2564: Computer Scientist Should Know About Floating-Point Arithmetic}, ACM
 2565: Computing Surveys 23(1):5@minus{}48, March 1991}.
 2566: 
 2567: In Forth source code literal FP numbers need an exponent, e.g.,
 2568: @code{1e0}; this can also be written shorter as @code{1e}, longer as
 2569: @code{+1.0e+0}, and many variations in between.  The reason for this is
 2570: that, for historical reasons, Forth interprets a decimal point alone
 2571: (e.g., @code{1.}) as indicating a double-cell integer.  Examples:
 2572: 
 2573: @example
 2574: 2e 2e f+ f.
 2575: @end example
 2576: 
 2577: Another requirement for literal FP numbers is that the current base is
 2578: decimal; with a hex base @code{1e} is interpreted as an integer.
 2579: 
 2580: Forth has a separate stack for FP numbers.@footnote{Theoretically, an
 2581: ANS Forth system may implement the FP stack on the data stack, but
 2582: virtually all systems implement a separate FP stack; and programming
 2583: in a way that accommodates all models is so cumbersome that nobody
 2584: does it.}  One advantage of this model is that cells are not in the
 2585: way when accessing FP values, and vice versa.  Forth has a set of
 2586: words for manipulating the FP stack: @code{fdup fswap fdrop fover
 2587: frot} and (non-standard) @code{fnip ftuck fpick}.
 2588: 
 2589: FP arithmetic words are prefixed with @code{F}.  There is the usual
 2590: set @code{f+ f- f* f/ f** fnegate} as well as a number of words for
 2591: other functions, e.g., @code{fsqrt fsin fln fmin}.  One word that you
 2592: might expect is @code{f=}; but @code{f=} is non-standard, because FP
 2593: computation results are usually inaccurate, so exact comparison is
 2594: usually a mistake, and one should use approximate comparison.
 2595: Unfortunately, @code{f~}, the standard word for that purpose, is not
 2596: well designed, so Gforth provides @code{f~abs} and @code{f~rel} as
 2597: well.
 2598: 
 2599: And of course there are words for accessing FP numbers in memory
 2600: (@code{f@@ f!}), and for address arithmetic (@code{floats float+
 2601: faligned}).  There are also variants of these words with an @code{sf}
 2602: and @code{df} prefix for accessing IEEE format single-precision and
 2603: double-precision numbers in memory; their main purpose is for
 2604: accessing external FP data (e.g., that has been read from or will be
 2605: written to a file).
 2606: 
 2607: Here is an example of a dot-product word and its use:
 2608: 
 2609: @example
 2610: : v* ( f_addr1 nstride1 f_addr2 nstride2 ucount -- r )
 2611:   >r swap 2swap swap 0e r> 0 ?DO
 2612:     dup f@@ over + 2swap dup f@@ f* f+ over + 2swap
 2613:   LOOP
 2614:   2drop 2drop ;
 2615: 
 2616: create v 1.23e f, 4.56e f, 7.89e f,
 2617: 
 2618: v 1 floats  v 1 floats  3  v* f.
 2619: @end example
 2620: 
 2621: @quotation Assignment
 2622: Write a program to solve a quadratic equation.  Then read @cite{Henry
 2623: G. Baker,
 2624: @uref{http://home.pipeline.com/~hbaker1/sigplannotices/sigcol05.ps.gz,You
 2625: Could Learn a Lot from a Quadratic}, ACM SIGPLAN Notices,
 2626: 33(1):30@minus{}39, January 1998}, and see if you can improve your
 2627: program.  Finally, find a test case where the original and the
 2628: improved version produce different results.
 2629: @end quotation
 2630: 
 2631: Reference: @ref{Floating Point}; @ref{Floating point stack};
 2632: @ref{Number Conversion}; @ref{Memory Access}; @ref{Address
 2633: arithmetic}.
 2634: 
 2635: @node Files Tutorial, Interpretation and Compilation Semantics and Immediacy Tutorial, Floating Point Tutorial, Tutorial
 2636: @section Files
 2637: @cindex files tutorial
 2638: 
 2639: This section gives a short introduction into how to use files inside
 2640: Forth. It's broken up into five easy steps:
 2641: 
 2642: @enumerate 1
 2643: @item Opened an ASCII text file for input
 2644: @item Opened a file for output
 2645: @item Read input file until string matched (or some other condition matched)
 2646: @item Wrote some lines from input ( modified or not) to output
 2647: @item Closed the files.
 2648: @end enumerate
 2649: 
 2650: Reference: @ref{General files}.
 2651: 
 2652: @subsection Open file for input
 2653: 
 2654: @example
 2655: s" foo.in"  r/o open-file throw Value fd-in
 2656: @end example
 2657: 
 2658: @subsection Create file for output
 2659: 
 2660: @example
 2661: s" foo.out" w/o create-file throw Value fd-out
 2662: @end example
 2663: 
 2664: The available file modes are r/o for read-only access, r/w for
 2665: read-write access, and w/o for write-only access. You could open both
 2666: files with r/w, too, if you like. All file words return error codes; for
 2667: most applications, it's best to pass there error codes with @code{throw}
 2668: to the outer error handler.
 2669: 
 2670: If you want words for opening and assigning, define them as follows:
 2671: 
 2672: @example
 2673: 0 Value fd-in
 2674: 0 Value fd-out
 2675: : open-input ( addr u -- )  r/o open-file throw to fd-in ;
 2676: : open-output ( addr u -- )  w/o create-file throw to fd-out ;
 2677: @end example
 2678: 
 2679: Usage example:
 2680: 
 2681: @example
 2682: s" foo.in" open-input
 2683: s" foo.out" open-output
 2684: @end example
 2685: 
 2686: @subsection Scan file for a particular line
 2687: 
 2688: @example
 2689: 256 Constant max-line
 2690: Create line-buffer  max-line 2 + allot
 2691: 
 2692: : scan-file ( addr u -- )
 2693:   begin
 2694:       line-buffer max-line fd-in read-line throw
 2695:   while
 2696:          >r 2dup line-buffer r> compare 0=
 2697:      until
 2698:   else
 2699:      drop
 2700:   then
 2701:   2drop ;
 2702: @end example
 2703: 
 2704: @code{read-line ( addr u1 fd -- u2 flag ior )} reads up to u1 bytes into
 2705: the buffer at addr, and returns the number of bytes read, a flag that is
 2706: false when the end of file is reached, and an error code.
 2707: 
 2708: @code{compare ( addr1 u1 addr2 u2 -- n )} compares two strings and
 2709: returns zero if both strings are equal. It returns a positive number if
 2710: the first string is lexically greater, a negative if the second string
 2711: is lexically greater.
 2712: 
 2713: We haven't seen this loop here; it has two exits. Since the @code{while}
 2714: exits with the number of bytes read on the stack, we have to clean up
 2715: that separately; that's after the @code{else}.
 2716: 
 2717: Usage example:
 2718: 
 2719: @example
 2720: s" The text I search is here" scan-file
 2721: @end example
 2722: 
 2723: @subsection Copy input to output
 2724: 
 2725: @example
 2726: : copy-file ( -- )
 2727:   begin
 2728:       line-buffer max-line fd-in read-line throw
 2729:   while
 2730:       line-buffer swap fd-out write-line throw
 2731:   repeat ;
 2732: @end example
 2733: @c !! does not handle long lines, no newline at end of file
 2734: 
 2735: @subsection Close files
 2736: 
 2737: @example
 2738: fd-in close-file throw
 2739: fd-out close-file throw
 2740: @end example
 2741: 
 2742: Likewise, you can put that into definitions, too:
 2743: 
 2744: @example
 2745: : close-input ( -- )  fd-in close-file throw ;
 2746: : close-output ( -- )  fd-out close-file throw ;
 2747: @end example
 2748: 
 2749: @quotation Assignment
 2750: How could you modify @code{copy-file} so that it copies until a second line is
 2751: matched? Can you write a program that extracts a section of a text file,
 2752: given the line that starts and the line that terminates that section?
 2753: @end quotation
 2754: 
 2755: @node Interpretation and Compilation Semantics and Immediacy Tutorial, Execution Tokens Tutorial, Files Tutorial, Tutorial
 2756: @section Interpretation and Compilation Semantics and Immediacy
 2757: @cindex semantics tutorial
 2758: @cindex interpretation semantics tutorial
 2759: @cindex compilation semantics tutorial
 2760: @cindex immediate, tutorial
 2761: 
 2762: When a word is compiled, it behaves differently from being interpreted.
 2763: E.g., consider @code{+}:
 2764: 
 2765: @example
 2766: 1 2 + .
 2767: : foo + ;
 2768: @end example
 2769: 
 2770: These two behaviours are known as compilation and interpretation
 2771: semantics.  For normal words (e.g., @code{+}), the compilation semantics
 2772: is to append the interpretation semantics to the currently defined word
 2773: (@code{foo} in the example above).  I.e., when @code{foo} is executed
 2774: later, the interpretation semantics of @code{+} (i.e., adding two
 2775: numbers) will be performed.
 2776: 
 2777: However, there are words with non-default compilation semantics, e.g.,
 2778: the control-flow words like @code{if}.  You can use @code{immediate} to
 2779: change the compilation semantics of the last defined word to be equal to
 2780: the interpretation semantics:
 2781: 
 2782: @example
 2783: : [FOO] ( -- )
 2784:  5 . ; immediate
 2785: 
 2786: [FOO]
 2787: : bar ( -- )
 2788:   [FOO] ;
 2789: bar
 2790: see bar
 2791: @end example
 2792: 
 2793: Two conventions to mark words with non-default compilation semantics are
 2794: names with brackets (more frequently used) and to write them all in
 2795: upper case (less frequently used).
 2796: 
 2797: In Gforth (and many other systems) you can also remove the
 2798: interpretation semantics with @code{compile-only} (the compilation
 2799: semantics is derived from the original interpretation semantics):
 2800: 
 2801: @example
 2802: : flip ( -- )
 2803:  6 . ; compile-only \ but not immediate
 2804: flip
 2805: 
 2806: : flop ( -- )
 2807:  flip ;
 2808: flop
 2809: @end example
 2810: 
 2811: In this example the interpretation semantics of @code{flop} is equal to
 2812: the original interpretation semantics of @code{flip}.
 2813: 
 2814: The text interpreter has two states: in interpret state, it performs the
 2815: interpretation semantics of words it encounters; in compile state, it
 2816: performs the compilation semantics of these words.
 2817: 
 2818: Among other things, @code{:} switches into compile state, and @code{;}
 2819: switches back to interpret state.  They contain the factors @code{]}
 2820: (switch to compile state) and @code{[} (switch to interpret state), that
 2821: do nothing but switch the state.
 2822: 
 2823: @example
 2824: : xxx ( -- )
 2825:   [ 5 . ]
 2826: ;
 2827: 
 2828: xxx
 2829: see xxx
 2830: @end example
 2831: 
 2832: These brackets are also the source of the naming convention mentioned
 2833: above.
 2834: 
 2835: Reference: @ref{Interpretation and Compilation Semantics}.
 2836: 
 2837: 
 2838: @node Execution Tokens Tutorial, Exceptions Tutorial, Interpretation and Compilation Semantics and Immediacy Tutorial, Tutorial
 2839: @section Execution Tokens
 2840: @cindex execution tokens tutorial
 2841: @cindex XT tutorial
 2842: 
 2843: @code{' word} gives you the execution token (XT) of a word.  The XT is a
 2844: cell representing the interpretation semantics of a word.  You can
 2845: execute this semantics with @code{execute}:
 2846: 
 2847: @example
 2848: ' + .s
 2849: 1 2 rot execute .
 2850: @end example
 2851: 
 2852: The XT is similar to a function pointer in C.  However, parameter
 2853: passing through the stack makes it a little more flexible:
 2854: 
 2855: @example
 2856: : map-array ( ... addr u xt -- ... )
 2857: \ executes xt ( ... x -- ... ) for every element of the array starting
 2858: \ at addr and containing u elements
 2859:   @{ xt @}
 2860:   cells over + swap ?do
 2861:     i @@ xt execute
 2862:   1 cells +loop ;
 2863: 
 2864: create a 3 , 4 , 2 , -1 , 4 ,
 2865: a 5 ' . map-array .s
 2866: 0 a 5 ' + map-array .
 2867: s" max-n" environment? drop .s
 2868: a 5 ' min map-array .
 2869: @end example
 2870: 
 2871: You can use map-array with the XTs of words that consume one element
 2872: more than they produce.  In theory you can also use it with other XTs,
 2873: but the stack effect then depends on the size of the array, which is
 2874: hard to understand.
 2875: 
 2876: Since XTs are cell-sized, you can store them in memory and manipulate
 2877: them on the stack like other cells.  You can also compile the XT into a
 2878: word with @code{compile,}:
 2879: 
 2880: @example
 2881: : foo1 ( n1 n2 -- n )
 2882:    [ ' + compile, ] ;
 2883: see foo
 2884: @end example
 2885: 
 2886: This is non-standard, because @code{compile,} has no compilation
 2887: semantics in the standard, but it works in good Forth systems.  For the
 2888: broken ones, use
 2889: 
 2890: @example
 2891: : [compile,] compile, ; immediate
 2892: 
 2893: : foo1 ( n1 n2 -- n )
 2894:    [ ' + ] [compile,] ;
 2895: see foo
 2896: @end example
 2897: 
 2898: @code{'} is a word with default compilation semantics; it parses the
 2899: next word when its interpretation semantics are executed, not during
 2900: compilation:
 2901: 
 2902: @example
 2903: : foo ( -- xt )
 2904:   ' ;
 2905: see foo
 2906: : bar ( ... "word" -- ... )
 2907:   ' execute ;
 2908: see bar
 2909: 1 2 bar + .
 2910: @end example
 2911: 
 2912: You often want to parse a word during compilation and compile its XT so
 2913: it will be pushed on the stack at run-time.  @code{[']} does this:
 2914: 
 2915: @example
 2916: : xt-+ ( -- xt )
 2917:   ['] + ;
 2918: see xt-+
 2919: 1 2 xt-+ execute .
 2920: @end example
 2921: 
 2922: Many programmers tend to see @code{'} and the word it parses as one
 2923: unit, and expect it to behave like @code{[']} when compiled, and are
 2924: confused by the actual behaviour.  If you are, just remember that the
 2925: Forth system just takes @code{'} as one unit and has no idea that it is
 2926: a parsing word (attempts to convenience programmers in this issue have
 2927: usually resulted in even worse pitfalls, see
 2928: @uref{http://www.complang.tuwien.ac.at/papers/ertl98.ps.gz,
 2929: @code{State}-smartness---Why it is evil and How to Exorcise it}).
 2930: 
 2931: Note that the state of the interpreter does not come into play when
 2932: creating and executing XTs.  I.e., even when you execute @code{'} in
 2933: compile state, it still gives you the interpretation semantics.  And
 2934: whatever that state is, @code{execute} performs the semantics
 2935: represented by the XT (i.e., for XTs produced with @code{'} the
 2936: interpretation semantics).
 2937: 
 2938: Reference: @ref{Tokens for Words}.
 2939: 
 2940: 
 2941: @node Exceptions Tutorial, Defining Words Tutorial, Execution Tokens Tutorial, Tutorial
 2942: @section Exceptions
 2943: @cindex exceptions tutorial
 2944: 
 2945: @code{throw ( n -- )} causes an exception unless n is zero.
 2946: 
 2947: @example
 2948: 100 throw .s
 2949: 0 throw .s
 2950: @end example
 2951: 
 2952: @code{catch ( ... xt -- ... n )} behaves similar to @code{execute}, but
 2953: it catches exceptions and pushes the number of the exception on the
 2954: stack (or 0, if the xt executed without exception).  If there was an
 2955: exception, the stacks have the same depth as when entering @code{catch}:
 2956: 
 2957: @example
 2958: .s
 2959: 3 0 ' / catch .s
 2960: 3 2 ' / catch .s
 2961: @end example
 2962: 
 2963: @quotation Assignment
 2964: Try the same with @code{execute} instead of @code{catch}.
 2965: @end quotation
 2966: 
 2967: @code{Throw} always jumps to the dynamically next enclosing
 2968: @code{catch}, even if it has to leave several call levels to achieve
 2969: this:
 2970: 
 2971: @example
 2972: : foo 100 throw ;
 2973: : foo1 foo ." after foo" ;
 2974: : bar ['] foo1 catch ;
 2975: bar .
 2976: @end example
 2977: 
 2978: It is often important to restore a value upon leaving a definition, even
 2979: if the definition is left through an exception.  You can ensure this
 2980: like this:
 2981: 
 2982: @example
 2983: : ...
 2984:    save-x
 2985:    ['] word-changing-x catch ( ... n )
 2986:    restore-x
 2987:    ( ... n ) throw ;
 2988: @end example
 2989: 
 2990: However, this is still not safe against, e.g., the user pressing
 2991: @kbd{Ctrl-C} when execution is between the @code{catch} and
 2992: @code{restore-x}.
 2993: 
 2994: Gforth provides an alternative exception handling syntax that is safe
 2995: against such cases: @code{try ... restore ... endtry}.  If the code
 2996: between @code{try} and @code{endtry} has an exception, the stack
 2997: depths are restored, the exception number is pushed on the stack, and
 2998: the execution continues right after @code{restore}.
 2999: 
 3000: The safer equivalent to the restoration code above is
 3001: 
 3002: @example
 3003: : ...
 3004:   save-x
 3005:   try
 3006:     word-changing-x 0
 3007:   restore
 3008:     restore-x
 3009:   endtry
 3010:   throw ;
 3011: @end example
 3012: 
 3013: Reference: @ref{Exception Handling}.
 3014: 
 3015: 
 3016: @node Defining Words Tutorial, Arrays and Records Tutorial, Exceptions Tutorial, Tutorial
 3017: @section Defining Words
 3018: @cindex defining words tutorial
 3019: @cindex does> tutorial
 3020: @cindex create...does> tutorial
 3021: 
 3022: @c before semantics?
 3023: 
 3024: @code{:}, @code{create}, and @code{variable} are definition words: They
 3025: define other words.  @code{Constant} is another definition word:
 3026: 
 3027: @example
 3028: 5 constant foo
 3029: foo .
 3030: @end example
 3031: 
 3032: You can also use the prefixes @code{2} (double-cell) and @code{f}
 3033: (floating point) with @code{variable} and @code{constant}.
 3034: 
 3035: You can also define your own defining words.  E.g.:
 3036: 
 3037: @example
 3038: : variable ( "name" -- )
 3039:   create 0 , ;
 3040: @end example
 3041: 
 3042: You can also define defining words that create words that do something
 3043: other than just producing their address:
 3044: 
 3045: @example
 3046: : constant ( n "name" -- )
 3047:   create ,
 3048: does> ( -- n )
 3049:   ( addr ) @@ ;
 3050: 
 3051: 5 constant foo
 3052: foo .
 3053: @end example
 3054: 
 3055: The definition of @code{constant} above ends at the @code{does>}; i.e.,
 3056: @code{does>} replaces @code{;}, but it also does something else: It
 3057: changes the last defined word such that it pushes the address of the
 3058: body of the word and then performs the code after the @code{does>}
 3059: whenever it is called.
 3060: 
 3061: In the example above, @code{constant} uses @code{,} to store 5 into the
 3062: body of @code{foo}.  When @code{foo} executes, it pushes the address of
 3063: the body onto the stack, then (in the code after the @code{does>})
 3064: fetches the 5 from there.
 3065: 
 3066: The stack comment near the @code{does>} reflects the stack effect of the
 3067: defined word, not the stack effect of the code after the @code{does>}
 3068: (the difference is that the code expects the address of the body that
 3069: the stack comment does not show).
 3070: 
 3071: You can use these definition words to do factoring in cases that involve
 3072: (other) definition words.  E.g., a field offset is always added to an
 3073: address.  Instead of defining
 3074: 
 3075: @example
 3076: 2 cells constant offset-field1
 3077: @end example
 3078: 
 3079: and using this like
 3080: 
 3081: @example
 3082: ( addr ) offset-field1 +
 3083: @end example
 3084: 
 3085: you can define a definition word
 3086: 
 3087: @example
 3088: : simple-field ( n "name" -- )
 3089:   create ,
 3090: does> ( n1 -- n1+n )
 3091:   ( addr ) @@ + ;
 3092: @end example
 3093: 
 3094: Definition and use of field offsets now look like this:
 3095: 
 3096: @example
 3097: 2 cells simple-field field1
 3098: create mystruct 4 cells allot
 3099: mystruct .s field1 .s drop
 3100: @end example
 3101: 
 3102: If you want to do something with the word without performing the code
 3103: after the @code{does>}, you can access the body of a @code{create}d word
 3104: with @code{>body ( xt -- addr )}:
 3105: 
 3106: @example
 3107: : value ( n "name" -- )
 3108:   create ,
 3109: does> ( -- n1 )
 3110:   @@ ;
 3111: : to ( n "name" -- )
 3112:   ' >body ! ;
 3113: 
 3114: 5 value foo
 3115: foo .
 3116: 7 to foo
 3117: foo .
 3118: @end example
 3119: 
 3120: @quotation Assignment
 3121: Define @code{defer ( "name" -- )}, which creates a word that stores an
 3122: XT (at the start the XT of @code{abort}), and upon execution
 3123: @code{execute}s the XT.  Define @code{is ( xt "name" -- )} that stores
 3124: @code{xt} into @code{name}, a word defined with @code{defer}.  Indirect
 3125: recursion is one application of @code{defer}.
 3126: @end quotation
 3127: 
 3128: Reference: @ref{User-defined Defining Words}.
 3129: 
 3130: 
 3131: @node Arrays and Records Tutorial, POSTPONE Tutorial, Defining Words Tutorial, Tutorial
 3132: @section Arrays and Records
 3133: @cindex arrays tutorial
 3134: @cindex records tutorial
 3135: @cindex structs tutorial
 3136: 
 3137: Forth has no standard words for defining data structures such as arrays
 3138: and records (structs in C terminology), but you can build them yourself
 3139: based on address arithmetic.  You can also define words for defining
 3140: arrays and records (@pxref{Defining Words Tutorial,, Defining Words}).
 3141: 
 3142: One of the first projects a Forth newcomer sets out upon when learning
 3143: about defining words is an array defining word (possibly for
 3144: n-dimensional arrays).  Go ahead and do it, I did it, too; you will
 3145: learn something from it.  However, don't be disappointed when you later
 3146: learn that you have little use for these words (inappropriate use would
 3147: be even worse).  I have not found a set of useful array words yet;
 3148: the needs are just too diverse, and named, global arrays (the result of
 3149: naive use of defining words) are often not flexible enough (e.g.,
 3150: consider how to pass them as parameters).  Another such project is a set
 3151: of words to help dealing with strings.
 3152: 
 3153: On the other hand, there is a useful set of record words, and it has
 3154: been defined in @file{compat/struct.fs}; these words are predefined in
 3155: Gforth.  They are explained in depth elsewhere in this manual (see
 3156: @pxref{Structures}).  The @code{simple-field} example above is
 3157: simplified variant of fields in this package.
 3158: 
 3159: 
 3160: @node POSTPONE Tutorial, Literal Tutorial, Arrays and Records Tutorial, Tutorial
 3161: @section @code{POSTPONE}
 3162: @cindex postpone tutorial
 3163: 
 3164: You can compile the compilation semantics (instead of compiling the
 3165: interpretation semantics) of a word with @code{POSTPONE}:
 3166: 
 3167: @example
 3168: : MY-+ ( Compilation: -- ; Run-time of compiled code: n1 n2 -- n )
 3169:  POSTPONE + ; immediate
 3170: : foo ( n1 n2 -- n )
 3171:  MY-+ ;
 3172: 1 2 foo .
 3173: see foo
 3174: @end example
 3175: 
 3176: During the definition of @code{foo} the text interpreter performs the
 3177: compilation semantics of @code{MY-+}, which performs the compilation
 3178: semantics of @code{+}, i.e., it compiles @code{+} into @code{foo}.
 3179: 
 3180: This example also displays separate stack comments for the compilation
 3181: semantics and for the stack effect of the compiled code.  For words with
 3182: default compilation semantics these stack effects are usually not
 3183: displayed; the stack effect of the compilation semantics is always
 3184: @code{( -- )} for these words, the stack effect for the compiled code is
 3185: the stack effect of the interpretation semantics.
 3186: 
 3187: Note that the state of the interpreter does not come into play when
 3188: performing the compilation semantics in this way.  You can also perform
 3189: it interpretively, e.g.:
 3190: 
 3191: @example
 3192: : foo2 ( n1 n2 -- n )
 3193:  [ MY-+ ] ;
 3194: 1 2 foo .
 3195: see foo
 3196: @end example
 3197: 
 3198: However, there are some broken Forth systems where this does not always
 3199: work, and therefore this practice was been declared non-standard in
 3200: 1999.
 3201: @c !! repair.fs
 3202: 
 3203: Here is another example for using @code{POSTPONE}:
 3204: 
 3205: @example
 3206: : MY-- ( Compilation: -- ; Run-time of compiled code: n1 n2 -- n )
 3207:  POSTPONE negate POSTPONE + ; immediate compile-only
 3208: : bar ( n1 n2 -- n )
 3209:   MY-- ;
 3210: 2 1 bar .
 3211: see bar
 3212: @end example
 3213: 
 3214: You can define @code{ENDIF} in this way:
 3215: 
 3216: @example
 3217: : ENDIF ( Compilation: orig -- )
 3218:   POSTPONE then ; immediate
 3219: @end example
 3220: 
 3221: @quotation Assignment
 3222: Write @code{MY-2DUP} that has compilation semantics equivalent to
 3223: @code{2dup}, but compiles @code{over over}.
 3224: @end quotation
 3225: 
 3226: @c !! @xref{Macros} for reference
 3227: 
 3228: 
 3229: @node Literal Tutorial, Advanced macros Tutorial, POSTPONE Tutorial, Tutorial
 3230: @section @code{Literal}
 3231: @cindex literal tutorial
 3232: 
 3233: You cannot @code{POSTPONE} numbers:
 3234: 
 3235: @example
 3236: : [FOO] POSTPONE 500 ; immediate
 3237: @end example
 3238: 
 3239: Instead, you can use @code{LITERAL (compilation: n --; run-time: -- n )}:
 3240: 
 3241: @example
 3242: : [FOO] ( compilation: --; run-time: -- n )
 3243:   500 POSTPONE literal ; immediate
 3244: 
 3245: : flip [FOO] ;
 3246: flip .
 3247: see flip
 3248: @end example
 3249: 
 3250: @code{LITERAL} consumes a number at compile-time (when it's compilation
 3251: semantics are executed) and pushes it at run-time (when the code it
 3252: compiled is executed).  A frequent use of @code{LITERAL} is to compile a
 3253: number computed at compile time into the current word:
 3254: 
 3255: @example
 3256: : bar ( -- n )
 3257:   [ 2 2 + ] literal ;
 3258: see bar
 3259: @end example
 3260: 
 3261: @quotation Assignment
 3262: Write @code{]L} which allows writing the example above as @code{: bar (
 3263: -- n ) [ 2 2 + ]L ;}
 3264: @end quotation
 3265: 
 3266: @c !! @xref{Macros} for reference
 3267: 
 3268: 
 3269: @node Advanced macros Tutorial, Compilation Tokens Tutorial, Literal Tutorial, Tutorial
 3270: @section Advanced macros
 3271: @cindex macros, advanced tutorial
 3272: @cindex run-time code generation, tutorial
 3273: 
 3274: Reconsider @code{map-array} from @ref{Execution Tokens Tutorial,,
 3275: Execution Tokens}.  It frequently performs @code{execute}, a relatively
 3276: expensive operation in some Forth implementations.  You can use
 3277: @code{compile,} and @code{POSTPONE} to eliminate these @code{execute}s
 3278: and produce a word that contains the word to be performed directly:
 3279: 
 3280: @c use ]] ... [[
 3281: @example
 3282: : compile-map-array ( compilation: xt -- ; run-time: ... addr u -- ... )
 3283: \ at run-time, execute xt ( ... x -- ... ) for each element of the
 3284: \ array beginning at addr and containing u elements
 3285:   @{ xt @}
 3286:   POSTPONE cells POSTPONE over POSTPONE + POSTPONE swap POSTPONE ?do
 3287:     POSTPONE i POSTPONE @@ xt compile,
 3288:   1 cells POSTPONE literal POSTPONE +loop ;
 3289: 
 3290: : sum-array ( addr u -- n )
 3291:  0 rot rot [ ' + compile-map-array ] ;
 3292: see sum-array
 3293: a 5 sum-array .
 3294: @end example
 3295: 
 3296: You can use the full power of Forth for generating the code; here's an
 3297: example where the code is generated in a loop:
 3298: 
 3299: @example
 3300: : compile-vmul-step ( compilation: n --; run-time: n1 addr1 -- n2 addr2 )
 3301: \ n2=n1+(addr1)*n, addr2=addr1+cell
 3302:   POSTPONE tuck POSTPONE @@
 3303:   POSTPONE literal POSTPONE * POSTPONE +
 3304:   POSTPONE swap POSTPONE cell+ ;
 3305: 
 3306: : compile-vmul ( compilation: addr1 u -- ; run-time: addr2 -- n )
 3307: \ n=v1*v2 (inner product), where the v_i are represented as addr_i u
 3308:   0 postpone literal postpone swap
 3309:   [ ' compile-vmul-step compile-map-array ]
 3310:   postpone drop ;
 3311: see compile-vmul
 3312: 
 3313: : a-vmul ( addr -- n )
 3314: \ n=a*v, where v is a vector that's as long as a and starts at addr
 3315:  [ a 5 compile-vmul ] ;
 3316: see a-vmul
 3317: a a-vmul .
 3318: @end example
 3319: 
 3320: This example uses @code{compile-map-array} to show off, but you could
 3321: also use @code{map-array} instead (try it now!).
 3322: 
 3323: You can use this technique for efficient multiplication of large
 3324: matrices.  In matrix multiplication, you multiply every line of one
 3325: matrix with every column of the other matrix.  You can generate the code
 3326: for one line once, and use it for every column.  The only downside of
 3327: this technique is that it is cumbersome to recover the memory consumed
 3328: by the generated code when you are done (and in more complicated cases
 3329: it is not possible portably).
 3330: 
 3331: @c !! @xref{Macros} for reference
 3332: 
 3333: 
 3334: @node Compilation Tokens Tutorial, Wordlists and Search Order Tutorial, Advanced macros Tutorial, Tutorial
 3335: @section Compilation Tokens
 3336: @cindex compilation tokens, tutorial
 3337: @cindex CT, tutorial
 3338: 
 3339: This section is Gforth-specific.  You can skip it.
 3340: 
 3341: @code{' word compile,} compiles the interpretation semantics.  For words
 3342: with default compilation semantics this is the same as performing the
 3343: compilation semantics.  To represent the compilation semantics of other
 3344: words (e.g., words like @code{if} that have no interpretation
 3345: semantics), Gforth has the concept of a compilation token (CT,
 3346: consisting of two cells), and words @code{comp'} and @code{[comp']}.
 3347: You can perform the compilation semantics represented by a CT with
 3348: @code{execute}:
 3349: 
 3350: @example
 3351: : foo2 ( n1 n2 -- n )
 3352:    [ comp' + execute ] ;
 3353: see foo
 3354: @end example
 3355: 
 3356: You can compile the compilation semantics represented by a CT with
 3357: @code{postpone,}:
 3358: 
 3359: @example
 3360: : foo3 ( -- )
 3361:   [ comp' + postpone, ] ;
 3362: see foo3
 3363: @end example
 3364: 
 3365: @code{[ comp' word postpone, ]} is equivalent to @code{POSTPONE word}.
 3366: @code{comp'} is particularly useful for words that have no
 3367: interpretation semantics:
 3368: 
 3369: @example
 3370: ' if
 3371: comp' if .s 2drop
 3372: @end example
 3373: 
 3374: Reference: @ref{Tokens for Words}.
 3375: 
 3376: 
 3377: @node Wordlists and Search Order Tutorial,  , Compilation Tokens Tutorial, Tutorial
 3378: @section Wordlists and Search Order
 3379: @cindex wordlists tutorial
 3380: @cindex search order, tutorial
 3381: 
 3382: The dictionary is not just a memory area that allows you to allocate
 3383: memory with @code{allot}, it also contains the Forth words, arranged in
 3384: several wordlists.  When searching for a word in a wordlist,
 3385: conceptually you start searching at the youngest and proceed towards
 3386: older words (in reality most systems nowadays use hash-tables); i.e., if
 3387: you define a word with the same name as an older word, the new word
 3388: shadows the older word.
 3389: 
 3390: Which wordlists are searched in which order is determined by the search
 3391: order.  You can display the search order with @code{order}.  It displays
 3392: first the search order, starting with the wordlist searched first, then
 3393: it displays the wordlist that will contain newly defined words.
 3394: 
 3395: You can create a new, empty wordlist with @code{wordlist ( -- wid )}:
 3396: 
 3397: @example
 3398: wordlist constant mywords
 3399: @end example
 3400: 
 3401: @code{Set-current ( wid -- )} sets the wordlist that will contain newly
 3402: defined words (the @emph{current} wordlist):
 3403: 
 3404: @example
 3405: mywords set-current
 3406: order
 3407: @end example
 3408: 
 3409: Gforth does not display a name for the wordlist in @code{mywords}
 3410: because this wordlist was created anonymously with @code{wordlist}.
 3411: 
 3412: You can get the current wordlist with @code{get-current ( -- wid)}.  If
 3413: you want to put something into a specific wordlist without overall
 3414: effect on the current wordlist, this typically looks like this:
 3415: 
 3416: @example
 3417: get-current mywords set-current ( wid )
 3418: create someword
 3419: ( wid ) set-current
 3420: @end example
 3421: 
 3422: You can write the search order with @code{set-order ( wid1 .. widn n --
 3423: )} and read it with @code{get-order ( -- wid1 .. widn n )}.  The first
 3424: searched wordlist is topmost.
 3425: 
 3426: @example
 3427: get-order mywords swap 1+ set-order
 3428: order
 3429: @end example
 3430: 
 3431: Yes, the order of wordlists in the output of @code{order} is reversed
 3432: from stack comments and the output of @code{.s} and thus unintuitive.
 3433: 
 3434: @quotation Assignment
 3435: Define @code{>order ( wid -- )} with adds @code{wid} as first searched
 3436: wordlist to the search order.  Define @code{previous ( -- )}, which
 3437: removes the first searched wordlist from the search order.  Experiment
 3438: with boundary conditions (you will see some crashes or situations that
 3439: are hard or impossible to leave).
 3440: @end quotation
 3441: 
 3442: The search order is a powerful foundation for providing features similar
 3443: to Modula-2 modules and C++ namespaces.  However, trying to modularize
 3444: programs in this way has disadvantages for debugging and reuse/factoring
 3445: that overcome the advantages in my experience (I don't do huge projects,
 3446: though).  These disadvantages are not so clear in other
 3447: languages/programming environments, because these languages are not so
 3448: strong in debugging and reuse.
 3449: 
 3450: @c !! example
 3451: 
 3452: Reference: @ref{Word Lists}.
 3453: 
 3454: @c ******************************************************************
 3455: @node Introduction, Words, Tutorial, Top
 3456: @comment node-name,     next,           previous, up
 3457: @chapter An Introduction to ANS Forth
 3458: @cindex Forth - an introduction
 3459: 
 3460: The difference of this chapter from the Tutorial (@pxref{Tutorial}) is
 3461: that it is slower-paced in its examples, but uses them to dive deep into
 3462: explaining Forth internals (not covered by the Tutorial).  Apart from
 3463: that, this chapter covers far less material.  It is suitable for reading
 3464: without using a computer.
 3465: 
 3466: The primary purpose of this manual is to document Gforth. However, since
 3467: Forth is not a widely-known language and there is a lack of up-to-date
 3468: teaching material, it seems worthwhile to provide some introductory
 3469: material.  For other sources of Forth-related
 3470: information, see @ref{Forth-related information}.
 3471: 
 3472: The examples in this section should work on any ANS Forth; the
 3473: output shown was produced using Gforth. Each example attempts to
 3474: reproduce the exact output that Gforth produces. If you try out the
 3475: examples (and you should), what you should type is shown @kbd{like this}
 3476: and Gforth's response is shown @code{like this}. The single exception is
 3477: that, where the example shows @key{RET} it means that you should
 3478: press the ``carriage return'' key. Unfortunately, some output formats for
 3479: this manual cannot show the difference between @kbd{this} and
 3480: @code{this} which will make trying out the examples harder (but not
 3481: impossible).
 3482: 
 3483: Forth is an unusual language. It provides an interactive development
 3484: environment which includes both an interpreter and compiler. Forth
 3485: programming style encourages you to break a problem down into many
 3486: @cindex factoring
 3487: small fragments (@dfn{factoring}), and then to develop and test each
 3488: fragment interactively. Forth advocates assert that breaking the
 3489: edit-compile-test cycle used by conventional programming languages can
 3490: lead to great productivity improvements.
 3491: 
 3492: @menu
 3493: * Introducing the Text Interpreter::  
 3494: * Stacks and Postfix notation::  
 3495: * Your first definition::       
 3496: * How does that work?::         
 3497: * Forth is written in Forth::   
 3498: * Review - elements of a Forth system::  
 3499: * Where to go next::            
 3500: * Exercises::                   
 3501: @end menu
 3502: 
 3503: @comment ----------------------------------------------
 3504: @node Introducing the Text Interpreter, Stacks and Postfix notation, Introduction, Introduction
 3505: @section Introducing the Text Interpreter
 3506: @cindex text interpreter
 3507: @cindex outer interpreter
 3508: 
 3509: @c IMO this is too detailed and the pace is too slow for
 3510: @c an introduction.  If you know German, take a look at
 3511: @c http://www.complang.tuwien.ac.at/anton/lvas/skriptum-stack.html 
 3512: @c to see how I do it - anton 
 3513: 
 3514: @c nac-> Where I have accepted your comments 100% and modified the text
 3515: @c accordingly, I have deleted your comments. Elsewhere I have added a
 3516: @c response like this to attempt to rationalise what I have done. Of
 3517: @c course, this is a very clumsy mechanism for something that would be
 3518: @c done far more efficiently over a beer. Please delete any dialogue
 3519: @c you consider closed.
 3520: 
 3521: When you invoke the Forth image, you will see a startup banner printed
 3522: and nothing else (if you have Gforth installed on your system, try
 3523: invoking it now, by typing @kbd{gforth@key{RET}}). Forth is now running
 3524: its command line interpreter, which is called the @dfn{Text Interpreter}
 3525: (also known as the @dfn{Outer Interpreter}).  (You will learn a lot
 3526: about the text interpreter as you read through this chapter, for more
 3527: detail @pxref{The Text Interpreter}).
 3528: 
 3529: Although it's not obvious, Forth is actually waiting for your
 3530: input. Type a number and press the @key{RET} key:
 3531: 
 3532: @example
 3533: @kbd{45@key{RET}}  ok
 3534: @end example
 3535: 
 3536: Rather than give you a prompt to invite you to input something, the text
 3537: interpreter prints a status message @i{after} it has processed a line
 3538: of input. The status message in this case (``@code{ ok}'' followed by
 3539: carriage-return) indicates that the text interpreter was able to process
 3540: all of your input successfully. Now type something illegal:
 3541: 
 3542: @example
 3543: @kbd{qwer341@key{RET}}
 3544: *the terminal*:2: Undefined word
 3545: >>>qwer341<<<
 3546: Backtrace:
 3547: $2A95B42A20 throw 
 3548: $2A95B57FB8 no.extensions 
 3549: @end example
 3550: 
 3551: The exact text, other than the ``Undefined word'' may differ slightly
 3552: on your system, but the effect is the same; when the text interpreter
 3553: detects an error, it discards any remaining text on a line, resets
 3554: certain internal state and prints an error message. For a detailed
 3555: description of error messages see @ref{Error messages}.
 3556: 
 3557: The text interpreter waits for you to press carriage-return, and then
 3558: processes your input line. Starting at the beginning of the line, it
 3559: breaks the line into groups of characters separated by spaces. For each
 3560: group of characters in turn, it makes two attempts to do something:
 3561: 
 3562: @itemize @bullet
 3563: @item
 3564: @cindex name dictionary
 3565: It tries to treat it as a command. It does this by searching a @dfn{name
 3566: dictionary}. If the group of characters matches an entry in the name
 3567: dictionary, the name dictionary provides the text interpreter with
 3568: information that allows the text interpreter perform some actions. In
 3569: Forth jargon, we say that the group
 3570: @cindex word
 3571: @cindex definition
 3572: @cindex execution token
 3573: @cindex xt
 3574: of characters names a @dfn{word}, that the dictionary search returns an
 3575: @dfn{execution token (xt)} corresponding to the @dfn{definition} of the
 3576: word, and that the text interpreter executes the xt. Often, the terms
 3577: @dfn{word} and @dfn{definition} are used interchangeably.
 3578: @item
 3579: If the text interpreter fails to find a match in the name dictionary, it
 3580: tries to treat the group of characters as a number in the current number
 3581: base (when you start up Forth, the current number base is base 10). If
 3582: the group of characters legitimately represents a number, the text
 3583: interpreter pushes the number onto a stack (we'll learn more about that
 3584: in the next section).
 3585: @end itemize
 3586: 
 3587: If the text interpreter is unable to do either of these things with any
 3588: group of characters, it discards the group of characters and the rest of
 3589: the line, then prints an error message. If the text interpreter reaches
 3590: the end of the line without error, it prints the status message ``@code{ ok}''
 3591: followed by carriage-return.
 3592: 
 3593: This is the simplest command we can give to the text interpreter:
 3594: 
 3595: @example
 3596: @key{RET}  ok
 3597: @end example
 3598: 
 3599: The text interpreter did everything we asked it to do (nothing) without
 3600: an error, so it said that everything is ``@code{ ok}''. Try a slightly longer
 3601: command:
 3602: 
 3603: @example
 3604: @kbd{12 dup fred dup@key{RET}}
 3605: *the terminal*:3: Undefined word
 3606: 12 dup >>>fred<<< dup
 3607: Backtrace:
 3608: $2A95B42A20 throw 
 3609: $2A95B57FB8 no.extensions 
 3610: @end example
 3611: 
 3612: When you press the carriage-return key, the text interpreter starts to
 3613: work its way along the line:
 3614: 
 3615: @itemize @bullet
 3616: @item
 3617: When it gets to the space after the @code{2}, it takes the group of
 3618: characters @code{12} and looks them up in the name
 3619: dictionary@footnote{We can't tell if it found them or not, but assume
 3620: for now that it did not}. There is no match for this group of characters
 3621: in the name dictionary, so it tries to treat them as a number. It is
 3622: able to do this successfully, so it puts the number, 12, ``on the stack''
 3623: (whatever that means).
 3624: @item
 3625: The text interpreter resumes scanning the line and gets the next group
 3626: of characters, @code{dup}. It looks it up in the name dictionary and
 3627: (you'll have to take my word for this) finds it, and executes the word
 3628: @code{dup} (whatever that means).
 3629: @item
 3630: Once again, the text interpreter resumes scanning the line and gets the
 3631: group of characters @code{fred}. It looks them up in the name
 3632: dictionary, but can't find them. It tries to treat them as a number, but
 3633: they don't represent any legal number.
 3634: @end itemize
 3635: 
 3636: At this point, the text interpreter gives up and prints an error
 3637: message. The error message shows exactly how far the text interpreter
 3638: got in processing the line. In particular, it shows that the text
 3639: interpreter made no attempt to do anything with the final character
 3640: group, @code{dup}, even though we have good reason to believe that the
 3641: text interpreter would have no problem looking that word up and
 3642: executing it a second time.
 3643: 
 3644: 
 3645: @comment ----------------------------------------------
 3646: @node Stacks and Postfix notation, Your first definition, Introducing the Text Interpreter, Introduction
 3647: @section Stacks, postfix notation and parameter passing
 3648: @cindex text interpreter
 3649: @cindex outer interpreter
 3650: 
 3651: In procedural programming languages (like C and Pascal), the
 3652: building-block of programs is the @dfn{function} or @dfn{procedure}. These
 3653: functions or procedures are called with @dfn{explicit parameters}. For
 3654: example, in C we might write:
 3655: 
 3656: @example
 3657: total = total + new_volume(length,height,depth);
 3658: @end example
 3659: 
 3660: @noindent
 3661: where new_volume is a function-call to another piece of code, and total,
 3662: length, height and depth are all variables. length, height and depth are
 3663: parameters to the function-call.
 3664: 
 3665: In Forth, the equivalent of the function or procedure is the
 3666: @dfn{definition} and parameters are implicitly passed between
 3667: definitions using a shared stack that is visible to the
 3668: programmer. Although Forth does support variables, the existence of the
 3669: stack means that they are used far less often than in most other
 3670: programming languages. When the text interpreter encounters a number, it
 3671: will place (@dfn{push}) it on the stack. There are several stacks (the
 3672: actual number is implementation-dependent ...) and the particular stack
 3673: used for any operation is implied unambiguously by the operation being
 3674: performed. The stack used for all integer operations is called the @dfn{data
 3675: stack} and, since this is the stack used most commonly, references to
 3676: ``the data stack'' are often abbreviated to ``the stack''.
 3677: 
 3678: The stacks have a last-in, first-out (LIFO) organisation. If you type:
 3679: 
 3680: @example
 3681: @kbd{1 2 3@key{RET}}  ok
 3682: @end example
 3683: 
 3684: Then this instructs the text interpreter to placed three numbers on the
 3685: (data) stack. An analogy for the behaviour of the stack is to take a
 3686: pack of playing cards and deal out the ace (1), 2 and 3 into a pile on
 3687: the table. The 3 was the last card onto the pile (``last-in'') and if
 3688: you take a card off the pile then, unless you're prepared to fiddle a
 3689: bit, the card that you take off will be the 3 (``first-out''). The
 3690: number that will be first-out of the stack is called the @dfn{top of
 3691: stack}, which
 3692: @cindex TOS definition
 3693: is often abbreviated to @dfn{TOS}.
 3694: 
 3695: To understand how parameters are passed in Forth, consider the
 3696: behaviour of the definition @code{+} (pronounced ``plus''). You will not
 3697: be surprised to learn that this definition performs addition. More
 3698: precisely, it adds two number together and produces a result. Where does
 3699: it get the two numbers from? It takes the top two numbers off the
 3700: stack. Where does it place the result? On the stack. You can act-out the
 3701: behaviour of @code{+} with your playing cards like this:
 3702: 
 3703: @itemize @bullet
 3704: @item
 3705: Pick up two cards from the stack on the table
 3706: @item
 3707: Stare at them intently and ask yourself ``what @i{is} the sum of these two
 3708: numbers''
 3709: @item
 3710: Decide that the answer is 5
 3711: @item
 3712: Shuffle the two cards back into the pack and find a 5
 3713: @item
 3714: Put a 5 on the remaining ace that's on the table.
 3715: @end itemize
 3716: 
 3717: If you don't have a pack of cards handy but you do have Forth running,
 3718: you can use the definition @code{.s} to show the current state of the stack,
 3719: without affecting the stack. Type:
 3720: 
 3721: @example
 3722: @kbd{clearstacks 1 2 3@key{RET}} ok
 3723: @kbd{.s@key{RET}} <3> 1 2 3  ok
 3724: @end example
 3725: 
 3726: The text interpreter looks up the word @code{clearstacks} and executes
 3727: it; it tidies up the stacks and removes any entries that may have been
 3728: left on it by earlier examples. The text interpreter pushes each of the
 3729: three numbers in turn onto the stack. Finally, the text interpreter
 3730: looks up the word @code{.s} and executes it. The effect of executing
 3731: @code{.s} is to print the ``<3>'' (the total number of items on the stack)
 3732: followed by a list of all the items on the stack; the item on the far
 3733: right-hand side is the TOS.
 3734: 
 3735: You can now type:
 3736: 
 3737: @example
 3738: @kbd{+ .s@key{RET}} <2> 1 5  ok
 3739: @end example
 3740: 
 3741: @noindent
 3742: which is correct; there are now 2 items on the stack and the result of
 3743: the addition is 5.
 3744: 
 3745: If you're playing with cards, try doing a second addition: pick up the
 3746: two cards, work out that their sum is 6, shuffle them into the pack,
 3747: look for a 6 and place that on the table. You now have just one item on
 3748: the stack. What happens if you try to do a third addition? Pick up the
 3749: first card, pick up the second card -- ah! There is no second card. This
 3750: is called a @dfn{stack underflow} and consitutes an error. If you try to
 3751: do the same thing with Forth it often reports an error (probably a Stack
 3752: Underflow or an Invalid Memory Address error).
 3753: 
 3754: The opposite situation to a stack underflow is a @dfn{stack overflow},
 3755: which simply accepts that there is a finite amount of storage space
 3756: reserved for the stack. To stretch the playing card analogy, if you had
 3757: enough packs of cards and you piled the cards up on the table, you would
 3758: eventually be unable to add another card; you'd hit the ceiling. Gforth
 3759: allows you to set the maximum size of the stacks. In general, the only
 3760: time that you will get a stack overflow is because a definition has a
 3761: bug in it and is generating data on the stack uncontrollably.
 3762: 
 3763: There's one final use for the playing card analogy. If you model your
 3764: stack using a pack of playing cards, the maximum number of items on
 3765: your stack will be 52 (I assume you didn't use the Joker). The maximum
 3766: @i{value} of any item on the stack is 13 (the King). In fact, the only
 3767: possible numbers are positive integer numbers 1 through 13; you can't
 3768: have (for example) 0 or 27 or 3.52 or -2. If you change the way you
 3769: think about some of the cards, you can accommodate different
 3770: numbers. For example, you could think of the Jack as representing 0,
 3771: the Queen as representing -1 and the King as representing -2. Your
 3772: @i{range} remains unchanged (you can still only represent a total of 13
 3773: numbers) but the numbers that you can represent are -2 through 10.
 3774: 
 3775: In that analogy, the limit was the amount of information that a single
 3776: stack entry could hold, and Forth has a similar limit. In Forth, the
 3777: size of a stack entry is called a @dfn{cell}. The actual size of a cell is
 3778: implementation dependent and affects the maximum value that a stack
 3779: entry can hold. A Standard Forth provides a cell size of at least
 3780: 16-bits, and most desktop systems use a cell size of 32-bits.
 3781: 
 3782: Forth does not do any type checking for you, so you are free to
 3783: manipulate and combine stack items in any way you wish. A convenient way
 3784: of treating stack items is as 2's complement signed integers, and that
 3785: is what Standard words like @code{+} do. Therefore you can type:
 3786: 
 3787: @example
 3788: @kbd{-5 12 + .s@key{RET}} <1> 7  ok
 3789: @end example
 3790: 
 3791: If you use numbers and definitions like @code{+} in order to turn Forth
 3792: into a great big pocket calculator, you will realise that it's rather
 3793: different from a normal calculator. Rather than typing 2 + 3 = you had
 3794: to type 2 3 + (ignore the fact that you had to use @code{.s} to see the
 3795: result). The terminology used to describe this difference is to say that
 3796: your calculator uses @dfn{Infix Notation} (parameters and operators are
 3797: mixed) whilst Forth uses @dfn{Postfix Notation} (parameters and
 3798: operators are separate), also called @dfn{Reverse Polish Notation}.
 3799: 
 3800: Whilst postfix notation might look confusing to begin with, it has
 3801: several important advantages:
 3802: 
 3803: @itemize @bullet
 3804: @item
 3805: it is unambiguous
 3806: @item
 3807: it is more concise
 3808: @item
 3809: it fits naturally with a stack-based system
 3810: @end itemize
 3811: 
 3812: To examine these claims in more detail, consider these sums:
 3813: 
 3814: @example
 3815: 6 + 5 * 4 =
 3816: 4 * 5 + 6 =
 3817: @end example
 3818: 
 3819: If you're just learning maths or your maths is very rusty, you will
 3820: probably come up with the answer 44 for the first and 26 for the
 3821: second. If you are a bit of a whizz at maths you will remember the
 3822: @i{convention} that multiplication takes precendence over addition, and
 3823: you'd come up with the answer 26 both times. To explain the answer 26
 3824: to someone who got the answer 44, you'd probably rewrite the first sum
 3825: like this:
 3826: 
 3827: @example
 3828: 6 + (5 * 4) =
 3829: @end example
 3830: 
 3831: If what you really wanted was to perform the addition before the
 3832: multiplication, you would have to use parentheses to force it.
 3833: 
 3834: If you did the first two sums on a pocket calculator you would probably
 3835: get the right answers, unless you were very cautious and entered them using
 3836: these keystroke sequences:
 3837: 
 3838: 6 + 5 = * 4 =
 3839: 4 * 5 = + 6 =
 3840: 
 3841: Postfix notation is unambiguous because the order that the operators
 3842: are applied is always explicit; that also means that parentheses are
 3843: never required. The operators are @i{active} (the act of quoting the
 3844: operator makes the operation occur) which removes the need for ``=''.
 3845: 
 3846: The sum 6 + 5 * 4 can be written (in postfix notation) in two
 3847: equivalent ways:
 3848: 
 3849: @example
 3850: 6 5 4 * +      or:
 3851: 5 4 * 6 +
 3852: @end example
 3853: 
 3854: An important thing that you should notice about this notation is that
 3855: the @i{order} of the numbers does not change; if you want to subtract
 3856: 2 from 10 you type @code{10 2 -}.
 3857: 
 3858: The reason that Forth uses postfix notation is very simple to explain: it
 3859: makes the implementation extremely simple, and it follows naturally from
 3860: using the stack as a mechanism for passing parameters. Another way of
 3861: thinking about this is to realise that all Forth definitions are
 3862: @i{active}; they execute as they are encountered by the text
 3863: interpreter. The result of this is that the syntax of Forth is trivially
 3864: simple.
 3865: 
 3866: 
 3867: 
 3868: @comment ----------------------------------------------
 3869: @node Your first definition, How does that work?, Stacks and Postfix notation, Introduction
 3870: @section Your first Forth definition
 3871: @cindex first definition
 3872: 
 3873: Until now, the examples we've seen have been trivial; we've just been
 3874: using Forth as a bigger-than-pocket calculator. Also, each calculation
 3875: we've shown has been a ``one-off'' -- to repeat it we'd need to type it in
 3876: again@footnote{That's not quite true. If you press the up-arrow key on
 3877: your keyboard you should be able to scroll back to any earlier command,
 3878: edit it and re-enter it.} In this section we'll see how to add new
 3879: words to Forth's vocabulary.
 3880: 
 3881: The easiest way to create a new word is to use a @dfn{colon
 3882: definition}. We'll define a few and try them out before worrying too
 3883: much about how they work. Try typing in these examples; be careful to
 3884: copy the spaces accurately:
 3885: 
 3886: @example
 3887: : add-two 2 + . ;
 3888: : greet ." Hello and welcome" ;
 3889: : demo 5 add-two ;
 3890: @end example
 3891: 
 3892: @noindent
 3893: Now try them out:
 3894: 
 3895: @example
 3896: @kbd{greet@key{RET}} Hello and welcome  ok
 3897: @kbd{greet greet@key{RET}} Hello and welcomeHello and welcome  ok
 3898: @kbd{4 add-two@key{RET}} 6  ok
 3899: @kbd{demo@key{RET}} 7  ok
 3900: @kbd{9 greet demo add-two@key{RET}} Hello and welcome7 11  ok
 3901: @end example
 3902: 
 3903: The first new thing that we've introduced here is the pair of words
 3904: @code{:} and @code{;}. These are used to start and terminate a new
 3905: definition, respectively. The first word after the @code{:} is the name
 3906: for the new definition.
 3907: 
 3908: As you can see from the examples, a definition is built up of words that
 3909: have already been defined; Forth makes no distinction between
 3910: definitions that existed when you started the system up, and those that
 3911: you define yourself.
 3912: 
 3913: The examples also introduce the words @code{.} (dot), @code{."}
 3914: (dot-quote) and @code{dup} (dewp). Dot takes the value from the top of
 3915: the stack and displays it. It's like @code{.s} except that it only
 3916: displays the top item of the stack and it is destructive; after it has
 3917: executed, the number is no longer on the stack. There is always one
 3918: space printed after the number, and no spaces before it. Dot-quote
 3919: defines a string (a sequence of characters) that will be printed when
 3920: the word is executed. The string can contain any printable characters
 3921: except @code{"}. A @code{"} has a special function; it is not a Forth
 3922: word but it acts as a delimiter (the way that delimiters work is
 3923: described in the next section). Finally, @code{dup} duplicates the value
 3924: at the top of the stack. Try typing @code{5 dup .s} to see what it does.
 3925: 
 3926: We already know that the text interpreter searches through the
 3927: dictionary to locate names. If you've followed the examples earlier, you
 3928: will already have a definition called @code{add-two}. Lets try modifying
 3929: it by typing in a new definition:
 3930: 
 3931: @example
 3932: @kbd{: add-two dup . ." + 2 =" 2 + . ;@key{RET}} redefined add-two  ok
 3933: @end example
 3934: 
 3935: Forth recognised that we were defining a word that already exists, and
 3936: printed a message to warn us of that fact. Let's try out the new
 3937: definition:
 3938: 
 3939: @example
 3940: @kbd{9 add-two@key{RET}} 9 + 2 =11  ok
 3941: @end example
 3942: 
 3943: @noindent
 3944: All that we've actually done here, though, is to create a new
 3945: definition, with a particular name. The fact that there was already a
 3946: definition with the same name did not make any difference to the way
 3947: that the new definition was created (except that Forth printed a warning
 3948: message). The old definition of add-two still exists (try @code{demo}
 3949: again to see that this is true). Any new definition will use the new
 3950: definition of @code{add-two}, but old definitions continue to use the
 3951: version that already existed at the time that they were @code{compiled}.
 3952: 
 3953: Before you go on to the next section, try defining and redefining some
 3954: words of your own.
 3955: 
 3956: @comment ----------------------------------------------
 3957: @node How does that work?, Forth is written in Forth, Your first definition, Introduction
 3958: @section How does that work?
 3959: @cindex parsing words
 3960: 
 3961: @c That's pretty deep (IMO way too deep) for an introduction. - anton
 3962: 
 3963: @c Is it a good idea to talk about the interpretation semantics of a
 3964: @c number? We don't have an xt to go along with it. - anton
 3965: 
 3966: @c Now that I have eliminated execution semantics, I wonder if it would not
 3967: @c be better to keep them (or add run-time semantics), to make it easier to
 3968: @c explain what compilation semantics usually does. - anton
 3969: 
 3970: @c nac-> I removed the term ``default compilation sematics'' from the
 3971: @c introductory chapter. Removing ``execution semantics'' was making
 3972: @c everything simpler to explain, then I think the use of this term made
 3973: @c everything more complex again. I replaced it with ``default
 3974: @c semantics'' (which is used elsewhere in the manual) by which I mean
 3975: @c ``a definition that has neither the immediate nor the compile-only
 3976: @c flag set''.
 3977: 
 3978: @c anton: I have eliminated default semantics (except in one place where it
 3979: @c means "default interpretation and compilation semantics"), because it
 3980: @c makes no sense in the presence of combined words.  I reverted to
 3981: @c "execution semantics" where necessary.
 3982: 
 3983: @c nac-> I reworded big chunks of the ``how does that work''
 3984: @c section (and, unusually for me, I think I even made it shorter!).  See
 3985: @c what you think -- I know I have not addressed your primary concern
 3986: @c that it is too heavy-going for an introduction. From what I understood
 3987: @c of your course notes it looks as though they might be a good framework. 
 3988: @c Things that I've tried to capture here are some things that came as a
 3989: @c great revelation here when I first understood them. Also, I like the
 3990: @c fact that a very simple code example shows up almost all of the issues
 3991: @c that you need to understand to see how Forth works. That's unique and
 3992: @c worthwhile to emphasise.
 3993: 
 3994: @c anton: I think it's a good idea to present the details, especially those
 3995: @c that you found to be a revelation, and probably the tutorial tries to be
 3996: @c too superficial and does not get some of the things across that make
 3997: @c Forth special.  I do believe that most of the time these things should
 3998: @c be discussed at the end of a section or in separate sections instead of
 3999: @c in the middle of a section (e.g., the stuff you added in "User-defined
 4000: @c defining words" leads in a completely different direction from the rest
 4001: @c of the section).
 4002: 
 4003: Now we're going to take another look at the definition of @code{add-two}
 4004: from the previous section. From our knowledge of the way that the text
 4005: interpreter works, we would have expected this result when we tried to
 4006: define @code{add-two}:
 4007: 
 4008: @example
 4009: @kbd{: add-two 2 + . ;@key{RET}}
 4010: *the terminal*:4: Undefined word
 4011: : >>>add-two<<< 2 + . ;
 4012: @end example
 4013: 
 4014: The reason that this didn't happen is bound up in the way that @code{:}
 4015: works. The word @code{:} does two special things. The first special
 4016: thing that it does prevents the text interpreter from ever seeing the
 4017: characters @code{add-two}. The text interpreter uses a variable called
 4018: @cindex modifying >IN
 4019: @code{>IN} (pronounced ``to-in'') to keep track of where it is in the
 4020: input line. When it encounters the word @code{:} it behaves in exactly
 4021: the same way as it does for any other word; it looks it up in the name
 4022: dictionary, finds its xt and executes it. When @code{:} executes, it
 4023: looks at the input buffer, finds the word @code{add-two} and advances the
 4024: value of @code{>IN} to point past it. It then does some other stuff
 4025: associated with creating the new definition (including creating an entry
 4026: for @code{add-two} in the name dictionary). When the execution of @code{:}
 4027: completes, control returns to the text interpreter, which is oblivious
 4028: to the fact that it has been tricked into ignoring part of the input
 4029: line.
 4030: 
 4031: @cindex parsing words
 4032: Words like @code{:} -- words that advance the value of @code{>IN} and so
 4033: prevent the text interpreter from acting on the whole of the input line
 4034: -- are called @dfn{parsing words}.
 4035: 
 4036: @cindex @code{state} - effect on the text interpreter
 4037: @cindex text interpreter - effect of state
 4038: The second special thing that @code{:} does is change the value of a
 4039: variable called @code{state}, which affects the way that the text
 4040: interpreter behaves. When Gforth starts up, @code{state} has the value
 4041: 0, and the text interpreter is said to be @dfn{interpreting}. During a
 4042: colon definition (started with @code{:}), @code{state} is set to -1 and
 4043: the text interpreter is said to be @dfn{compiling}.
 4044: 
 4045: In this example, the text interpreter is compiling when it processes the
 4046: string ``@code{2 + . ;}''. It still breaks the string down into
 4047: character sequences in the same way. However, instead of pushing the
 4048: number @code{2} onto the stack, it lays down (@dfn{compiles}) some magic
 4049: into the definition of @code{add-two} that will make the number @code{2} get
 4050: pushed onto the stack when @code{add-two} is @dfn{executed}. Similarly,
 4051: the behaviours of @code{+} and @code{.} are also compiled into the
 4052: definition.
 4053: 
 4054: One category of words don't get compiled. These so-called @dfn{immediate
 4055: words} get executed (performed @i{now}) regardless of whether the text
 4056: interpreter is interpreting or compiling. The word @code{;} is an
 4057: immediate word. Rather than being compiled into the definition, it
 4058: executes. Its effect is to terminate the current definition, which
 4059: includes changing the value of @code{state} back to 0.
 4060: 
 4061: When you execute @code{add-two}, it has a @dfn{run-time effect} that is
 4062: exactly the same as if you had typed @code{2 + . @key{RET}} outside of a
 4063: definition.
 4064: 
 4065: In Forth, every word or number can be described in terms of two
 4066: properties:
 4067: 
 4068: @itemize @bullet
 4069: @item
 4070: @cindex interpretation semantics
 4071: Its @dfn{interpretation semantics} describe how it will behave when the
 4072: text interpreter encounters it in @dfn{interpret} state. The
 4073: interpretation semantics of a word are represented by an @dfn{execution
 4074: token}.
 4075: @item
 4076: @cindex compilation semantics
 4077: Its @dfn{compilation semantics} describe how it will behave when the
 4078: text interpreter encounters it in @dfn{compile} state. The compilation
 4079: semantics of a word are represented in an implementation-dependent way;
 4080: Gforth uses a @dfn{compilation token}.
 4081: @end itemize
 4082: 
 4083: @noindent
 4084: Numbers are always treated in a fixed way:
 4085: 
 4086: @itemize @bullet
 4087: @item
 4088: When the number is @dfn{interpreted}, its behaviour is to push the
 4089: number onto the stack.
 4090: @item
 4091: When the number is @dfn{compiled}, a piece of code is appended to the
 4092: current definition that pushes the number when it runs. (In other words,
 4093: the compilation semantics of a number are to postpone its interpretation
 4094: semantics until the run-time of the definition that it is being compiled
 4095: into.)
 4096: @end itemize
 4097: 
 4098: Words don't behave in such a regular way, but most have @i{default
 4099: semantics} which means that they behave like this:
 4100: 
 4101: @itemize @bullet
 4102: @item
 4103: The @dfn{interpretation semantics} of the word are to do something useful.
 4104: @item
 4105: The @dfn{compilation semantics} of the word are to append its
 4106: @dfn{interpretation semantics} to the current definition (so that its
 4107: run-time behaviour is to do something useful).
 4108: @end itemize
 4109: 
 4110: @cindex immediate words
 4111: The actual behaviour of any particular word can be controlled by using
 4112: the words @code{immediate} and @code{compile-only} when the word is
 4113: defined. These words set flags in the name dictionary entry of the most
 4114: recently defined word, and these flags are retrieved by the text
 4115: interpreter when it finds the word in the name dictionary.
 4116: 
 4117: A word that is marked as @dfn{immediate} has compilation semantics that
 4118: are identical to its interpretation semantics. In other words, it
 4119: behaves like this:
 4120: 
 4121: @itemize @bullet
 4122: @item
 4123: The @dfn{interpretation semantics} of the word are to do something useful.
 4124: @item
 4125: The @dfn{compilation semantics} of the word are to do something useful
 4126: (and actually the same thing); i.e., it is executed during compilation.
 4127: @end itemize
 4128: 
 4129: Marking a word as @dfn{compile-only} prohibits the text interpreter from
 4130: performing the interpretation semantics of the word directly; an attempt
 4131: to do so will generate an error. It is never necessary to use
 4132: @code{compile-only} (and it is not even part of ANS Forth, though it is
 4133: provided by many implementations) but it is good etiquette to apply it
 4134: to a word that will not behave correctly (and might have unexpected
 4135: side-effects) in interpret state. For example, it is only legal to use
 4136: the conditional word @code{IF} within a definition. If you forget this
 4137: and try to use it elsewhere, the fact that (in Gforth) it is marked as
 4138: @code{compile-only} allows the text interpreter to generate a helpful
 4139: error message rather than subjecting you to the consequences of your
 4140: folly.
 4141: 
 4142: This example shows the difference between an immediate and a
 4143: non-immediate word:
 4144: 
 4145: @example
 4146: : show-state state @@ . ;
 4147: : show-state-now show-state ; immediate
 4148: : word1 show-state ;
 4149: : word2 show-state-now ;
 4150: @end example
 4151: 
 4152: The word @code{immediate} after the definition of @code{show-state-now}
 4153: makes that word an immediate word. These definitions introduce a new
 4154: word: @code{@@} (pronounced ``fetch''). This word fetches the value of a
 4155: variable, and leaves it on the stack. Therefore, the behaviour of
 4156: @code{show-state} is to print a number that represents the current value
 4157: of @code{state}.
 4158: 
 4159: When you execute @code{word1}, it prints the number 0, indicating that
 4160: the system is interpreting. When the text interpreter compiled the
 4161: definition of @code{word1}, it encountered @code{show-state} whose
 4162: compilation semantics are to append its interpretation semantics to the
 4163: current definition. When you execute @code{word1}, it performs the
 4164: interpretation semantics of @code{show-state}.  At the time that @code{word1}
 4165: (and therefore @code{show-state}) are executed, the system is
 4166: interpreting.
 4167: 
 4168: When you pressed @key{RET} after entering the definition of @code{word2},
 4169: you should have seen the number -1 printed, followed by ``@code{
 4170: ok}''. When the text interpreter compiled the definition of
 4171: @code{word2}, it encountered @code{show-state-now}, an immediate word,
 4172: whose compilation semantics are therefore to perform its interpretation
 4173: semantics. It is executed straight away (even before the text
 4174: interpreter has moved on to process another group of characters; the
 4175: @code{;} in this example). The effect of executing it are to display the
 4176: value of @code{state} @i{at the time that the definition of}
 4177: @code{word2} @i{is being defined}. Printing -1 demonstrates that the
 4178: system is compiling at this time. If you execute @code{word2} it does
 4179: nothing at all.
 4180: 
 4181: @cindex @code{."}, how it works
 4182: Before leaving the subject of immediate words, consider the behaviour of
 4183: @code{."} in the definition of @code{greet}, in the previous
 4184: section. This word is both a parsing word and an immediate word. Notice
 4185: that there is a space between @code{."} and the start of the text
 4186: @code{Hello and welcome}, but that there is no space between the last
 4187: letter of @code{welcome} and the @code{"} character. The reason for this
 4188: is that @code{."} is a Forth word; it must have a space after it so that
 4189: the text interpreter can identify it. The @code{"} is not a Forth word;
 4190: it is a @dfn{delimiter}. The examples earlier show that, when the string
 4191: is displayed, there is neither a space before the @code{H} nor after the
 4192: @code{e}. Since @code{."} is an immediate word, it executes at the time
 4193: that @code{greet} is defined. When it executes, its behaviour is to
 4194: search forward in the input line looking for the delimiter. When it
 4195: finds the delimiter, it updates @code{>IN} to point past the
 4196: delimiter. It also compiles some magic code into the definition of
 4197: @code{greet}; the xt of a run-time routine that prints a text string. It
 4198: compiles the string @code{Hello and welcome} into memory so that it is
 4199: available to be printed later. When the text interpreter gains control,
 4200: the next word it finds in the input stream is @code{;} and so it
 4201: terminates the definition of @code{greet}.
 4202: 
 4203: 
 4204: @comment ----------------------------------------------
 4205: @node Forth is written in Forth, Review - elements of a Forth system, How does that work?, Introduction
 4206: @section Forth is written in Forth
 4207: @cindex structure of Forth programs
 4208: 
 4209: When you start up a Forth compiler, a large number of definitions
 4210: already exist. In Forth, you develop a new application using bottom-up
 4211: programming techniques to create new definitions that are defined in
 4212: terms of existing definitions. As you create each definition you can
 4213: test and debug it interactively.
 4214: 
 4215: If you have tried out the examples in this section, you will probably
 4216: have typed them in by hand; when you leave Gforth, your definitions will
 4217: be lost. You can avoid this by using a text editor to enter Forth source
 4218: code into a file, and then loading code from the file using
 4219: @code{include} (@pxref{Forth source files}). A Forth source file is
 4220: processed by the text interpreter, just as though you had typed it in by
 4221: hand@footnote{Actually, there are some subtle differences -- see
 4222: @ref{The Text Interpreter}.}.
 4223: 
 4224: Gforth also supports the traditional Forth alternative to using text
 4225: files for program entry (@pxref{Blocks}).
 4226: 
 4227: In common with many, if not most, Forth compilers, most of Gforth is
 4228: actually written in Forth. All of the @file{.fs} files in the
 4229: installation directory@footnote{For example,
 4230: @file{/usr/local/share/gforth...}} are Forth source files, which you can
 4231: study to see examples of Forth programming.
 4232: 
 4233: Gforth maintains a history file that records every line that you type to
 4234: the text interpreter. This file is preserved between sessions, and is
 4235: used to provide a command-line recall facility. If you enter long
 4236: definitions by hand, you can use a text editor to paste them out of the
 4237: history file into a Forth source file for reuse at a later time
 4238: (for more information @pxref{Command-line editing}).
 4239: 
 4240: 
 4241: @comment ----------------------------------------------
 4242: @node Review - elements of a Forth system, Where to go next, Forth is written in Forth, Introduction
 4243: @section Review - elements of a Forth system
 4244: @cindex elements of a Forth system
 4245: 
 4246: To summarise this chapter:
 4247: 
 4248: @itemize @bullet
 4249: @item
 4250: Forth programs use @dfn{factoring} to break a problem down into small
 4251: fragments called @dfn{words} or @dfn{definitions}.
 4252: @item
 4253: Forth program development is an interactive process.
 4254: @item
 4255: The main command loop that accepts input, and controls both
 4256: interpretation and compilation, is called the @dfn{text interpreter}
 4257: (also known as the @dfn{outer interpreter}).
 4258: @item
 4259: Forth has a very simple syntax, consisting of words and numbers
 4260: separated by spaces or carriage-return characters. Any additional syntax
 4261: is imposed by @dfn{parsing words}.
 4262: @item
 4263: Forth uses a stack to pass parameters between words. As a result, it
 4264: uses postfix notation.
 4265: @item
 4266: To use a word that has previously been defined, the text interpreter
 4267: searches for the word in the @dfn{name dictionary}.
 4268: @item
 4269: Words have @dfn{interpretation semantics} and @dfn{compilation semantics}.
 4270: @item
 4271: The text interpreter uses the value of @code{state} to select between
 4272: the use of the @dfn{interpretation semantics} and the  @dfn{compilation
 4273: semantics} of a word that it encounters.
 4274: @item
 4275: The relationship between the @dfn{interpretation semantics} and
 4276: @dfn{compilation semantics} for a word
 4277: depend upon the way in which the word was defined (for example, whether
 4278: it is an @dfn{immediate} word).
 4279: @item
 4280: Forth definitions can be implemented in Forth (called @dfn{high-level
 4281: definitions}) or in some other way (usually a lower-level language and
 4282: as a result often called @dfn{low-level definitions}, @dfn{code
 4283: definitions} or @dfn{primitives}).
 4284: @item
 4285: Many Forth systems are implemented mainly in Forth.
 4286: @end itemize
 4287: 
 4288: 
 4289: @comment ----------------------------------------------
 4290: @node Where to go next, Exercises, Review - elements of a Forth system, Introduction
 4291: @section Where To Go Next
 4292: @cindex where to go next
 4293: 
 4294: Amazing as it may seem, if you have read (and understood) this far, you
 4295: know almost all the fundamentals about the inner workings of a Forth
 4296: system. You certainly know enough to be able to read and understand the
 4297: rest of this manual and the ANS Forth document, to learn more about the
 4298: facilities that Forth in general and Gforth in particular provide. Even
 4299: scarier, you know almost enough to implement your own Forth system.
 4300: However, that's not a good idea just yet... better to try writing some
 4301: programs in Gforth.
 4302: 
 4303: Forth has such a rich vocabulary that it can be hard to know where to
 4304: start in learning it. This section suggests a few sets of words that are
 4305: enough to write small but useful programs. Use the word index in this
 4306: document to learn more about each word, then try it out and try to write
 4307: small definitions using it. Start by experimenting with these words:
 4308: 
 4309: @itemize @bullet
 4310: @item
 4311: Arithmetic: @code{+ - * / /MOD */ ABS INVERT}
 4312: @item
 4313: Comparison: @code{MIN MAX =}
 4314: @item
 4315: Logic: @code{AND OR XOR NOT}
 4316: @item
 4317: Stack manipulation: @code{DUP DROP SWAP OVER}
 4318: @item
 4319: Loops and decisions: @code{IF ELSE ENDIF ?DO I LOOP}
 4320: @item
 4321: Input/Output: @code{. ." EMIT CR KEY}
 4322: @item
 4323: Defining words: @code{: ; CREATE}
 4324: @item
 4325: Memory allocation words: @code{ALLOT ,}
 4326: @item
 4327: Tools: @code{SEE WORDS .S MARKER}
 4328: @end itemize
 4329: 
 4330: When you have mastered those, go on to:
 4331: 
 4332: @itemize @bullet
 4333: @item
 4334: More defining words: @code{VARIABLE CONSTANT VALUE TO CREATE DOES>}
 4335: @item
 4336: Memory access: @code{@@ !}
 4337: @end itemize
 4338: 
 4339: When you have mastered these, there's nothing for it but to read through
 4340: the whole of this manual and find out what you've missed.
 4341: 
 4342: @comment ----------------------------------------------
 4343: @node Exercises,  , Where to go next, Introduction
 4344: @section Exercises
 4345: @cindex exercises
 4346: 
 4347: TODO: provide a set of programming excercises linked into the stuff done
 4348: already and into other sections of the manual. Provide solutions to all
 4349: the exercises in a .fs file in the distribution.
 4350: 
 4351: @c Get some inspiration from Starting Forth and Kelly&Spies.
 4352: 
 4353: @c excercises:
 4354: @c 1. take inches and convert to feet and inches.
 4355: @c 2. take temperature and convert from fahrenheight to celcius;
 4356: @c    may need to care about symmetric vs floored??
 4357: @c 3. take input line and do character substitution
 4358: @c    to encipher or decipher
 4359: @c 4. as above but work on a file for in and out
 4360: @c 5. take input line and convert to pig-latin 
 4361: @c
 4362: @c thing of sets of things to exercise then come up with
 4363: @c problems that need those things.
 4364: 
 4365: 
 4366: @c ******************************************************************
 4367: @node Words, Error messages, Introduction, Top
 4368: @chapter Forth Words
 4369: @cindex words
 4370: 
 4371: @menu
 4372: * Notation::                    
 4373: * Case insensitivity::          
 4374: * Comments::                    
 4375: * Boolean Flags::               
 4376: * Arithmetic::                  
 4377: * Stack Manipulation::          
 4378: * Memory::                      
 4379: * Control Structures::          
 4380: * Defining Words::              
 4381: * Interpretation and Compilation Semantics::  
 4382: * Tokens for Words::            
 4383: * Compiling words::             
 4384: * The Text Interpreter::        
 4385: * The Input Stream::            
 4386: * Word Lists::                  
 4387: * Environmental Queries::       
 4388: * Files::                       
 4389: * Blocks::                      
 4390: * Other I/O::                   
 4391: * OS command line arguments::   
 4392: * Locals::                      
 4393: * Structures::                  
 4394: * Object-oriented Forth::       
 4395: * Programming Tools::           
 4396: * C Interface::                 
 4397: * Assembler and Code Words::    
 4398: * Threading Words::             
 4399: * Passing Commands to the OS::  
 4400: * Keeping track of Time::       
 4401: * Miscellaneous Words::         
 4402: @end menu
 4403: 
 4404: @node Notation, Case insensitivity, Words, Words
 4405: @section Notation
 4406: @cindex notation of glossary entries
 4407: @cindex format of glossary entries
 4408: @cindex glossary notation format
 4409: @cindex word glossary entry format
 4410: 
 4411: The Forth words are described in this section in the glossary notation
 4412: that has become a de-facto standard for Forth texts:
 4413: 
 4414: @format
 4415: @i{word}     @i{Stack effect}   @i{wordset}   @i{pronunciation}
 4416: @end format
 4417: @i{Description}
 4418: 
 4419: @table @var
 4420: @item word
 4421: The name of the word.
 4422: 
 4423: @item Stack effect
 4424: @cindex stack effect
 4425: The stack effect is written in the notation @code{@i{before} --
 4426: @i{after}}, where @i{before} and @i{after} describe the top of
 4427: stack entries before and after the execution of the word. The rest of
 4428: the stack is not touched by the word. The top of stack is rightmost,
 4429: i.e., a stack sequence is written as it is typed in. Note that Gforth
 4430: uses a separate floating point stack, but a unified stack
 4431: notation. Also, return stack effects are not shown in @i{stack
 4432: effect}, but in @i{Description}. The name of a stack item describes
 4433: the type and/or the function of the item. See below for a discussion of
 4434: the types.
 4435: 
 4436: All words have two stack effects: A compile-time stack effect and a
 4437: run-time stack effect. The compile-time stack-effect of most words is
 4438: @i{ -- }. If the compile-time stack-effect of a word deviates from
 4439: this standard behaviour, or the word does other unusual things at
 4440: compile time, both stack effects are shown; otherwise only the run-time
 4441: stack effect is shown.
 4442: 
 4443: Also note that in code templates or examples there can be comments in
 4444: parentheses that display the stack picture at this point; there is no
 4445: @code{--} in these places, because there is no before-after situation.
 4446: 
 4447: @cindex pronounciation of words
 4448: @item pronunciation
 4449: How the word is pronounced.
 4450: 
 4451: @cindex wordset
 4452: @cindex environment wordset
 4453: @item wordset
 4454: The ANS Forth standard is divided into several word sets. A standard
 4455: system need not support all of them. Therefore, in theory, the fewer
 4456: word sets your program uses the more portable it will be. However, we
 4457: suspect that most ANS Forth systems on personal machines will feature
 4458: all word sets. Words that are not defined in ANS Forth have
 4459: @code{gforth} or @code{gforth-internal} as word set. @code{gforth}
 4460: describes words that will work in future releases of Gforth;
 4461: @code{gforth-internal} words are more volatile. Environmental query
 4462: strings are also displayed like words; you can recognize them by the
 4463: @code{environment} in the word set field.
 4464: 
 4465: @item Description
 4466: A description of the behaviour of the word.
 4467: @end table
 4468: 
 4469: @cindex types of stack items
 4470: @cindex stack item types
 4471: The type of a stack item is specified by the character(s) the name
 4472: starts with:
 4473: 
 4474: @table @code
 4475: @item f
 4476: @cindex @code{f}, stack item type
 4477: Boolean flags, i.e. @code{false} or @code{true}.
 4478: @item c
 4479: @cindex @code{c}, stack item type
 4480: Char
 4481: @item w
 4482: @cindex @code{w}, stack item type
 4483: Cell, can contain an integer or an address
 4484: @item n
 4485: @cindex @code{n}, stack item type
 4486: signed integer
 4487: @item u
 4488: @cindex @code{u}, stack item type
 4489: unsigned integer
 4490: @item d
 4491: @cindex @code{d}, stack item type
 4492: double sized signed integer
 4493: @item ud
 4494: @cindex @code{ud}, stack item type
 4495: double sized unsigned integer
 4496: @item r
 4497: @cindex @code{r}, stack item type
 4498: Float (on the FP stack)
 4499: @item a-
 4500: @cindex @code{a_}, stack item type
 4501: Cell-aligned address
 4502: @item c-
 4503: @cindex @code{c_}, stack item type
 4504: Char-aligned address (note that a Char may have two bytes in Windows NT)
 4505: @item f-
 4506: @cindex @code{f_}, stack item type
 4507: Float-aligned address
 4508: @item df-
 4509: @cindex @code{df_}, stack item type
 4510: Address aligned for IEEE double precision float
 4511: @item sf-
 4512: @cindex @code{sf_}, stack item type
 4513: Address aligned for IEEE single precision float
 4514: @item xt
 4515: @cindex @code{xt}, stack item type
 4516: Execution token, same size as Cell
 4517: @item wid
 4518: @cindex @code{wid}, stack item type
 4519: Word list ID, same size as Cell
 4520: @item ior, wior
 4521: @cindex ior type description
 4522: @cindex wior type description
 4523: I/O result code, cell-sized.  In Gforth, you can @code{throw} iors.
 4524: @item f83name
 4525: @cindex @code{f83name}, stack item type
 4526: Pointer to a name structure
 4527: @item "
 4528: @cindex @code{"}, stack item type
 4529: string in the input stream (not on the stack). The terminating character
 4530: is a blank by default. If it is not a blank, it is shown in @code{<>}
 4531: quotes.
 4532: @end table
 4533: 
 4534: @comment ----------------------------------------------
 4535: @node Case insensitivity, Comments, Notation, Words
 4536: @section Case insensitivity
 4537: @cindex case sensitivity
 4538: @cindex upper and lower case
 4539: 
 4540: Gforth is case-insensitive; you can enter definitions and invoke
 4541: Standard words using upper, lower or mixed case (however,
 4542: @pxref{core-idef, Implementation-defined options, Implementation-defined
 4543: options}).
 4544: 
 4545: ANS Forth only @i{requires} implementations to recognise Standard words
 4546: when they are typed entirely in upper case. Therefore, a Standard
 4547: program must use upper case for all Standard words. You can use whatever
 4548: case you like for words that you define, but in a Standard program you
 4549: have to use the words in the same case that you defined them.
 4550: 
 4551: Gforth supports case sensitivity through @code{table}s (case-sensitive
 4552: wordlists, @pxref{Word Lists}).
 4553: 
 4554: Two people have asked how to convert Gforth to be case-sensitive; while
 4555: we think this is a bad idea, you can change all wordlists into tables
 4556: like this:
 4557: 
 4558: @example
 4559: ' table-find forth-wordlist wordlist-map @ !
 4560: @end example
 4561: 
 4562: Note that you now have to type the predefined words in the same case
 4563: that we defined them, which are varying.  You may want to convert them
 4564: to your favourite case before doing this operation (I won't explain how,
 4565: because if you are even contemplating doing this, you'd better have
 4566: enough knowledge of Forth systems to know this already).
 4567: 
 4568: @node Comments, Boolean Flags, Case insensitivity, Words
 4569: @section Comments
 4570: @cindex comments
 4571: 
 4572: Forth supports two styles of comment; the traditional @i{in-line} comment,
 4573: @code{(} and its modern cousin, the @i{comment to end of line}; @code{\}.
 4574: 
 4575: 
 4576: doc-(
 4577: doc-\
 4578: doc-\G
 4579: 
 4580: 
 4581: @node Boolean Flags, Arithmetic, Comments, Words
 4582: @section Boolean Flags
 4583: @cindex Boolean flags
 4584: 
 4585: A Boolean flag is cell-sized. A cell with all bits clear represents the
 4586: flag @code{false} and a flag with all bits set represents the flag
 4587: @code{true}. Words that check a flag (for example, @code{IF}) will treat
 4588: a cell that has @i{any} bit set as @code{true}.
 4589: @c on and off to Memory? 
 4590: @c true and false to "Bitwise operations" or "Numeric comparison"?
 4591: 
 4592: doc-true
 4593: doc-false
 4594: doc-on
 4595: doc-off
 4596: 
 4597: 
 4598: @node Arithmetic, Stack Manipulation, Boolean Flags, Words
 4599: @section Arithmetic
 4600: @cindex arithmetic words
 4601: 
 4602: @cindex division with potentially negative operands
 4603: Forth arithmetic is not checked, i.e., you will not hear about integer
 4604: overflow on addition or multiplication, you may hear about division by
 4605: zero if you are lucky. The operator is written after the operands, but
 4606: the operands are still in the original order. I.e., the infix @code{2-1}
 4607: corresponds to @code{2 1 -}. Forth offers a variety of division
 4608: operators. If you perform division with potentially negative operands,
 4609: you do not want to use @code{/} or @code{/mod} with its undefined
 4610: behaviour, but rather @code{fm/mod} or @code{sm/mod} (probably the
 4611: former, @pxref{Mixed precision}).
 4612: @comment TODO discuss the different division forms and the std approach
 4613: 
 4614: @menu
 4615: * Single precision::            
 4616: * Double precision::            Double-cell integer arithmetic
 4617: * Bitwise operations::          
 4618: * Numeric comparison::          
 4619: * Mixed precision::             Operations with single and double-cell integers
 4620: * Floating Point::              
 4621: @end menu
 4622: 
 4623: @node Single precision, Double precision, Arithmetic, Arithmetic
 4624: @subsection Single precision
 4625: @cindex single precision arithmetic words
 4626: 
 4627: @c !! cell undefined
 4628: 
 4629: By default, numbers in Forth are single-precision integers that are one
 4630: cell in size. They can be signed or unsigned, depending upon how you
 4631: treat them. For the rules used by the text interpreter for recognising
 4632: single-precision integers see @ref{Number Conversion}.
 4633: 
 4634: These words are all defined for signed operands, but some of them also
 4635: work for unsigned numbers: @code{+}, @code{1+}, @code{-}, @code{1-},
 4636: @code{*}.
 4637: 
 4638: doc-+
 4639: doc-1+
 4640: doc-under+
 4641: doc--
 4642: doc-1-
 4643: doc-*
 4644: doc-/
 4645: doc-mod
 4646: doc-/mod
 4647: doc-negate
 4648: doc-abs
 4649: doc-min
 4650: doc-max
 4651: doc-floored
 4652: 
 4653: 
 4654: @node Double precision, Bitwise operations, Single precision, Arithmetic
 4655: @subsection Double precision
 4656: @cindex double precision arithmetic words
 4657: 
 4658: For the rules used by the text interpreter for
 4659: recognising double-precision integers, see @ref{Number Conversion}.
 4660: 
 4661: A double precision number is represented by a cell pair, with the most
 4662: significant cell at the TOS. It is trivial to convert an unsigned single
 4663: to a double: simply push a @code{0} onto the TOS. Since numbers are
 4664: represented by Gforth using 2's complement arithmetic, converting a
 4665: signed single to a (signed) double requires sign-extension across the
 4666: most significant cell. This can be achieved using @code{s>d}. The moral
 4667: of the story is that you cannot convert a number without knowing whether
 4668: it represents an unsigned or a signed number.
 4669: 
 4670: These words are all defined for signed operands, but some of them also
 4671: work for unsigned numbers: @code{d+}, @code{d-}.
 4672: 
 4673: doc-s>d
 4674: doc-d>s
 4675: doc-d+
 4676: doc-d-
 4677: doc-dnegate
 4678: doc-dabs
 4679: doc-dmin
 4680: doc-dmax
 4681: 
 4682: 
 4683: @node Bitwise operations, Numeric comparison, Double precision, Arithmetic
 4684: @subsection Bitwise operations
 4685: @cindex bitwise operation words
 4686: 
 4687: 
 4688: doc-and
 4689: doc-or
 4690: doc-xor
 4691: doc-invert
 4692: doc-lshift
 4693: doc-rshift
 4694: doc-2*
 4695: doc-d2*
 4696: doc-2/
 4697: doc-d2/
 4698: 
 4699: 
 4700: @node Numeric comparison, Mixed precision, Bitwise operations, Arithmetic
 4701: @subsection Numeric comparison
 4702: @cindex numeric comparison words
 4703: 
 4704: Note that the words that compare for equality (@code{= <> 0= 0<> d= d<>
 4705: d0= d0<>}) work for for both signed and unsigned numbers.
 4706: 
 4707: doc-<
 4708: doc-<=
 4709: doc-<>
 4710: doc-=
 4711: doc->
 4712: doc->=
 4713: 
 4714: doc-0<
 4715: doc-0<=
 4716: doc-0<>
 4717: doc-0=
 4718: doc-0>
 4719: doc-0>=
 4720: 
 4721: doc-u<
 4722: doc-u<=
 4723: @c u<> and u= exist but are the same as <> and =
 4724: @c doc-u<>
 4725: @c doc-u=
 4726: doc-u>
 4727: doc-u>=
 4728: 
 4729: doc-within
 4730: 
 4731: doc-d<
 4732: doc-d<=
 4733: doc-d<>
 4734: doc-d=
 4735: doc-d>
 4736: doc-d>=
 4737: 
 4738: doc-d0<
 4739: doc-d0<=
 4740: doc-d0<>
 4741: doc-d0=
 4742: doc-d0>
 4743: doc-d0>=
 4744: 
 4745: doc-du<
 4746: doc-du<=
 4747: @c du<> and du= exist but are the same as d<> and d=
 4748: @c doc-du<>
 4749: @c doc-du=
 4750: doc-du>
 4751: doc-du>=
 4752: 
 4753: 
 4754: @node Mixed precision, Floating Point, Numeric comparison, Arithmetic
 4755: @subsection Mixed precision
 4756: @cindex mixed precision arithmetic words
 4757: 
 4758: 
 4759: doc-m+
 4760: doc-*/
 4761: doc-*/mod
 4762: doc-m*
 4763: doc-um*
 4764: doc-m*/
 4765: doc-um/mod
 4766: doc-fm/mod
 4767: doc-sm/rem
 4768: 
 4769: 
 4770: @node Floating Point,  , Mixed precision, Arithmetic
 4771: @subsection Floating Point
 4772: @cindex floating point arithmetic words
 4773: 
 4774: For the rules used by the text interpreter for
 4775: recognising floating-point numbers see @ref{Number Conversion}.
 4776: 
 4777: Gforth has a separate floating point stack, but the documentation uses
 4778: the unified notation.@footnote{It's easy to generate the separate
 4779: notation from that by just separating the floating-point numbers out:
 4780: e.g. @code{( n r1 u r2 -- r3 )} becomes @code{( n u -- ) ( F: r1 r2 --
 4781: r3 )}.}
 4782: 
 4783: @cindex floating-point arithmetic, pitfalls
 4784: Floating point numbers have a number of unpleasant surprises for the
 4785: unwary (e.g., floating point addition is not associative) and even a
 4786: few for the wary. You should not use them unless you know what you are
 4787: doing or you don't care that the results you get are totally bogus. If
 4788: you want to learn about the problems of floating point numbers (and
 4789: how to avoid them), you might start with @cite{David Goldberg,
 4790: @uref{http://docs.sun.com/source/806-3568/ncg_goldberg.html,What Every
 4791: Computer Scientist Should Know About Floating-Point Arithmetic}, ACM
 4792: Computing Surveys 23(1):5@minus{}48, March 1991}.
 4793: 
 4794: 
 4795: doc-d>f
 4796: doc-f>d
 4797: doc-f+
 4798: doc-f-
 4799: doc-f*
 4800: doc-f/
 4801: doc-fnegate
 4802: doc-fabs
 4803: doc-fmax
 4804: doc-fmin
 4805: doc-floor
 4806: doc-fround
 4807: doc-f**
 4808: doc-fsqrt
 4809: doc-fexp
 4810: doc-fexpm1
 4811: doc-fln
 4812: doc-flnp1
 4813: doc-flog
 4814: doc-falog
 4815: doc-f2*
 4816: doc-f2/
 4817: doc-1/f
 4818: doc-precision
 4819: doc-set-precision
 4820: 
 4821: @cindex angles in trigonometric operations
 4822: @cindex trigonometric operations
 4823: Angles in floating point operations are given in radians (a full circle
 4824: has 2 pi radians).
 4825: 
 4826: doc-fsin
 4827: doc-fcos
 4828: doc-fsincos
 4829: doc-ftan
 4830: doc-fasin
 4831: doc-facos
 4832: doc-fatan
 4833: doc-fatan2
 4834: doc-fsinh
 4835: doc-fcosh
 4836: doc-ftanh
 4837: doc-fasinh
 4838: doc-facosh
 4839: doc-fatanh
 4840: doc-pi
 4841: 
 4842: @cindex equality of floats
 4843: @cindex floating-point comparisons
 4844: One particular problem with floating-point arithmetic is that comparison
 4845: for equality often fails when you would expect it to succeed.  For this
 4846: reason approximate equality is often preferred (but you still have to
 4847: know what you are doing).  Also note that IEEE NaNs may compare
 4848: differently from what you might expect.  The comparison words are:
 4849: 
 4850: doc-f~rel
 4851: doc-f~abs
 4852: doc-f~
 4853: doc-f=
 4854: doc-f<>
 4855: 
 4856: doc-f<
 4857: doc-f<=
 4858: doc-f>
 4859: doc-f>=
 4860: 
 4861: doc-f0<
 4862: doc-f0<=
 4863: doc-f0<>
 4864: doc-f0=
 4865: doc-f0>
 4866: doc-f0>=
 4867: 
 4868: 
 4869: @node Stack Manipulation, Memory, Arithmetic, Words
 4870: @section Stack Manipulation
 4871: @cindex stack manipulation words
 4872: 
 4873: @cindex floating-point stack in the standard
 4874: Gforth maintains a number of separate stacks:
 4875: 
 4876: @cindex data stack
 4877: @cindex parameter stack
 4878: @itemize @bullet
 4879: @item
 4880: A data stack (also known as the @dfn{parameter stack}) -- for
 4881: characters, cells, addresses, and double cells.
 4882: 
 4883: @cindex floating-point stack
 4884: @item
 4885: A floating point stack -- for holding floating point (FP) numbers.
 4886: 
 4887: @cindex return stack
 4888: @item
 4889: A return stack -- for holding the return addresses of colon
 4890: definitions and other (non-FP) data.
 4891: 
 4892: @cindex locals stack
 4893: @item
 4894: A locals stack -- for holding local variables.
 4895: @end itemize
 4896: 
 4897: @menu
 4898: * Data stack::                  
 4899: * Floating point stack::        
 4900: * Return stack::                
 4901: * Locals stack::                
 4902: * Stack pointer manipulation::  
 4903: @end menu
 4904: 
 4905: @node Data stack, Floating point stack, Stack Manipulation, Stack Manipulation
 4906: @subsection Data stack
 4907: @cindex data stack manipulation words
 4908: @cindex stack manipulations words, data stack
 4909: 
 4910: 
 4911: doc-drop
 4912: doc-nip
 4913: doc-dup
 4914: doc-over
 4915: doc-tuck
 4916: doc-swap
 4917: doc-pick
 4918: doc-rot
 4919: doc--rot
 4920: doc-?dup
 4921: doc-roll
 4922: doc-2drop
 4923: doc-2nip
 4924: doc-2dup
 4925: doc-2over
 4926: doc-2tuck
 4927: doc-2swap
 4928: doc-2rot
 4929: 
 4930: 
 4931: @node Floating point stack, Return stack, Data stack, Stack Manipulation
 4932: @subsection Floating point stack
 4933: @cindex floating-point stack manipulation words
 4934: @cindex stack manipulation words, floating-point stack
 4935: 
 4936: Whilst every sane Forth has a separate floating-point stack, it is not
 4937: strictly required; an ANS Forth system could theoretically keep
 4938: floating-point numbers on the data stack. As an additional difficulty,
 4939: you don't know how many cells a floating-point number takes. It is
 4940: reportedly possible to write words in a way that they work also for a
 4941: unified stack model, but we do not recommend trying it. Instead, just
 4942: say that your program has an environmental dependency on a separate
 4943: floating-point stack.
 4944: 
 4945: doc-floating-stack
 4946: 
 4947: doc-fdrop
 4948: doc-fnip
 4949: doc-fdup
 4950: doc-fover
 4951: doc-ftuck
 4952: doc-fswap
 4953: doc-fpick
 4954: doc-frot
 4955: 
 4956: 
 4957: @node Return stack, Locals stack, Floating point stack, Stack Manipulation
 4958: @subsection Return stack
 4959: @cindex return stack manipulation words
 4960: @cindex stack manipulation words, return stack
 4961: 
 4962: @cindex return stack and locals
 4963: @cindex locals and return stack
 4964: A Forth system is allowed to keep local variables on the
 4965: return stack. This is reasonable, as local variables usually eliminate
 4966: the need to use the return stack explicitly. So, if you want to produce
 4967: a standard compliant program and you are using local variables in a
 4968: word, forget about return stack manipulations in that word (refer to the
 4969: standard document for the exact rules).
 4970: 
 4971: doc->r
 4972: doc-r>
 4973: doc-r@
 4974: doc-rdrop
 4975: doc-2>r
 4976: doc-2r>
 4977: doc-2r@
 4978: doc-2rdrop
 4979: 
 4980: 
 4981: @node Locals stack, Stack pointer manipulation, Return stack, Stack Manipulation
 4982: @subsection Locals stack
 4983: 
 4984: Gforth uses an extra locals stack.  It is described, along with the
 4985: reasons for its existence, in @ref{Locals implementation}.
 4986: 
 4987: @node Stack pointer manipulation,  , Locals stack, Stack Manipulation
 4988: @subsection Stack pointer manipulation
 4989: @cindex stack pointer manipulation words
 4990: 
 4991: @c removed s0 r0 l0 -- they are obsolete aliases for sp0 rp0 lp0
 4992: doc-sp0
 4993: doc-sp@
 4994: doc-sp!
 4995: doc-fp0
 4996: doc-fp@
 4997: doc-fp!
 4998: doc-rp0
 4999: doc-rp@
 5000: doc-rp!
 5001: doc-lp0
 5002: doc-lp@
 5003: doc-lp!
 5004: 
 5005: 
 5006: @node Memory, Control Structures, Stack Manipulation, Words
 5007: @section Memory
 5008: @cindex memory words
 5009: 
 5010: @menu
 5011: * Memory model::                
 5012: * Dictionary allocation::       
 5013: * Heap Allocation::             
 5014: * Memory Access::               
 5015: * Address arithmetic::          
 5016: * Memory Blocks::               
 5017: @end menu
 5018: 
 5019: In addition to the standard Forth memory allocation words, there is also
 5020: a @uref{http://www.complang.tuwien.ac.at/forth/garbage-collection.zip,
 5021: garbage collector}.
 5022: 
 5023: @node Memory model, Dictionary allocation, Memory, Memory
 5024: @subsection ANS Forth and Gforth memory models
 5025: 
 5026: @c The ANS Forth description is a mess (e.g., is the heap part of
 5027: @c the dictionary?), so let's not stick to closely with it.
 5028: 
 5029: ANS Forth considers a Forth system as consisting of several address
 5030: spaces, of which only @dfn{data space} is managed and accessible with
 5031: the memory words.  Memory not necessarily in data space includes the
 5032: stacks, the code (called code space) and the headers (called name
 5033: space). In Gforth everything is in data space, but the code for the
 5034: primitives is usually read-only.
 5035: 
 5036: Data space is divided into a number of areas: The (data space portion of
 5037: the) dictionary@footnote{Sometimes, the term @dfn{dictionary} is used to
 5038: refer to the search data structure embodied in word lists and headers,
 5039: because it is used for looking up names, just as you would in a
 5040: conventional dictionary.}, the heap, and a number of system-allocated
 5041: buffers.
 5042: 
 5043: @cindex address arithmetic restrictions, ANS vs. Gforth
 5044: @cindex contiguous regions, ANS vs. Gforth
 5045: In ANS Forth data space is also divided into contiguous regions.  You
 5046: can only use address arithmetic within a contiguous region, not between
 5047: them.  Usually each allocation gives you one contiguous region, but the
 5048: dictionary allocation words have additional rules (@pxref{Dictionary
 5049: allocation}).
 5050: 
 5051: Gforth provides one big address space, and address arithmetic can be
 5052: performed between any addresses. However, in the dictionary headers or
 5053: code are interleaved with data, so almost the only contiguous data space
 5054: regions there are those described by ANS Forth as contiguous; but you
 5055: can be sure that the dictionary is allocated towards increasing
 5056: addresses even between contiguous regions.  The memory order of
 5057: allocations in the heap is platform-dependent (and possibly different
 5058: from one run to the next).
 5059: 
 5060: 
 5061: @node Dictionary allocation, Heap Allocation, Memory model, Memory
 5062: @subsection Dictionary allocation
 5063: @cindex reserving data space
 5064: @cindex data space - reserving some
 5065: 
 5066: Dictionary allocation is a stack-oriented allocation scheme, i.e., if
 5067: you want to deallocate X, you also deallocate everything
 5068: allocated after X.
 5069: 
 5070: @cindex contiguous regions in dictionary allocation
 5071: The allocations using the words below are contiguous and grow the region
 5072: towards increasing addresses.  Other words that allocate dictionary
 5073: memory of any kind (i.e., defining words including @code{:noname}) end
 5074: the contiguous region and start a new one.
 5075: 
 5076: In ANS Forth only @code{create}d words are guaranteed to produce an
 5077: address that is the start of the following contiguous region.  In
 5078: particular, the cell allocated by @code{variable} is not guaranteed to
 5079: be contiguous with following @code{allot}ed memory.
 5080: 
 5081: You can deallocate memory by using @code{allot} with a negative argument
 5082: (with some restrictions, see @code{allot}). For larger deallocations use
 5083: @code{marker}.
 5084: 
 5085: 
 5086: doc-here
 5087: doc-unused
 5088: doc-allot
 5089: doc-c,
 5090: doc-f,
 5091: doc-,
 5092: doc-2,
 5093: 
 5094: Memory accesses have to be aligned (@pxref{Address arithmetic}). So of
 5095: course you should allocate memory in an aligned way, too. I.e., before
 5096: allocating allocating a cell, @code{here} must be cell-aligned, etc.
 5097: The words below align @code{here} if it is not already.  Basically it is
 5098: only already aligned for a type, if the last allocation was a multiple
 5099: of the size of this type and if @code{here} was aligned for this type
 5100: before.
 5101: 
 5102: After freshly @code{create}ing a word, @code{here} is @code{align}ed in
 5103: ANS Forth (@code{maxalign}ed in Gforth).
 5104: 
 5105: doc-align
 5106: doc-falign
 5107: doc-sfalign
 5108: doc-dfalign
 5109: doc-maxalign
 5110: doc-cfalign
 5111: 
 5112: 
 5113: @node Heap Allocation, Memory Access, Dictionary allocation, Memory
 5114: @subsection Heap allocation
 5115: @cindex heap allocation
 5116: @cindex dynamic allocation of memory
 5117: @cindex memory-allocation word set
 5118: 
 5119: @cindex contiguous regions and heap allocation
 5120: Heap allocation supports deallocation of allocated memory in any
 5121: order. Dictionary allocation is not affected by it (i.e., it does not
 5122: end a contiguous region). In Gforth, these words are implemented using
 5123: the standard C library calls malloc(), free() and resize().
 5124: 
 5125: The memory region produced by one invocation of @code{allocate} or
 5126: @code{resize} is internally contiguous.  There is no contiguity between
 5127: such a region and any other region (including others allocated from the
 5128: heap).
 5129: 
 5130: doc-allocate
 5131: doc-free
 5132: doc-resize
 5133: 
 5134: 
 5135: @node Memory Access, Address arithmetic, Heap Allocation, Memory
 5136: @subsection Memory Access
 5137: @cindex memory access words
 5138: 
 5139: doc-@
 5140: doc-!
 5141: doc-+!
 5142: doc-c@
 5143: doc-c!
 5144: doc-2@
 5145: doc-2!
 5146: doc-f@
 5147: doc-f!
 5148: doc-sf@
 5149: doc-sf!
 5150: doc-df@
 5151: doc-df!
 5152: doc-sw@
 5153: doc-uw@
 5154: doc-w!
 5155: doc-sl@
 5156: doc-ul@
 5157: doc-l!
 5158: 
 5159: @node Address arithmetic, Memory Blocks, Memory Access, Memory
 5160: @subsection Address arithmetic
 5161: @cindex address arithmetic words
 5162: 
 5163: Address arithmetic is the foundation on which you can build data
 5164: structures like arrays, records (@pxref{Structures}) and objects
 5165: (@pxref{Object-oriented Forth}).
 5166: 
 5167: @cindex address unit
 5168: @cindex au (address unit)
 5169: ANS Forth does not specify the sizes of the data types. Instead, it
 5170: offers a number of words for computing sizes and doing address
 5171: arithmetic. Address arithmetic is performed in terms of address units
 5172: (aus); on most systems the address unit is one byte. Note that a
 5173: character may have more than one au, so @code{chars} is no noop (on
 5174: platforms where it is a noop, it compiles to nothing).
 5175: 
 5176: The basic address arithmetic words are @code{+} and @code{-}.  E.g., if
 5177: you have the address of a cell, perform @code{1 cells +}, and you will
 5178: have the address of the next cell.
 5179: 
 5180: @cindex contiguous regions and address arithmetic
 5181: In ANS Forth you can perform address arithmetic only within a contiguous
 5182: region, i.e., if you have an address into one region, you can only add
 5183: and subtract such that the result is still within the region; you can
 5184: only subtract or compare addresses from within the same contiguous
 5185: region.  Reasons: several contiguous regions can be arranged in memory
 5186: in any way; on segmented systems addresses may have unusual
 5187: representations, such that address arithmetic only works within a
 5188: region.  Gforth provides a few more guarantees (linear address space,
 5189: dictionary grows upwards), but in general I have found it easy to stay
 5190: within contiguous regions (exception: computing and comparing to the
 5191: address just beyond the end of an array).
 5192: 
 5193: @cindex alignment of addresses for types
 5194: ANS Forth also defines words for aligning addresses for specific
 5195: types. Many computers require that accesses to specific data types
 5196: must only occur at specific addresses; e.g., that cells may only be
 5197: accessed at addresses divisible by 4. Even if a machine allows unaligned
 5198: accesses, it can usually perform aligned accesses faster. 
 5199: 
 5200: For the performance-conscious: alignment operations are usually only
 5201: necessary during the definition of a data structure, not during the
 5202: (more frequent) accesses to it.
 5203: 
 5204: ANS Forth defines no words for character-aligning addresses. This is not
 5205: an oversight, but reflects the fact that addresses that are not
 5206: char-aligned have no use in the standard and therefore will not be
 5207: created.
 5208: 
 5209: @cindex @code{CREATE} and alignment
 5210: ANS Forth guarantees that addresses returned by @code{CREATE}d words
 5211: are cell-aligned; in addition, Gforth guarantees that these addresses
 5212: are aligned for all purposes.
 5213: 
 5214: Note that the ANS Forth word @code{char} has nothing to do with address
 5215: arithmetic.
 5216: 
 5217: 
 5218: doc-chars
 5219: doc-char+
 5220: doc-cells
 5221: doc-cell+
 5222: doc-cell
 5223: doc-aligned
 5224: doc-floats
 5225: doc-float+
 5226: doc-float
 5227: doc-faligned
 5228: doc-sfloats
 5229: doc-sfloat+
 5230: doc-sfaligned
 5231: doc-dfloats
 5232: doc-dfloat+
 5233: doc-dfaligned
 5234: doc-maxaligned
 5235: doc-cfaligned
 5236: doc-address-unit-bits
 5237: doc-/w
 5238: doc-/l
 5239: 
 5240: @node Memory Blocks,  , Address arithmetic, Memory
 5241: @subsection Memory Blocks
 5242: @cindex memory block words
 5243: @cindex character strings - moving and copying
 5244: 
 5245: Memory blocks often represent character strings; For ways of storing
 5246: character strings in memory see @ref{String Formats}.  For other
 5247: string-processing words see @ref{Displaying characters and strings}.
 5248: 
 5249: A few of these words work on address unit blocks.  In that case, you
 5250: usually have to insert @code{CHARS} before the word when working on
 5251: character strings.  Most words work on character blocks, and expect a
 5252: char-aligned address.
 5253: 
 5254: When copying characters between overlapping memory regions, use
 5255: @code{chars move} or choose carefully between @code{cmove} and
 5256: @code{cmove>}.
 5257: 
 5258: doc-move
 5259: doc-erase
 5260: doc-cmove
 5261: doc-cmove>
 5262: doc-fill
 5263: doc-blank
 5264: doc-compare
 5265: doc-str=
 5266: doc-str<
 5267: doc-string-prefix?
 5268: doc-search
 5269: doc--trailing
 5270: doc-/string
 5271: doc-bounds
 5272: doc-pad
 5273: 
 5274: @comment TODO examples
 5275: 
 5276: 
 5277: @node Control Structures, Defining Words, Memory, Words
 5278: @section Control Structures
 5279: @cindex control structures
 5280: 
 5281: Control structures in Forth cannot be used interpretively, only in a
 5282: colon definition@footnote{To be precise, they have no interpretation
 5283: semantics (@pxref{Interpretation and Compilation Semantics}).}. We do
 5284: not like this limitation, but have not seen a satisfying way around it
 5285: yet, although many schemes have been proposed.
 5286: 
 5287: @menu
 5288: * Selection::                   IF ... ELSE ... ENDIF
 5289: * Simple Loops::                BEGIN ...
 5290: * Counted Loops::               DO
 5291: * Arbitrary control structures::  
 5292: * Calls and returns::           
 5293: * Exception Handling::          
 5294: @end menu
 5295: 
 5296: @node Selection, Simple Loops, Control Structures, Control Structures
 5297: @subsection Selection
 5298: @cindex selection control structures
 5299: @cindex control structures for selection
 5300: 
 5301: @cindex @code{IF} control structure
 5302: @example
 5303: @i{flag}
 5304: IF
 5305:   @i{code}
 5306: ENDIF
 5307: @end example
 5308: @noindent
 5309: 
 5310: If @i{flag} is non-zero (as far as @code{IF} etc. are concerned, a cell
 5311: with any bit set represents truth) @i{code} is executed.
 5312: 
 5313: @example
 5314: @i{flag}
 5315: IF
 5316:   @i{code1}
 5317: ELSE
 5318:   @i{code2}
 5319: ENDIF
 5320: @end example
 5321: 
 5322: If @var{flag} is true, @i{code1} is executed, otherwise @i{code2} is
 5323: executed.
 5324: 
 5325: You can use @code{THEN} instead of @code{ENDIF}. Indeed, @code{THEN} is
 5326: standard, and @code{ENDIF} is not, although it is quite popular. We
 5327: recommend using @code{ENDIF}, because it is less confusing for people
 5328: who also know other languages (and is not prone to reinforcing negative
 5329: prejudices against Forth in these people). Adding @code{ENDIF} to a
 5330: system that only supplies @code{THEN} is simple:
 5331: @example
 5332: : ENDIF   POSTPONE then ; immediate
 5333: @end example
 5334: 
 5335: [According to @cite{Webster's New Encyclopedic Dictionary}, @dfn{then
 5336: (adv.)}  has the following meanings:
 5337: @quotation
 5338: ... 2b: following next after in order ... 3d: as a necessary consequence
 5339: (if you were there, then you saw them).
 5340: @end quotation
 5341: Forth's @code{THEN} has the meaning 2b, whereas @code{THEN} in Pascal
 5342: and many other programming languages has the meaning 3d.]
 5343: 
 5344: Gforth also provides the words @code{?DUP-IF} and @code{?DUP-0=-IF}, so
 5345: you can avoid using @code{?dup}. Using these alternatives is also more
 5346: efficient than using @code{?dup}. Definitions in ANS Forth
 5347: for @code{ENDIF}, @code{?DUP-IF} and @code{?DUP-0=-IF} are provided in
 5348: @file{compat/control.fs}.
 5349: 
 5350: @cindex @code{CASE} control structure
 5351: @example
 5352: @i{x}
 5353: CASE
 5354:   @i{x1} OF @i{code1} ENDOF
 5355:   @i{x2} OF @i{code2} ENDOF
 5356:   @dots{}
 5357:   ( x ) @i{default-code} ( x )
 5358: ENDCASE ( )
 5359: @end example
 5360: 
 5361: Executes the first @i{codei}, where the @i{xi} is equal to @i{x}.  If no
 5362: @i{xi} matches, the optional @i{default-code} is executed. The optional
 5363: default case can be added by simply writing the code after the last
 5364: @code{ENDOF}. It may use @i{x}, which is on top of the stack, but must
 5365: not consume it.  The value @i{x} is consumed by this construction
 5366: (either by an @code{OF} that matches, or by the @code{ENDCASE}, if no OF
 5367: matches).  Example:
 5368: 
 5369: @example
 5370: : num-name ( n -- c-addr u )
 5371:  case
 5372:    0 of s" zero " endof
 5373:    1 of s" one "  endof
 5374:    2 of s" two "  endof
 5375:    \ default case:
 5376:    s" other number" 
 5377:    rot \ get n on top so ENDCASE can drop it
 5378:  endcase ;
 5379: @end example
 5380: 
 5381: @progstyle
 5382: To keep the code understandable, you should ensure that you change the
 5383: stack in the same way (wrt. number and types of stack items consumed
 5384: and pushed) on all paths through a selection construct.
 5385: 
 5386: @node Simple Loops, Counted Loops, Selection, Control Structures
 5387: @subsection Simple Loops
 5388: @cindex simple loops
 5389: @cindex loops without count 
 5390: 
 5391: @cindex @code{WHILE} loop
 5392: @example
 5393: BEGIN
 5394:   @i{code1}
 5395:   @i{flag}
 5396: WHILE
 5397:   @i{code2}
 5398: REPEAT
 5399: @end example
 5400: 
 5401: @i{code1} is executed and @i{flag} is computed. If it is true,
 5402: @i{code2} is executed and the loop is restarted; If @i{flag} is
 5403: false, execution continues after the @code{REPEAT}.
 5404: 
 5405: @cindex @code{UNTIL} loop
 5406: @example
 5407: BEGIN
 5408:   @i{code}
 5409:   @i{flag}
 5410: UNTIL
 5411: @end example
 5412: 
 5413: @i{code} is executed. The loop is restarted if @code{flag} is false.
 5414: 
 5415: @progstyle
 5416: To keep the code understandable, a complete iteration of the loop should
 5417: not change the number and types of the items on the stacks.
 5418: 
 5419: @cindex endless loop
 5420: @cindex loops, endless
 5421: @example
 5422: BEGIN
 5423:   @i{code}
 5424: AGAIN
 5425: @end example
 5426: 
 5427: This is an endless loop.
 5428: 
 5429: @node Counted Loops, Arbitrary control structures, Simple Loops, Control Structures
 5430: @subsection Counted Loops
 5431: @cindex counted loops
 5432: @cindex loops, counted
 5433: @cindex @code{DO} loops
 5434: 
 5435: The basic counted loop is:
 5436: @example
 5437: @i{limit} @i{start}
 5438: ?DO
 5439:   @i{body}
 5440: LOOP
 5441: @end example
 5442: 
 5443: This performs one iteration for every integer, starting from @i{start}
 5444: and up to, but excluding @i{limit}. The counter, or @i{index}, can be
 5445: accessed with @code{i}. For example, the loop:
 5446: @example
 5447: 10 0 ?DO
 5448:   i .
 5449: LOOP
 5450: @end example
 5451: @noindent
 5452: prints @code{0 1 2 3 4 5 6 7 8 9}
 5453: 
 5454: The index of the innermost loop can be accessed with @code{i}, the index
 5455: of the next loop with @code{j}, and the index of the third loop with
 5456: @code{k}.
 5457: 
 5458: 
 5459: doc-i
 5460: doc-j
 5461: doc-k
 5462: 
 5463: 
 5464: The loop control data are kept on the return stack, so there are some
 5465: restrictions on mixing return stack accesses and counted loop words. In
 5466: particuler, if you put values on the return stack outside the loop, you
 5467: cannot read them inside the loop@footnote{well, not in a way that is
 5468: portable.}. If you put values on the return stack within a loop, you
 5469: have to remove them before the end of the loop and before accessing the
 5470: index of the loop.
 5471: 
 5472: There are several variations on the counted loop:
 5473: 
 5474: @itemize @bullet
 5475: @item
 5476: @code{LEAVE} leaves the innermost counted loop immediately; execution
 5477: continues after the associated @code{LOOP} or @code{NEXT}. For example:
 5478: 
 5479: @example
 5480: 10 0 ?DO  i DUP . 3 = IF LEAVE THEN LOOP
 5481: @end example
 5482: prints @code{0 1 2 3}
 5483: 
 5484: 
 5485: @item
 5486: @code{UNLOOP} prepares for an abnormal loop exit, e.g., via
 5487: @code{EXIT}. @code{UNLOOP} removes the loop control parameters from the
 5488: return stack so @code{EXIT} can get to its return address. For example:
 5489: 
 5490: @example
 5491: : demo 10 0 ?DO i DUP . 3 = IF UNLOOP EXIT THEN LOOP ." Done" ;
 5492: @end example
 5493: prints @code{0 1 2 3}
 5494: 
 5495: 
 5496: @item
 5497: If @i{start} is greater than @i{limit}, a @code{?DO} loop is entered
 5498: (and @code{LOOP} iterates until they become equal by wrap-around
 5499: arithmetic). This behaviour is usually not what you want. Therefore,
 5500: Gforth offers @code{+DO} and @code{U+DO} (as replacements for
 5501: @code{?DO}), which do not enter the loop if @i{start} is greater than
 5502: @i{limit}; @code{+DO} is for signed loop parameters, @code{U+DO} for
 5503: unsigned loop parameters.
 5504: 
 5505: @item
 5506: @code{?DO} can be replaced by @code{DO}. @code{DO} always enters
 5507: the loop, independent of the loop parameters. Do not use @code{DO}, even
 5508: if you know that the loop is entered in any case. Such knowledge tends
 5509: to become invalid during maintenance of a program, and then the
 5510: @code{DO} will make trouble.
 5511: 
 5512: @item
 5513: @code{LOOP} can be replaced with @code{@i{n} +LOOP}; this updates the
 5514: index by @i{n} instead of by 1. The loop is terminated when the border
 5515: between @i{limit-1} and @i{limit} is crossed. E.g.:
 5516: 
 5517: @example
 5518: 4 0 +DO  i .  2 +LOOP
 5519: @end example
 5520: @noindent
 5521: prints @code{0 2}
 5522: 
 5523: @example
 5524: 4 1 +DO  i .  2 +LOOP
 5525: @end example
 5526: @noindent
 5527: prints @code{1 3}
 5528: 
 5529: @item
 5530: @cindex negative increment for counted loops
 5531: @cindex counted loops with negative increment
 5532: The behaviour of @code{@i{n} +LOOP} is peculiar when @i{n} is negative:
 5533: 
 5534: @example
 5535: -1 0 ?DO  i .  -1 +LOOP
 5536: @end example
 5537: @noindent
 5538: prints @code{0 -1}
 5539: 
 5540: @example
 5541: 0 0 ?DO  i .  -1 +LOOP
 5542: @end example
 5543: prints nothing.
 5544: 
 5545: Therefore we recommend avoiding @code{@i{n} +LOOP} with negative
 5546: @i{n}. One alternative is @code{@i{u} -LOOP}, which reduces the
 5547: index by @i{u} each iteration. The loop is terminated when the border
 5548: between @i{limit+1} and @i{limit} is crossed. Gforth also provides
 5549: @code{-DO} and @code{U-DO} for down-counting loops. E.g.:
 5550: 
 5551: @example
 5552: -2 0 -DO  i .  1 -LOOP
 5553: @end example
 5554: @noindent
 5555: prints @code{0 -1}
 5556: 
 5557: @example
 5558: -1 0 -DO  i .  1 -LOOP
 5559: @end example
 5560: @noindent
 5561: prints @code{0}
 5562: 
 5563: @example
 5564: 0 0 -DO  i .  1 -LOOP
 5565: @end example
 5566: @noindent
 5567: prints nothing.
 5568: 
 5569: @end itemize
 5570: 
 5571: Unfortunately, @code{+DO}, @code{U+DO}, @code{-DO}, @code{U-DO} and
 5572: @code{-LOOP} are not defined in ANS Forth. However, an implementation
 5573: for these words that uses only standard words is provided in
 5574: @file{compat/loops.fs}.
 5575: 
 5576: 
 5577: @cindex @code{FOR} loops
 5578: Another counted loop is:
 5579: @example
 5580: @i{n}
 5581: FOR
 5582:   @i{body}
 5583: NEXT
 5584: @end example
 5585: This is the preferred loop of native code compiler writers who are too
 5586: lazy to optimize @code{?DO} loops properly. This loop structure is not
 5587: defined in ANS Forth. In Gforth, this loop iterates @i{n+1} times;
 5588: @code{i} produces values starting with @i{n} and ending with 0. Other
 5589: Forth systems may behave differently, even if they support @code{FOR}
 5590: loops. To avoid problems, don't use @code{FOR} loops.
 5591: 
 5592: @node Arbitrary control structures, Calls and returns, Counted Loops, Control Structures
 5593: @subsection Arbitrary control structures
 5594: @cindex control structures, user-defined
 5595: 
 5596: @cindex control-flow stack
 5597: ANS Forth permits and supports using control structures in a non-nested
 5598: way. Information about incomplete control structures is stored on the
 5599: control-flow stack. This stack may be implemented on the Forth data
 5600: stack, and this is what we have done in Gforth.
 5601: 
 5602: @cindex @code{orig}, control-flow stack item
 5603: @cindex @code{dest}, control-flow stack item
 5604: An @i{orig} entry represents an unresolved forward branch, a @i{dest}
 5605: entry represents a backward branch target. A few words are the basis for
 5606: building any control structure possible (except control structures that
 5607: need storage, like calls, coroutines, and backtracking).
 5608: 
 5609: 
 5610: doc-if
 5611: doc-ahead
 5612: doc-then
 5613: doc-begin
 5614: doc-until
 5615: doc-again
 5616: doc-cs-pick
 5617: doc-cs-roll
 5618: 
 5619: 
 5620: The Standard words @code{CS-PICK} and @code{CS-ROLL} allow you to
 5621: manipulate the control-flow stack in a portable way. Without them, you
 5622: would need to know how many stack items are occupied by a control-flow
 5623: entry (many systems use one cell. In Gforth they currently take three,
 5624: but this may change in the future).
 5625: 
 5626: Some standard control structure words are built from these words:
 5627: 
 5628: 
 5629: doc-else
 5630: doc-while
 5631: doc-repeat
 5632: 
 5633: 
 5634: @noindent
 5635: Gforth adds some more control-structure words:
 5636: 
 5637: 
 5638: doc-endif
 5639: doc-?dup-if
 5640: doc-?dup-0=-if
 5641: 
 5642: 
 5643: @noindent
 5644: Counted loop words constitute a separate group of words:
 5645: 
 5646: 
 5647: doc-?do
 5648: doc-+do
 5649: doc-u+do
 5650: doc--do
 5651: doc-u-do
 5652: doc-do
 5653: doc-for
 5654: doc-loop
 5655: doc-+loop
 5656: doc--loop
 5657: doc-next
 5658: doc-leave
 5659: doc-?leave
 5660: doc-unloop
 5661: doc-done
 5662: 
 5663: 
 5664: The standard does not allow using @code{CS-PICK} and @code{CS-ROLL} on
 5665: @i{do-sys}. Gforth allows it, but it's your job to ensure that for
 5666: every @code{?DO} etc. there is exactly one @code{UNLOOP} on any path
 5667: through the definition (@code{LOOP} etc. compile an @code{UNLOOP} on the
 5668: fall-through path). Also, you have to ensure that all @code{LEAVE}s are
 5669: resolved (by using one of the loop-ending words or @code{DONE}).
 5670: 
 5671: @noindent
 5672: Another group of control structure words are:
 5673: 
 5674: 
 5675: doc-case
 5676: doc-endcase
 5677: doc-of
 5678: doc-endof
 5679: 
 5680: 
 5681: @i{case-sys} and @i{of-sys} cannot be processed using @code{CS-PICK} and
 5682: @code{CS-ROLL}.
 5683: 
 5684: @subsubsection Programming Style
 5685: @cindex control structures programming style
 5686: @cindex programming style, arbitrary control structures
 5687: 
 5688: In order to ensure readability we recommend that you do not create
 5689: arbitrary control structures directly, but define new control structure
 5690: words for the control structure you want and use these words in your
 5691: program. For example, instead of writing:
 5692: 
 5693: @example
 5694: BEGIN
 5695:   ...
 5696: IF [ 1 CS-ROLL ]
 5697:   ...
 5698: AGAIN THEN
 5699: @end example
 5700: 
 5701: @noindent
 5702: we recommend defining control structure words, e.g.,
 5703: 
 5704: @example
 5705: : WHILE ( DEST -- ORIG DEST )
 5706:  POSTPONE IF
 5707:  1 CS-ROLL ; immediate
 5708: 
 5709: : REPEAT ( orig dest -- )
 5710:  POSTPONE AGAIN
 5711:  POSTPONE THEN ; immediate
 5712: @end example
 5713: 
 5714: @noindent
 5715: and then using these to create the control structure:
 5716: 
 5717: @example
 5718: BEGIN
 5719:   ...
 5720: WHILE
 5721:   ...
 5722: REPEAT
 5723: @end example
 5724: 
 5725: That's much easier to read, isn't it? Of course, @code{REPEAT} and
 5726: @code{WHILE} are predefined, so in this example it would not be
 5727: necessary to define them.
 5728: 
 5729: @node Calls and returns, Exception Handling, Arbitrary control structures, Control Structures
 5730: @subsection Calls and returns
 5731: @cindex calling a definition
 5732: @cindex returning from a definition
 5733: 
 5734: @cindex recursive definitions
 5735: A definition can be called simply be writing the name of the definition
 5736: to be called. Normally a definition is invisible during its own
 5737: definition. If you want to write a directly recursive definition, you
 5738: can use @code{recursive} to make the current definition visible, or
 5739: @code{recurse} to call the current definition directly.
 5740: 
 5741: 
 5742: doc-recursive
 5743: doc-recurse
 5744: 
 5745: 
 5746: @comment TODO add example of the two recursion methods
 5747: @quotation
 5748: @progstyle
 5749: I prefer using @code{recursive} to @code{recurse}, because calling the
 5750: definition by name is more descriptive (if the name is well-chosen) than
 5751: the somewhat cryptic @code{recurse}.  E.g., in a quicksort
 5752: implementation, it is much better to read (and think) ``now sort the
 5753: partitions'' than to read ``now do a recursive call''.
 5754: @end quotation
 5755: 
 5756: For mutual recursion, use @code{Defer}red words, like this:
 5757: 
 5758: @example
 5759: Defer foo
 5760: 
 5761: : bar ( ... -- ... )
 5762:  ... foo ... ;
 5763: 
 5764: :noname ( ... -- ... )
 5765:  ... bar ... ;
 5766: IS foo
 5767: @end example
 5768: 
 5769: Deferred words are discussed in more detail in @ref{Deferred Words}.
 5770: 
 5771: The current definition returns control to the calling definition when
 5772: the end of the definition is reached or @code{EXIT} is encountered.
 5773: 
 5774: doc-exit
 5775: doc-;s
 5776: 
 5777: 
 5778: @node Exception Handling,  , Calls and returns, Control Structures
 5779: @subsection Exception Handling
 5780: @cindex exceptions
 5781: 
 5782: @c quit is a very bad idea for error handling, 
 5783: @c because it does not translate into a THROW
 5784: @c it also does not belong into this chapter
 5785: 
 5786: If a word detects an error condition that it cannot handle, it can
 5787: @code{throw} an exception.  In the simplest case, this will terminate
 5788: your program, and report an appropriate error.
 5789: 
 5790: doc-throw
 5791: 
 5792: @code{Throw} consumes a cell-sized error number on the stack. There are
 5793: some predefined error numbers in ANS Forth (see @file{errors.fs}).  In
 5794: Gforth (and most other systems) you can use the iors produced by various
 5795: words as error numbers (e.g., a typical use of @code{allocate} is
 5796: @code{allocate throw}).  Gforth also provides the word @code{exception}
 5797: to define your own error numbers (with decent error reporting); an ANS
 5798: Forth version of this word (but without the error messages) is available
 5799: in @code{compat/except.fs}.  And finally, you can use your own error
 5800: numbers (anything outside the range -4095..0), but won't get nice error
 5801: messages, only numbers.  For example, try:
 5802: 
 5803: @example
 5804: -10 throw                    \ ANS defined
 5805: -267 throw                   \ system defined
 5806: s" my error" exception throw \ user defined
 5807: 7 throw                      \ arbitrary number
 5808: @end example
 5809: 
 5810: doc---exception-exception
 5811: 
 5812: A common idiom to @code{THROW} a specific error if a flag is true is
 5813: this:
 5814: 
 5815: @example
 5816: @code{( flag ) 0<> @i{errno} and throw}
 5817: @end example
 5818: 
 5819: Your program can provide exception handlers to catch exceptions.  An
 5820: exception handler can be used to correct the problem, or to clean up
 5821: some data structures and just throw the exception to the next exception
 5822: handler.  Note that @code{throw} jumps to the dynamically innermost
 5823: exception handler.  The system's exception handler is outermost, and just
 5824: prints an error and restarts command-line interpretation (or, in batch
 5825: mode (i.e., while processing the shell command line), leaves Gforth).
 5826: 
 5827: The ANS Forth way to catch exceptions is @code{catch}:
 5828: 
 5829: doc-catch
 5830: doc-nothrow
 5831: 
 5832: The most common use of exception handlers is to clean up the state when
 5833: an error happens.  E.g.,
 5834: 
 5835: @example
 5836: base @ >r hex \ actually the hex should be inside foo, or we h
 5837: ['] foo catch ( nerror|0 )
 5838: r> base !
 5839: ( nerror|0 ) throw \ pass it on
 5840: @end example
 5841: 
 5842: A use of @code{catch} for handling the error @code{myerror} might look
 5843: like this:
 5844: 
 5845: @example
 5846: ['] foo catch
 5847: CASE
 5848:   myerror OF ... ( do something about it ) nothrow ENDOF
 5849:   dup throw \ default: pass other errors on, do nothing on non-errors
 5850: ENDCASE
 5851: @end example
 5852: 
 5853: Having to wrap the code into a separate word is often cumbersome,
 5854: therefore Gforth provides an alternative syntax:
 5855: 
 5856: @example
 5857: TRY
 5858:   @i{code1}
 5859:   IFERROR
 5860:     @i{code2}
 5861:   THEN
 5862:   @i{code3}
 5863: ENDTRY
 5864: @end example
 5865: 
 5866: This performs @i{code1}.  If @i{code1} completes normally, execution
 5867: continues with @i{code3}.  If there is an exception in @i{code1} or
 5868: before @code{endtry}, the stacks are reset to the depth during
 5869: @code{try}, the throw value is pushed on the data stack, and execution
 5870: constinues at @i{code2}, and finally falls through to @i{code3}.
 5871: 
 5872: doc-try
 5873: doc-endtry
 5874: doc-iferror
 5875: 
 5876: If you don't need @i{code2}, you can write @code{restore} instead of
 5877: @code{iferror then}:
 5878: 
 5879: @example
 5880: TRY
 5881:   @i{code1}
 5882: RESTORE
 5883:   @i{code3}
 5884: ENDTRY
 5885: @end example
 5886: 
 5887: @cindex unwind-protect
 5888: The cleanup example from above in this syntax:
 5889: 
 5890: @example
 5891: base @@ @{ oldbase @}
 5892: TRY
 5893:   hex foo \ now the hex is placed correctly
 5894:   0       \ value for throw
 5895: RESTORE
 5896:   oldbase base !
 5897: ENDTRY
 5898: throw
 5899: @end example
 5900: 
 5901: An additional advantage of this variant is that an exception between
 5902: @code{restore} and @code{endtry} (e.g., from the user pressing
 5903: @kbd{Ctrl-C}) restarts the execution of the code after @code{restore},
 5904: so the base will be restored under all circumstances.
 5905: 
 5906: However, you have to ensure that this code does not cause an exception
 5907: itself, otherwise the @code{iferror}/@code{restore} code will loop.
 5908: Moreover, you should also make sure that the stack contents needed by
 5909: the @code{iferror}/@code{restore} code exist everywhere between
 5910: @code{try} and @code{endtry}; in our example this is achived by
 5911: putting the data in a local before the @code{try} (you cannot use the
 5912: return stack because the exception frame (@i{sys1}) is in the way
 5913: there).
 5914: 
 5915: This kind of usage corresponds to Lisp's @code{unwind-protect}.
 5916: 
 5917: @cindex @code{recover} (old Gforth versions)
 5918: If you do not want this exception-restarting behaviour, you achieve
 5919: this as follows:
 5920: 
 5921: @example
 5922: TRY
 5923:   @i{code1}
 5924: ENDTRY-IFERROR
 5925:   @i{code2}
 5926: THEN
 5927: @end example
 5928: 
 5929: If there is an exception in @i{code1}, then @i{code2} is executed,
 5930: otherwise execution continues behind the @code{then} (or in a possible
 5931: @code{else} branch).  This corresponds to the construct
 5932: 
 5933: @example
 5934: TRY
 5935:   @i{code1}
 5936: RECOVER
 5937:   @i{code2}
 5938: ENDTRY
 5939: @end example
 5940: 
 5941: in Gforth before version 0.7.  So you can directly replace
 5942: @code{recover}-using code; however, we recommend that you check if it
 5943: would not be better to use one of the other @code{try} variants while
 5944: you are at it.
 5945: 
 5946: To ease the transition, Gforth provides two compatibility files:
 5947: @file{endtry-iferror.fs} provides the @code{try ... endtry-iferror
 5948: ... then} syntax (but not @code{iferror} or @code{restore}) for old
 5949: systems; @file{recover-endtry.fs} provides the @code{try ... recover
 5950: ... endtry} syntax on new systems, so you can use that file as a
 5951: stopgap to run old programs.  Both files work on any system (they just
 5952: do nothing if the system already has the syntax it implements), so you
 5953: can unconditionally @code{require} one of these files, even if you use
 5954: a mix old and new systems.
 5955: 
 5956: doc-restore
 5957: doc-endtry-iferror
 5958: 
 5959: Here's the error handling example:
 5960: 
 5961: @example
 5962: TRY
 5963:   foo
 5964: ENDTRY-IFERROR
 5965:   CASE
 5966:     myerror OF ... ( do something about it ) nothrow ENDOF
 5967:     throw \ pass other errors on
 5968:   ENDCASE
 5969: THEN
 5970: @end example
 5971: 
 5972: @progstyle
 5973: As usual, you should ensure that the stack depth is statically known at
 5974: the end: either after the @code{throw} for passing on errors, or after
 5975: the @code{ENDTRY} (or, if you use @code{catch}, after the end of the
 5976: selection construct for handling the error).
 5977: 
 5978: There are two alternatives to @code{throw}: @code{Abort"} is conditional
 5979: and you can provide an error message.  @code{Abort} just produces an
 5980: ``Aborted'' error.
 5981: 
 5982: The problem with these words is that exception handlers cannot
 5983: differentiate between different @code{abort"}s; they just look like
 5984: @code{-2 throw} to them (the error message cannot be accessed by
 5985: standard programs).  Similar @code{abort} looks like @code{-1 throw} to
 5986: exception handlers.
 5987: 
 5988: doc-abort"
 5989: doc-abort
 5990: 
 5991: 
 5992: 
 5993: @c -------------------------------------------------------------
 5994: @node Defining Words, Interpretation and Compilation Semantics, Control Structures, Words
 5995: @section Defining Words
 5996: @cindex defining words
 5997: 
 5998: Defining words are used to extend Forth by creating new entries in the dictionary.
 5999: 
 6000: @menu
 6001: * CREATE::                      
 6002: * Variables::                   Variables and user variables
 6003: * Constants::                   
 6004: * Values::                      Initialised variables
 6005: * Colon Definitions::           
 6006: * Anonymous Definitions::       Definitions without names
 6007: * Supplying names::             Passing definition names as strings
 6008: * User-defined Defining Words::  
 6009: * Deferred Words::              Allow forward references
 6010: * Aliases::                     
 6011: @end menu
 6012: 
 6013: @node CREATE, Variables, Defining Words, Defining Words
 6014: @subsection @code{CREATE}
 6015: @cindex simple defining words
 6016: @cindex defining words, simple
 6017: 
 6018: Defining words are used to create new entries in the dictionary. The
 6019: simplest defining word is @code{CREATE}. @code{CREATE} is used like
 6020: this:
 6021: 
 6022: @example
 6023: CREATE new-word1
 6024: @end example
 6025: 
 6026: @code{CREATE} is a parsing word, i.e., it takes an argument from the
 6027: input stream (@code{new-word1} in our example).  It generates a
 6028: dictionary entry for @code{new-word1}. When @code{new-word1} is
 6029: executed, all that it does is leave an address on the stack. The address
 6030: represents the value of the data space pointer (@code{HERE}) at the time
 6031: that @code{new-word1} was defined. Therefore, @code{CREATE} is a way of
 6032: associating a name with the address of a region of memory.
 6033: 
 6034: doc-create
 6035: 
 6036: Note that in ANS Forth guarantees only for @code{create} that its body
 6037: is in dictionary data space (i.e., where @code{here}, @code{allot}
 6038: etc. work, @pxref{Dictionary allocation}).  Also, in ANS Forth only
 6039: @code{create}d words can be modified with @code{does>}
 6040: (@pxref{User-defined Defining Words}).  And in ANS Forth @code{>body}
 6041: can only be applied to @code{create}d words.
 6042: 
 6043: By extending this example to reserve some memory in data space, we end
 6044: up with something like a @i{variable}. Here are two different ways to do
 6045: it:
 6046: 
 6047: @example
 6048: CREATE new-word2 1 cells allot  \ reserve 1 cell - initial value undefined
 6049: CREATE new-word3 4 ,            \ reserve 1 cell and initialise it (to 4)
 6050: @end example
 6051: 
 6052: The variable can be examined and modified using @code{@@} (``fetch'') and
 6053: @code{!} (``store'') like this:
 6054: 
 6055: @example
 6056: new-word2 @@ .      \ get address, fetch from it and display
 6057: 1234 new-word2 !   \ new value, get address, store to it
 6058: @end example
 6059: 
 6060: @cindex arrays
 6061: A similar mechanism can be used to create arrays. For example, an
 6062: 80-character text input buffer:
 6063: 
 6064: @example
 6065: CREATE text-buf 80 chars allot
 6066: 
 6067: text-buf 0 chars + c@@ \ the 1st character (offset 0)
 6068: text-buf 3 chars + c@@ \ the 4th character (offset 3)
 6069: @end example
 6070: 
 6071: You can build arbitrarily complex data structures by allocating
 6072: appropriate areas of memory. For further discussions of this, and to
 6073: learn about some Gforth tools that make it easier,
 6074: @xref{Structures}.
 6075: 
 6076: 
 6077: @node Variables, Constants, CREATE, Defining Words
 6078: @subsection Variables
 6079: @cindex variables
 6080: 
 6081: The previous section showed how a sequence of commands could be used to
 6082: generate a variable.  As a final refinement, the whole code sequence can
 6083: be wrapped up in a defining word (pre-empting the subject of the next
 6084: section), making it easier to create new variables:
 6085: 
 6086: @example
 6087: : myvariableX ( "name" -- a-addr ) CREATE 1 cells allot ;
 6088: : myvariable0 ( "name" -- a-addr ) CREATE 0 , ;
 6089: 
 6090: myvariableX foo \ variable foo starts off with an unknown value
 6091: myvariable0 joe \ whilst joe is initialised to 0
 6092: 
 6093: 45 3 * foo !   \ set foo to 135
 6094: 1234 joe !     \ set joe to 1234
 6095: 3 joe +!       \ increment joe by 3.. to 1237
 6096: @end example
 6097: 
 6098: Not surprisingly, there is no need to define @code{myvariable}, since
 6099: Forth already has a definition @code{Variable}. ANS Forth does not
 6100: guarantee that a @code{Variable} is initialised when it is created
 6101: (i.e., it may behave like @code{myvariableX}). In contrast, Gforth's
 6102: @code{Variable} initialises the variable to 0 (i.e., it behaves exactly
 6103: like @code{myvariable0}). Forth also provides @code{2Variable} and
 6104: @code{fvariable} for double and floating-point variables, respectively
 6105: -- they are initialised to 0. and 0e in Gforth. If you use a @code{Variable} to
 6106: store a boolean, you can use @code{on} and @code{off} to toggle its
 6107: state.
 6108: 
 6109: doc-variable
 6110: doc-2variable
 6111: doc-fvariable
 6112: 
 6113: @cindex user variables
 6114: @cindex user space
 6115: The defining word @code{User} behaves in the same way as @code{Variable}.
 6116: The difference is that it reserves space in @i{user (data) space} rather
 6117: than normal data space. In a Forth system that has a multi-tasker, each
 6118: task has its own set of user variables.
 6119: 
 6120: doc-user
 6121: @c doc-udp
 6122: @c doc-uallot
 6123: 
 6124: @comment TODO is that stuff about user variables strictly correct? Is it
 6125: @comment just terminal tasks that have user variables?
 6126: @comment should document tasker.fs (with some examples) elsewhere
 6127: @comment in this manual, then expand on user space and user variables.
 6128: 
 6129: @node Constants, Values, Variables, Defining Words
 6130: @subsection Constants
 6131: @cindex constants
 6132: 
 6133: @code{Constant} allows you to declare a fixed value and refer to it by
 6134: name. For example:
 6135: 
 6136: @example
 6137: 12 Constant INCHES-PER-FOOT
 6138: 3E+08 fconstant SPEED-O-LIGHT
 6139: @end example
 6140: 
 6141: A @code{Variable} can be both read and written, so its run-time
 6142: behaviour is to supply an address through which its current value can be
 6143: manipulated. In contrast, the value of a @code{Constant} cannot be
 6144: changed once it has been declared@footnote{Well, often it can be -- but
 6145: not in a Standard, portable way. It's safer to use a @code{Value} (read
 6146: on).} so it's not necessary to supply the address -- it is more
 6147: efficient to return the value of the constant directly. That's exactly
 6148: what happens; the run-time effect of a constant is to put its value on
 6149: the top of the stack (You can find one
 6150: way of implementing @code{Constant} in @ref{User-defined Defining Words}).
 6151: 
 6152: Forth also provides @code{2Constant} and @code{fconstant} for defining
 6153: double and floating-point constants, respectively.
 6154: 
 6155: doc-constant
 6156: doc-2constant
 6157: doc-fconstant
 6158: 
 6159: @c that's too deep, and it's not necessarily true for all ANS Forths. - anton
 6160: @c nac-> How could that not be true in an ANS Forth? You can't define a
 6161: @c constant, use it and then delete the definition of the constant..
 6162: 
 6163: @c anton->An ANS Forth system can compile a constant to a literal; On
 6164: @c decompilation you would see only the number, just as if it had been used
 6165: @c in the first place.  The word will stay, of course, but it will only be
 6166: @c used by the text interpreter (no run-time duties, except when it is 
 6167: @c POSTPONEd or somesuch).
 6168: 
 6169: @c nac:
 6170: @c I agree that it's rather deep, but IMO it is an important difference
 6171: @c relative to other programming languages.. often it's annoying: it
 6172: @c certainly changes my programming style relative to C.
 6173: 
 6174: @c anton: In what way?
 6175: 
 6176: Constants in Forth behave differently from their equivalents in other
 6177: programming languages. In other languages, a constant (such as an EQU in
 6178: assembler or a #define in C) only exists at compile-time; in the
 6179: executable program the constant has been translated into an absolute
 6180: number and, unless you are using a symbolic debugger, it's impossible to
 6181: know what abstract thing that number represents. In Forth a constant has
 6182: an entry in the header space and remains there after the code that uses
 6183: it has been defined. In fact, it must remain in the dictionary since it
 6184: has run-time duties to perform. For example:
 6185: 
 6186: @example
 6187: 12 Constant INCHES-PER-FOOT
 6188: : FEET-TO-INCHES ( n1 -- n2 ) INCHES-PER-FOOT * ;
 6189: @end example
 6190: 
 6191: @cindex in-lining of constants
 6192: When @code{FEET-TO-INCHES} is executed, it will in turn execute the xt
 6193: associated with the constant @code{INCHES-PER-FOOT}. If you use
 6194: @code{see} to decompile the definition of @code{FEET-TO-INCHES}, you can
 6195: see that it makes a call to @code{INCHES-PER-FOOT}. Some Forth compilers
 6196: attempt to optimise constants by in-lining them where they are used. You
 6197: can force Gforth to in-line a constant like this:
 6198: 
 6199: @example
 6200: : FEET-TO-INCHES ( n1 -- n2 ) [ INCHES-PER-FOOT ] LITERAL * ;
 6201: @end example
 6202: 
 6203: If you use @code{see} to decompile @i{this} version of
 6204: @code{FEET-TO-INCHES}, you can see that @code{INCHES-PER-FOOT} is no
 6205: longer present. To understand how this works, read
 6206: @ref{Interpret/Compile states}, and @ref{Literals}.
 6207: 
 6208: In-lining constants in this way might improve execution time
 6209: fractionally, and can ensure that a constant is now only referenced at
 6210: compile-time. However, the definition of the constant still remains in
 6211: the dictionary. Some Forth compilers provide a mechanism for controlling
 6212: a second dictionary for holding transient words such that this second
 6213: dictionary can be deleted later in order to recover memory
 6214: space. However, there is no standard way of doing this.
 6215: 
 6216: 
 6217: @node Values, Colon Definitions, Constants, Defining Words
 6218: @subsection Values
 6219: @cindex values
 6220: 
 6221: A @code{Value} behaves like a @code{Constant}, but it can be changed.
 6222: @code{TO} is a parsing word that changes a @code{Values}.  In Gforth
 6223: (not in ANS Forth) you can access (and change) a @code{value} also with
 6224: @code{>body}.
 6225: 
 6226: Here are some
 6227: examples:
 6228: 
 6229: @example
 6230: 12 Value APPLES     \ Define APPLES with an initial value of 12
 6231: 34 TO APPLES        \ Change the value of APPLES. TO is a parsing word
 6232: 1 ' APPLES >body +! \ Increment APPLES.  Non-standard usage.
 6233: APPLES              \ puts 35 on the top of the stack.
 6234: @end example
 6235: 
 6236: doc-value
 6237: doc-to
 6238: 
 6239: 
 6240: 
 6241: @node Colon Definitions, Anonymous Definitions, Values, Defining Words
 6242: @subsection Colon Definitions
 6243: @cindex colon definitions
 6244: 
 6245: @example
 6246: : name ( ... -- ... )
 6247:     word1 word2 word3 ;
 6248: @end example
 6249: 
 6250: @noindent
 6251: Creates a word called @code{name} that, upon execution, executes
 6252: @code{word1 word2 word3}. @code{name} is a @dfn{(colon) definition}.
 6253: 
 6254: The explanation above is somewhat superficial. For simple examples of
 6255: colon definitions see @ref{Your first definition}.  For an in-depth
 6256: discussion of some of the issues involved, @xref{Interpretation and
 6257: Compilation Semantics}.
 6258: 
 6259: doc-:
 6260: doc-;
 6261: 
 6262: 
 6263: @node Anonymous Definitions, Supplying names, Colon Definitions, Defining Words
 6264: @subsection Anonymous Definitions
 6265: @cindex colon definitions
 6266: @cindex defining words without name
 6267: 
 6268: Sometimes you want to define an @dfn{anonymous word}; a word without a
 6269: name. You can do this with:
 6270: 
 6271: doc-:noname
 6272: 
 6273: This leaves the execution token for the word on the stack after the
 6274: closing @code{;}. Here's an example in which a deferred word is
 6275: initialised with an @code{xt} from an anonymous colon definition:
 6276: 
 6277: @example
 6278: Defer deferred
 6279: :noname ( ... -- ... )
 6280:   ... ;
 6281: IS deferred
 6282: @end example
 6283: 
 6284: @noindent
 6285: Gforth provides an alternative way of doing this, using two separate
 6286: words:
 6287: 
 6288: doc-noname
 6289: @cindex execution token of last defined word
 6290: doc-latestxt
 6291: 
 6292: @noindent
 6293: The previous example can be rewritten using @code{noname} and
 6294: @code{latestxt}:
 6295: 
 6296: @example
 6297: Defer deferred
 6298: noname : ( ... -- ... )
 6299:   ... ;
 6300: latestxt IS deferred
 6301: @end example
 6302: 
 6303: @noindent
 6304: @code{noname} works with any defining word, not just @code{:}.
 6305: 
 6306: @code{latestxt} also works when the last word was not defined as
 6307: @code{noname}.  It does not work for combined words, though.  It also has
 6308: the useful property that is is valid as soon as the header for a
 6309: definition has been built. Thus:
 6310: 
 6311: @example
 6312: latestxt . : foo [ latestxt . ] ; ' foo .
 6313: @end example
 6314: 
 6315: @noindent
 6316: prints 3 numbers; the last two are the same.
 6317: 
 6318: @node Supplying names, User-defined Defining Words, Anonymous Definitions, Defining Words
 6319: @subsection Supplying the name of a defined word
 6320: @cindex names for defined words
 6321: @cindex defining words, name given in a string
 6322: 
 6323: By default, a defining word takes the name for the defined word from the
 6324: input stream. Sometimes you want to supply the name from a string. You
 6325: can do this with:
 6326: 
 6327: doc-nextname
 6328: 
 6329: For example:
 6330: 
 6331: @example
 6332: s" foo" nextname create
 6333: @end example
 6334: 
 6335: @noindent
 6336: is equivalent to:
 6337: 
 6338: @example
 6339: create foo
 6340: @end example
 6341: 
 6342: @noindent
 6343: @code{nextname} works with any defining word.
 6344: 
 6345: 
 6346: @node User-defined Defining Words, Deferred Words, Supplying names, Defining Words
 6347: @subsection User-defined Defining Words
 6348: @cindex user-defined defining words
 6349: @cindex defining words, user-defined
 6350: 
 6351: You can create a new defining word by wrapping defining-time code around
 6352: an existing defining word and putting the sequence in a colon
 6353: definition. 
 6354: 
 6355: @c anton: This example is very complex and leads in a quite different
 6356: @c direction from the CREATE-DOES> stuff that follows.  It should probably
 6357: @c be done elsewhere, or as a subsubsection of this subsection (or as a
 6358: @c subsection of Defining Words)
 6359: 
 6360: For example, suppose that you have a word @code{stats} that
 6361: gathers statistics about colon definitions given the @i{xt} of the
 6362: definition, and you want every colon definition in your application to
 6363: make a call to @code{stats}. You can define and use a new version of
 6364: @code{:} like this:
 6365: 
 6366: @example
 6367: : stats ( xt -- ) DUP ." (Gathering statistics for " . ." )"
 6368:   ... ;  \ other code
 6369: 
 6370: : my: : latestxt postpone literal ['] stats compile, ;
 6371: 
 6372: my: foo + - ;
 6373: @end example
 6374: 
 6375: When @code{foo} is defined using @code{my:} these steps occur:
 6376: 
 6377: @itemize @bullet
 6378: @item
 6379: @code{my:} is executed.
 6380: @item
 6381: The @code{:} within the definition (the one between @code{my:} and
 6382: @code{latestxt}) is executed, and does just what it always does; it parses
 6383: the input stream for a name, builds a dictionary header for the name
 6384: @code{foo} and switches @code{state} from interpret to compile.
 6385: @item
 6386: The word @code{latestxt} is executed. It puts the @i{xt} for the word that is
 6387: being defined -- @code{foo} -- onto the stack.
 6388: @item
 6389: The code that was produced by @code{postpone literal} is executed; this
 6390: causes the value on the stack to be compiled as a literal in the code
 6391: area of @code{foo}.
 6392: @item
 6393: The code @code{['] stats} compiles a literal into the definition of
 6394: @code{my:}. When @code{compile,} is executed, that literal -- the
 6395: execution token for @code{stats} -- is layed down in the code area of
 6396: @code{foo} , following the literal@footnote{Strictly speaking, the
 6397: mechanism that @code{compile,} uses to convert an @i{xt} into something
 6398: in the code area is implementation-dependent. A threaded implementation
 6399: might spit out the execution token directly whilst another
 6400: implementation might spit out a native code sequence.}.
 6401: @item
 6402: At this point, the execution of @code{my:} is complete, and control
 6403: returns to the text interpreter. The text interpreter is in compile
 6404: state, so subsequent text @code{+ -} is compiled into the definition of
 6405: @code{foo} and the @code{;} terminates the definition as always.
 6406: @end itemize
 6407: 
 6408: You can use @code{see} to decompile a word that was defined using
 6409: @code{my:} and see how it is different from a normal @code{:}
 6410: definition. For example:
 6411: 
 6412: @example
 6413: : bar + - ;  \ like foo but using : rather than my:
 6414: see bar
 6415: : bar
 6416:   + - ;
 6417: see foo
 6418: : foo
 6419:   107645672 stats + - ;
 6420: 
 6421: \ use ' foo . to show that 107645672 is the xt for foo
 6422: @end example
 6423: 
 6424: You can use techniques like this to make new defining words in terms of
 6425: @i{any} existing defining word.
 6426: 
 6427: 
 6428: @cindex defining defining words
 6429: @cindex @code{CREATE} ... @code{DOES>}
 6430: If you want the words defined with your defining words to behave
 6431: differently from words defined with standard defining words, you can
 6432: write your defining word like this:
 6433: 
 6434: @example
 6435: : def-word ( "name" -- )
 6436:     CREATE @i{code1}
 6437: DOES> ( ... -- ... )
 6438:     @i{code2} ;
 6439: 
 6440: def-word name
 6441: @end example
 6442: 
 6443: @cindex child words
 6444: This fragment defines a @dfn{defining word} @code{def-word} and then
 6445: executes it.  When @code{def-word} executes, it @code{CREATE}s a new
 6446: word, @code{name}, and executes the code @i{code1}. The code @i{code2}
 6447: is not executed at this time. The word @code{name} is sometimes called a
 6448: @dfn{child} of @code{def-word}.
 6449: 
 6450: When you execute @code{name}, the address of the body of @code{name} is
 6451: put on the data stack and @i{code2} is executed (the address of the body
 6452: of @code{name} is the address @code{HERE} returns immediately after the
 6453: @code{CREATE}, i.e., the address a @code{create}d word returns by
 6454: default).
 6455: 
 6456: @c anton:
 6457: @c www.dictionary.com says:
 6458: @c at·a·vism: 1.The reappearance of a characteristic in an organism after
 6459: @c several generations of absence, usually caused by the chance
 6460: @c recombination of genes.  2.An individual or a part that exhibits
 6461: @c atavism. Also called throwback.  3.The return of a trait or recurrence
 6462: @c of previous behavior after a period of absence.
 6463: @c
 6464: @c Doesn't seem to fit.
 6465: 
 6466: @c @cindex atavism in child words
 6467: You can use @code{def-word} to define a set of child words that behave
 6468: similarly; they all have a common run-time behaviour determined by
 6469: @i{code2}. Typically, the @i{code1} sequence builds a data area in the
 6470: body of the child word. The structure of the data is common to all
 6471: children of @code{def-word}, but the data values are specific -- and
 6472: private -- to each child word. When a child word is executed, the
 6473: address of its private data area is passed as a parameter on TOS to be
 6474: used and manipulated@footnote{It is legitimate both to read and write to
 6475: this data area.} by @i{code2}.
 6476: 
 6477: The two fragments of code that make up the defining words act (are
 6478: executed) at two completely separate times:
 6479: 
 6480: @itemize @bullet
 6481: @item
 6482: At @i{define time}, the defining word executes @i{code1} to generate a
 6483: child word
 6484: @item
 6485: At @i{child execution time}, when a child word is invoked, @i{code2}
 6486: is executed, using parameters (data) that are private and specific to
 6487: the child word.
 6488: @end itemize
 6489: 
 6490: Another way of understanding the behaviour of @code{def-word} and
 6491: @code{name} is to say that, if you make the following definitions:
 6492: @example
 6493: : def-word1 ( "name" -- )
 6494:     CREATE @i{code1} ;
 6495: 
 6496: : action1 ( ... -- ... )
 6497:     @i{code2} ;
 6498: 
 6499: def-word1 name1
 6500: @end example
 6501: 
 6502: @noindent
 6503: Then using @code{name1 action1} is equivalent to using @code{name}.
 6504: 
 6505: The classic example is that you can define @code{CONSTANT} in this way:
 6506: 
 6507: @example
 6508: : CONSTANT ( w "name" -- )
 6509:     CREATE ,
 6510: DOES> ( -- w )
 6511:     @@ ;
 6512: @end example
 6513: 
 6514: @comment There is a beautiful description of how this works and what
 6515: @comment it does in the Forthwrite 100th edition.. as well as an elegant
 6516: @comment commentary on the Counting Fruits problem.
 6517: 
 6518: When you create a constant with @code{5 CONSTANT five}, a set of
 6519: define-time actions take place; first a new word @code{five} is created,
 6520: then the value 5 is laid down in the body of @code{five} with
 6521: @code{,}. When @code{five} is executed, the address of the body is put on
 6522: the stack, and @code{@@} retrieves the value 5. The word @code{five} has
 6523: no code of its own; it simply contains a data field and a pointer to the
 6524: code that follows @code{DOES>} in its defining word. That makes words
 6525: created in this way very compact.
 6526: 
 6527: The final example in this section is intended to remind you that space
 6528: reserved in @code{CREATE}d words is @i{data} space and therefore can be
 6529: both read and written by a Standard program@footnote{Exercise: use this
 6530: example as a starting point for your own implementation of @code{Value}
 6531: and @code{TO} -- if you get stuck, investigate the behaviour of @code{'} and
 6532: @code{[']}.}:
 6533: 
 6534: @example
 6535: : foo ( "name" -- )
 6536:     CREATE -1 ,
 6537: DOES> ( -- )
 6538:     @@ . ;
 6539: 
 6540: foo first-word
 6541: foo second-word
 6542: 
 6543: 123 ' first-word >BODY !
 6544: @end example
 6545: 
 6546: If @code{first-word} had been a @code{CREATE}d word, we could simply
 6547: have executed it to get the address of its data field. However, since it
 6548: was defined to have @code{DOES>} actions, its execution semantics are to
 6549: perform those @code{DOES>} actions. To get the address of its data field
 6550: it's necessary to use @code{'} to get its xt, then @code{>BODY} to
 6551: translate the xt into the address of the data field.  When you execute
 6552: @code{first-word}, it will display @code{123}. When you execute
 6553: @code{second-word} it will display @code{-1}.
 6554: 
 6555: @cindex stack effect of @code{DOES>}-parts
 6556: @cindex @code{DOES>}-parts, stack effect
 6557: In the examples above the stack comment after the @code{DOES>} specifies
 6558: the stack effect of the defined words, not the stack effect of the
 6559: following code (the following code expects the address of the body on
 6560: the top of stack, which is not reflected in the stack comment). This is
 6561: the convention that I use and recommend (it clashes a bit with using
 6562: locals declarations for stack effect specification, though).
 6563: 
 6564: @menu
 6565: * CREATE..DOES> applications::  
 6566: * CREATE..DOES> details::       
 6567: * Advanced does> usage example::  
 6568: * Const-does>::                 
 6569: @end menu
 6570: 
 6571: @node CREATE..DOES> applications, CREATE..DOES> details, User-defined Defining Words, User-defined Defining Words
 6572: @subsubsection Applications of @code{CREATE..DOES>}
 6573: @cindex @code{CREATE} ... @code{DOES>}, applications
 6574: 
 6575: You may wonder how to use this feature. Here are some usage patterns:
 6576: 
 6577: @cindex factoring similar colon definitions
 6578: When you see a sequence of code occurring several times, and you can
 6579: identify a meaning, you will factor it out as a colon definition. When
 6580: you see similar colon definitions, you can factor them using
 6581: @code{CREATE..DOES>}. E.g., an assembler usually defines several words
 6582: that look very similar:
 6583: @example
 6584: : ori, ( reg-target reg-source n -- )
 6585:     0 asm-reg-reg-imm ;
 6586: : andi, ( reg-target reg-source n -- )
 6587:     1 asm-reg-reg-imm ;
 6588: @end example
 6589: 
 6590: @noindent
 6591: This could be factored with:
 6592: @example
 6593: : reg-reg-imm ( op-code -- )
 6594:     CREATE ,
 6595: DOES> ( reg-target reg-source n -- )
 6596:     @@ asm-reg-reg-imm ;
 6597: 
 6598: 0 reg-reg-imm ori,
 6599: 1 reg-reg-imm andi,
 6600: @end example
 6601: 
 6602: @cindex currying
 6603: Another view of @code{CREATE..DOES>} is to consider it as a crude way to
 6604: supply a part of the parameters for a word (known as @dfn{currying} in
 6605: the functional language community). E.g., @code{+} needs two
 6606: parameters. Creating versions of @code{+} with one parameter fixed can
 6607: be done like this:
 6608: 
 6609: @example
 6610: : curry+ ( n1 "name" -- )
 6611:     CREATE ,
 6612: DOES> ( n2 -- n1+n2 )
 6613:     @@ + ;
 6614: 
 6615:  3 curry+ 3+
 6616: -2 curry+ 2-
 6617: @end example
 6618: 
 6619: 
 6620: @node CREATE..DOES> details, Advanced does> usage example, CREATE..DOES> applications, User-defined Defining Words
 6621: @subsubsection The gory details of @code{CREATE..DOES>}
 6622: @cindex @code{CREATE} ... @code{DOES>}, details
 6623: 
 6624: doc-does>
 6625: 
 6626: @cindex @code{DOES>} in a separate definition
 6627: This means that you need not use @code{CREATE} and @code{DOES>} in the
 6628: same definition; you can put the @code{DOES>}-part in a separate
 6629: definition. This allows us to, e.g., select among different @code{DOES>}-parts:
 6630: @example
 6631: : does1 
 6632: DOES> ( ... -- ... )
 6633:     ... ;
 6634: 
 6635: : does2
 6636: DOES> ( ... -- ... )
 6637:     ... ;
 6638: 
 6639: : def-word ( ... -- ... )
 6640:     create ...
 6641:     IF
 6642:        does1
 6643:     ELSE
 6644:        does2
 6645:     ENDIF ;
 6646: @end example
 6647: 
 6648: In this example, the selection of whether to use @code{does1} or
 6649: @code{does2} is made at definition-time; at the time that the child word is
 6650: @code{CREATE}d.
 6651: 
 6652: @cindex @code{DOES>} in interpretation state
 6653: In a standard program you can apply a @code{DOES>}-part only if the last
 6654: word was defined with @code{CREATE}. In Gforth, the @code{DOES>}-part
 6655: will override the behaviour of the last word defined in any case. In a
 6656: standard program, you can use @code{DOES>} only in a colon
 6657: definition. In Gforth, you can also use it in interpretation state, in a
 6658: kind of one-shot mode; for example:
 6659: @example
 6660: CREATE name ( ... -- ... )
 6661:   @i{initialization}
 6662: DOES>
 6663:   @i{code} ;
 6664: @end example
 6665: 
 6666: @noindent
 6667: is equivalent to the standard:
 6668: @example
 6669: :noname
 6670: DOES>
 6671:     @i{code} ;
 6672: CREATE name EXECUTE ( ... -- ... )
 6673:     @i{initialization}
 6674: @end example
 6675: 
 6676: doc->body
 6677: 
 6678: @node Advanced does> usage example, Const-does>, CREATE..DOES> details, User-defined Defining Words
 6679: @subsubsection Advanced does> usage example
 6680: 
 6681: The MIPS disassembler (@file{arch/mips/disasm.fs}) contains many words
 6682: for disassembling instructions, that follow a very repetetive scheme:
 6683: 
 6684: @example
 6685: :noname @var{disasm-operands} s" @var{inst-name}" type ;
 6686: @var{entry-num} cells @var{table} + !
 6687: @end example
 6688: 
 6689: Of course, this inspires the idea to factor out the commonalities to
 6690: allow a definition like
 6691: 
 6692: @example
 6693: @var{disasm-operands} @var{entry-num} @var{table} define-inst @var{inst-name}
 6694: @end example
 6695: 
 6696: The parameters @var{disasm-operands} and @var{table} are usually
 6697: correlated.  Moreover, before I wrote the disassembler, there already
 6698: existed code that defines instructions like this:
 6699: 
 6700: @example
 6701: @var{entry-num} @var{inst-format} @var{inst-name}
 6702: @end example
 6703: 
 6704: This code comes from the assembler and resides in
 6705: @file{arch/mips/insts.fs}.
 6706: 
 6707: So I had to define the @var{inst-format} words that performed the scheme
 6708: above when executed.  At first I chose to use run-time code-generation:
 6709: 
 6710: @example
 6711: : @var{inst-format} ( entry-num "name" -- ; compiled code: addr w -- )
 6712:   :noname Postpone @var{disasm-operands}
 6713:   name Postpone sliteral Postpone type Postpone ;
 6714:   swap cells @var{table} + ! ;
 6715: @end example
 6716: 
 6717: Note that this supplies the other two parameters of the scheme above.
 6718: 
 6719: An alternative would have been to write this using
 6720: @code{create}/@code{does>}:
 6721: 
 6722: @example
 6723: : @var{inst-format} ( entry-num "name" -- )
 6724:   here name string, ( entry-num c-addr ) \ parse and save "name"
 6725:   noname create , ( entry-num )
 6726:   latestxt swap cells @var{table} + !
 6727: does> ( addr w -- )
 6728:   \ disassemble instruction w at addr
 6729:   @@ >r 
 6730:   @var{disasm-operands}
 6731:   r> count type ;
 6732: @end example
 6733: 
 6734: Somehow the first solution is simpler, mainly because it's simpler to
 6735: shift a string from definition-time to use-time with @code{sliteral}
 6736: than with @code{string,} and friends.
 6737: 
 6738: I wrote a lot of words following this scheme and soon thought about
 6739: factoring out the commonalities among them.  Note that this uses a
 6740: two-level defining word, i.e., a word that defines ordinary defining
 6741: words.
 6742: 
 6743: This time a solution involving @code{postpone} and friends seemed more
 6744: difficult (try it as an exercise), so I decided to use a
 6745: @code{create}/@code{does>} word; since I was already at it, I also used
 6746: @code{create}/@code{does>} for the lower level (try using
 6747: @code{postpone} etc. as an exercise), resulting in the following
 6748: definition:
 6749: 
 6750: @example
 6751: : define-format ( disasm-xt table-xt -- )
 6752:     \ define an instruction format that uses disasm-xt for
 6753:     \ disassembling and enters the defined instructions into table
 6754:     \ table-xt
 6755:     create 2,
 6756: does> ( u "inst" -- )
 6757:     \ defines an anonymous word for disassembling instruction inst,
 6758:     \ and enters it as u-th entry into table-xt
 6759:     2@@ swap here name string, ( u table-xt disasm-xt c-addr ) \ remember string
 6760:     noname create 2,      \ define anonymous word
 6761:     execute latestxt swap ! \ enter xt of defined word into table-xt
 6762: does> ( addr w -- )
 6763:     \ disassemble instruction w at addr
 6764:     2@@ >r ( addr w disasm-xt R: c-addr )
 6765:     execute ( R: c-addr ) \ disassemble operands
 6766:     r> count type ; \ print name 
 6767: @end example
 6768: 
 6769: Note that the tables here (in contrast to above) do the @code{cells +}
 6770: by themselves (that's why you have to pass an xt).  This word is used in
 6771: the following way:
 6772: 
 6773: @example
 6774: ' @var{disasm-operands} ' @var{table} define-format @var{inst-format}
 6775: @end example
 6776: 
 6777: As shown above, the defined instruction format is then used like this:
 6778: 
 6779: @example
 6780: @var{entry-num} @var{inst-format} @var{inst-name}
 6781: @end example
 6782: 
 6783: In terms of currying, this kind of two-level defining word provides the
 6784: parameters in three stages: first @var{disasm-operands} and @var{table},
 6785: then @var{entry-num} and @var{inst-name}, finally @code{addr w}, i.e.,
 6786: the instruction to be disassembled.  
 6787: 
 6788: Of course this did not quite fit all the instruction format names used
 6789: in @file{insts.fs}, so I had to define a few wrappers that conditioned
 6790: the parameters into the right form.
 6791: 
 6792: If you have trouble following this section, don't worry.  First, this is
 6793: involved and takes time (and probably some playing around) to
 6794: understand; second, this is the first two-level
 6795: @code{create}/@code{does>} word I have written in seventeen years of
 6796: Forth; and if I did not have @file{insts.fs} to start with, I may well
 6797: have elected to use just a one-level defining word (with some repeating
 6798: of parameters when using the defining word). So it is not necessary to
 6799: understand this, but it may improve your understanding of Forth.
 6800: 
 6801: 
 6802: @node Const-does>,  , Advanced does> usage example, User-defined Defining Words
 6803: @subsubsection @code{Const-does>}
 6804: 
 6805: A frequent use of @code{create}...@code{does>} is for transferring some
 6806: values from definition-time to run-time.  Gforth supports this use with
 6807: 
 6808: doc-const-does>
 6809: 
 6810: A typical use of this word is:
 6811: 
 6812: @example
 6813: : curry+ ( n1 "name" -- )
 6814: 1 0 CONST-DOES> ( n2 -- n1+n2 )
 6815:     + ;
 6816: 
 6817: 3 curry+ 3+
 6818: @end example
 6819: 
 6820: Here the @code{1 0} means that 1 cell and 0 floats are transferred from
 6821: definition to run-time.
 6822: 
 6823: The advantages of using @code{const-does>} are:
 6824: 
 6825: @itemize
 6826: 
 6827: @item
 6828: You don't have to deal with storing and retrieving the values, i.e.,
 6829: your program becomes more writable and readable.
 6830: 
 6831: @item
 6832: When using @code{does>}, you have to introduce a @code{@@} that cannot
 6833: be optimized away (because you could change the data using
 6834: @code{>body}...@code{!}); @code{const-does>} avoids this problem.
 6835: 
 6836: @end itemize
 6837: 
 6838: An ANS Forth implementation of @code{const-does>} is available in
 6839: @file{compat/const-does.fs}.
 6840: 
 6841: 
 6842: @node Deferred Words, Aliases, User-defined Defining Words, Defining Words
 6843: @subsection Deferred Words
 6844: @cindex deferred words
 6845: 
 6846: The defining word @code{Defer} allows you to define a word by name
 6847: without defining its behaviour; the definition of its behaviour is
 6848: deferred. Here are two situation where this can be useful:
 6849: 
 6850: @itemize @bullet
 6851: @item
 6852: Where you want to allow the behaviour of a word to be altered later, and
 6853: for all precompiled references to the word to change when its behaviour
 6854: is changed.
 6855: @item
 6856: For mutual recursion; @xref{Calls and returns}.
 6857: @end itemize
 6858: 
 6859: In the following example, @code{foo} always invokes the version of
 6860: @code{greet} that prints ``@code{Good morning}'' whilst @code{bar}
 6861: always invokes the version that prints ``@code{Hello}''. There is no way
 6862: of getting @code{foo} to use the later version without re-ordering the
 6863: source code and recompiling it.
 6864: 
 6865: @example
 6866: : greet ." Good morning" ;
 6867: : foo ... greet ... ;
 6868: : greet ." Hello" ;
 6869: : bar ... greet ... ;
 6870: @end example
 6871: 
 6872: This problem can be solved by defining @code{greet} as a @code{Defer}red
 6873: word. The behaviour of a @code{Defer}red word can be defined and
 6874: redefined at any time by using @code{IS} to associate the xt of a
 6875: previously-defined word with it. The previous example becomes:
 6876: 
 6877: @example
 6878: Defer greet ( -- )
 6879: : foo ... greet ... ;
 6880: : bar ... greet ... ;
 6881: : greet1 ( -- ) ." Good morning" ;
 6882: : greet2 ( -- ) ." Hello" ;
 6883: ' greet2 IS greet  \ make greet behave like greet2
 6884: @end example
 6885: 
 6886: @progstyle
 6887: You should write a stack comment for every deferred word, and put only
 6888: XTs into deferred words that conform to this stack effect.  Otherwise
 6889: it's too difficult to use the deferred word.
 6890: 
 6891: A deferred word can be used to improve the statistics-gathering example
 6892: from @ref{User-defined Defining Words}; rather than edit the
 6893: application's source code to change every @code{:} to a @code{my:}, do
 6894: this:
 6895: 
 6896: @example
 6897: : real: : ;     \ retain access to the original
 6898: defer :         \ redefine as a deferred word
 6899: ' my: IS :      \ use special version of :
 6900: \
 6901: \ load application here
 6902: \
 6903: ' real: IS :    \ go back to the original
 6904: @end example
 6905: 
 6906: 
 6907: One thing to note is that @code{IS} has special compilation semantics,
 6908: such that it parses the name at compile time (like @code{TO}):
 6909: 
 6910: @example
 6911: : set-greet ( xt -- )
 6912:   IS greet ;
 6913: 
 6914: ' greet1 set-greet
 6915: @end example
 6916: 
 6917: In situations where @code{IS} does not fit, use @code{defer!} instead.
 6918: 
 6919: A deferred word can only inherit execution semantics from the xt
 6920: (because that is all that an xt can represent -- for more discussion of
 6921: this @pxref{Tokens for Words}); by default it will have default
 6922: interpretation and compilation semantics deriving from this execution
 6923: semantics.  However, you can change the interpretation and compilation
 6924: semantics of the deferred word in the usual ways:
 6925: 
 6926: @example
 6927: : bar .... ; immediate
 6928: Defer fred immediate
 6929: Defer jim
 6930: 
 6931: ' bar IS jim  \ jim has default semantics
 6932: ' bar IS fred \ fred is immediate
 6933: @end example
 6934: 
 6935: doc-defer
 6936: doc-defer!
 6937: doc-is
 6938: doc-defer@
 6939: doc-action-of
 6940: @comment TODO document these: what's defers [is]
 6941: doc-defers
 6942: 
 6943: @c Use @code{words-deferred} to see a list of deferred words.
 6944: 
 6945: Definitions of these words (except @code{defers}) in ANS Forth are
 6946: provided in @file{compat/defer.fs}.
 6947: 
 6948: 
 6949: @node Aliases,  , Deferred Words, Defining Words
 6950: @subsection Aliases
 6951: @cindex aliases
 6952: 
 6953: The defining word @code{Alias} allows you to define a word by name that
 6954: has the same behaviour as some other word. Here are two situation where
 6955: this can be useful:
 6956: 
 6957: @itemize @bullet
 6958: @item
 6959: When you want access to a word's definition from a different word list
 6960: (for an example of this, see the definition of the @code{Root} word list
 6961: in the Gforth source).
 6962: @item
 6963: When you want to create a synonym; a definition that can be known by
 6964: either of two names (for example, @code{THEN} and @code{ENDIF} are
 6965: aliases).
 6966: @end itemize
 6967: 
 6968: Like deferred words, an alias has default compilation and interpretation
 6969: semantics at the beginning (not the modifications of the other word),
 6970: but you can change them in the usual ways (@code{immediate},
 6971: @code{compile-only}). For example:
 6972: 
 6973: @example
 6974: : foo ... ; immediate
 6975: 
 6976: ' foo Alias bar \ bar is not an immediate word
 6977: ' foo Alias fooby immediate \ fooby is an immediate word
 6978: @end example
 6979: 
 6980: Words that are aliases have the same xt, different headers in the
 6981: dictionary, and consequently different name tokens (@pxref{Tokens for
 6982: Words}) and possibly different immediate flags.  An alias can only have
 6983: default or immediate compilation semantics; you can define aliases for
 6984: combined words with @code{interpret/compile:} -- see @ref{Combined words}.
 6985: 
 6986: doc-alias
 6987: 
 6988: 
 6989: @node Interpretation and Compilation Semantics, Tokens for Words, Defining Words, Words
 6990: @section Interpretation and Compilation Semantics
 6991: @cindex semantics, interpretation and compilation
 6992: 
 6993: @c !! state and ' are used without explanation
 6994: @c example for immediate/compile-only? or is the tutorial enough
 6995: 
 6996: @cindex interpretation semantics
 6997: The @dfn{interpretation semantics} of a (named) word are what the text
 6998: interpreter does when it encounters the word in interpret state. It also
 6999: appears in some other contexts, e.g., the execution token returned by
 7000: @code{' @i{word}} identifies the interpretation semantics of @i{word}
 7001: (in other words, @code{' @i{word} execute} is equivalent to
 7002: interpret-state text interpretation of @code{@i{word}}).
 7003: 
 7004: @cindex compilation semantics
 7005: The @dfn{compilation semantics} of a (named) word are what the text
 7006: interpreter does when it encounters the word in compile state. It also
 7007: appears in other contexts, e.g, @code{POSTPONE @i{word}}
 7008: compiles@footnote{In standard terminology, ``appends to the current
 7009: definition''.} the compilation semantics of @i{word}.
 7010: 
 7011: @cindex execution semantics
 7012: The standard also talks about @dfn{execution semantics}. They are used
 7013: only for defining the interpretation and compilation semantics of many
 7014: words. By default, the interpretation semantics of a word are to
 7015: @code{execute} its execution semantics, and the compilation semantics of
 7016: a word are to @code{compile,} its execution semantics.@footnote{In
 7017: standard terminology: The default interpretation semantics are its
 7018: execution semantics; the default compilation semantics are to append its
 7019: execution semantics to the execution semantics of the current
 7020: definition.}
 7021: 
 7022: Unnamed words (@pxref{Anonymous Definitions}) cannot be encountered by
 7023: the text interpreter, ticked, or @code{postpone}d, so they have no
 7024: interpretation or compilation semantics.  Their behaviour is represented
 7025: by their XT (@pxref{Tokens for Words}), and we call it execution
 7026: semantics, too.
 7027: 
 7028: @comment TODO expand, make it co-operate with new sections on text interpreter.
 7029: 
 7030: @cindex immediate words
 7031: @cindex compile-only words
 7032: You can change the semantics of the most-recently defined word:
 7033: 
 7034: 
 7035: doc-immediate
 7036: doc-compile-only
 7037: doc-restrict
 7038: 
 7039: By convention, words with non-default compilation semantics (e.g.,
 7040: immediate words) often have names surrounded with brackets (e.g.,
 7041: @code{[']}, @pxref{Execution token}).
 7042: 
 7043: Note that ticking (@code{'}) a compile-only word gives an error
 7044: (``Interpreting a compile-only word'').
 7045: 
 7046: @menu
 7047: * Combined words::              
 7048: @end menu
 7049: 
 7050: 
 7051: @node Combined words,  , Interpretation and Compilation Semantics, Interpretation and Compilation Semantics
 7052: @subsection Combined Words
 7053: @cindex combined words
 7054: 
 7055: Gforth allows you to define @dfn{combined words} -- words that have an
 7056: arbitrary combination of interpretation and compilation semantics.
 7057: 
 7058: doc-interpret/compile:
 7059: 
 7060: This feature was introduced for implementing @code{TO} and @code{S"}. I
 7061: recommend that you do not define such words, as cute as they may be:
 7062: they make it hard to get at both parts of the word in some contexts.
 7063: E.g., assume you want to get an execution token for the compilation
 7064: part. Instead, define two words, one that embodies the interpretation
 7065: part, and one that embodies the compilation part.  Once you have done
 7066: that, you can define a combined word with @code{interpret/compile:} for
 7067: the convenience of your users.
 7068: 
 7069: You might try to use this feature to provide an optimizing
 7070: implementation of the default compilation semantics of a word. For
 7071: example, by defining:
 7072: @example
 7073: :noname
 7074:    foo bar ;
 7075: :noname
 7076:    POSTPONE foo POSTPONE bar ;
 7077: interpret/compile: opti-foobar
 7078: @end example
 7079: 
 7080: @noindent
 7081: as an optimizing version of:
 7082: 
 7083: @example
 7084: : foobar
 7085:     foo bar ;
 7086: @end example
 7087: 
 7088: Unfortunately, this does not work correctly with @code{[compile]},
 7089: because @code{[compile]} assumes that the compilation semantics of all
 7090: @code{interpret/compile:} words are non-default. I.e., @code{[compile]
 7091: opti-foobar} would compile compilation semantics, whereas
 7092: @code{[compile] foobar} would compile interpretation semantics.
 7093: 
 7094: @cindex state-smart words (are a bad idea)
 7095: @anchor{state-smartness}
 7096: Some people try to use @dfn{state-smart} words to emulate the feature provided
 7097: by @code{interpret/compile:} (words are state-smart if they check
 7098: @code{STATE} during execution). E.g., they would try to code
 7099: @code{foobar} like this:
 7100: 
 7101: @example
 7102: : foobar
 7103:   STATE @@
 7104:   IF ( compilation state )
 7105:     POSTPONE foo POSTPONE bar
 7106:   ELSE
 7107:     foo bar
 7108:   ENDIF ; immediate
 7109: @end example
 7110: 
 7111: Although this works if @code{foobar} is only processed by the text
 7112: interpreter, it does not work in other contexts (like @code{'} or
 7113: @code{POSTPONE}). E.g., @code{' foobar} will produce an execution token
 7114: for a state-smart word, not for the interpretation semantics of the
 7115: original @code{foobar}; when you execute this execution token (directly
 7116: with @code{EXECUTE} or indirectly through @code{COMPILE,}) in compile
 7117: state, the result will not be what you expected (i.e., it will not
 7118: perform @code{foo bar}). State-smart words are a bad idea. Simply don't
 7119: write them@footnote{For a more detailed discussion of this topic, see
 7120: M. Anton Ertl,
 7121: @cite{@uref{http://www.complang.tuwien.ac.at/papers/ertl98.ps.gz,@code{State}-smartness---Why
 7122: it is Evil and How to Exorcise it}}, EuroForth '98.}!
 7123: 
 7124: @cindex defining words with arbitrary semantics combinations
 7125: It is also possible to write defining words that define words with
 7126: arbitrary combinations of interpretation and compilation semantics. In
 7127: general, they look like this:
 7128: 
 7129: @example
 7130: : def-word
 7131:     create-interpret/compile
 7132:     @i{code1}
 7133: interpretation>
 7134:     @i{code2}
 7135: <interpretation
 7136: compilation>
 7137:     @i{code3}
 7138: <compilation ;
 7139: @end example
 7140: 
 7141: For a @i{word} defined with @code{def-word}, the interpretation
 7142: semantics are to push the address of the body of @i{word} and perform
 7143: @i{code2}, and the compilation semantics are to push the address of
 7144: the body of @i{word} and perform @i{code3}. E.g., @code{constant}
 7145: can also be defined like this (except that the defined constants don't
 7146: behave correctly when @code{[compile]}d):
 7147: 
 7148: @example
 7149: : constant ( n "name" -- )
 7150:     create-interpret/compile
 7151:     ,
 7152: interpretation> ( -- n )
 7153:     @@
 7154: <interpretation
 7155: compilation> ( compilation. -- ; run-time. -- n )
 7156:     @@ postpone literal
 7157: <compilation ;
 7158: @end example
 7159: 
 7160: 
 7161: doc-create-interpret/compile
 7162: doc-interpretation>
 7163: doc-<interpretation
 7164: doc-compilation>
 7165: doc-<compilation
 7166: 
 7167: 
 7168: Words defined with @code{interpret/compile:} and
 7169: @code{create-interpret/compile} have an extended header structure that
 7170: differs from other words; however, unless you try to access them with
 7171: plain address arithmetic, you should not notice this. Words for
 7172: accessing the header structure usually know how to deal with this; e.g.,
 7173: @code{'} @i{word} @code{>body} also gives you the body of a word created
 7174: with @code{create-interpret/compile}.
 7175: 
 7176: 
 7177: @c -------------------------------------------------------------
 7178: @node Tokens for Words, Compiling words, Interpretation and Compilation Semantics, Words
 7179: @section Tokens for Words
 7180: @cindex tokens for words
 7181: 
 7182: This section describes the creation and use of tokens that represent
 7183: words.
 7184: 
 7185: @menu
 7186: * Execution token::             represents execution/interpretation semantics
 7187: * Compilation token::           represents compilation semantics
 7188: * Name token::                  represents named words
 7189: @end menu
 7190: 
 7191: @node Execution token, Compilation token, Tokens for Words, Tokens for Words
 7192: @subsection Execution token
 7193: 
 7194: @cindex xt
 7195: @cindex execution token
 7196: An @dfn{execution token} (@i{XT}) represents some behaviour of a word.
 7197: You can use @code{execute} to invoke this behaviour.
 7198: 
 7199: @cindex tick (')
 7200: You can use @code{'} to get an execution token that represents the
 7201: interpretation semantics of a named word:
 7202: 
 7203: @example
 7204: 5 ' .   ( n xt ) 
 7205: execute ( )      \ execute the xt (i.e., ".")
 7206: @end example
 7207: 
 7208: doc-'
 7209: 
 7210: @code{'} parses at run-time; there is also a word @code{[']} that parses
 7211: when it is compiled, and compiles the resulting XT:
 7212: 
 7213: @example
 7214: : foo ['] . execute ;
 7215: 5 foo
 7216: : bar ' execute ; \ by contrast,
 7217: 5 bar .           \ ' parses "." when bar executes
 7218: @end example
 7219: 
 7220: doc-[']
 7221: 
 7222: If you want the execution token of @i{word}, write @code{['] @i{word}}
 7223: in compiled code and @code{' @i{word}} in interpreted code.  Gforth's
 7224: @code{'} and @code{[']} behave somewhat unusually by complaining about
 7225: compile-only words (because these words have no interpretation
 7226: semantics).  You might get what you want by using @code{COMP' @i{word}
 7227: DROP} or @code{[COMP'] @i{word} DROP} (for details @pxref{Compilation
 7228: token}).
 7229: 
 7230: Another way to get an XT is @code{:noname} or @code{latestxt}
 7231: (@pxref{Anonymous Definitions}).  For anonymous words this gives an xt
 7232: for the only behaviour the word has (the execution semantics).  For
 7233: named words, @code{latestxt} produces an XT for the same behaviour it
 7234: would produce if the word was defined anonymously.
 7235: 
 7236: @example
 7237: :noname ." hello" ;
 7238: execute
 7239: @end example
 7240: 
 7241: An XT occupies one cell and can be manipulated like any other cell.
 7242: 
 7243: @cindex code field address
 7244: @cindex CFA
 7245: In ANS Forth the XT is just an abstract data type (i.e., defined by the
 7246: operations that produce or consume it).  For old hands: In Gforth, the
 7247: XT is implemented as a code field address (CFA).
 7248: 
 7249: doc-execute
 7250: doc-perform
 7251: 
 7252: @node Compilation token, Name token, Execution token, Tokens for Words
 7253: @subsection Compilation token
 7254: 
 7255: @cindex compilation token
 7256: @cindex CT (compilation token)
 7257: Gforth represents the compilation semantics of a named word by a
 7258: @dfn{compilation token} consisting of two cells: @i{w xt}. The top cell
 7259: @i{xt} is an execution token. The compilation semantics represented by
 7260: the compilation token can be performed with @code{execute}, which
 7261: consumes the whole compilation token, with an additional stack effect
 7262: determined by the represented compilation semantics.
 7263: 
 7264: At present, the @i{w} part of a compilation token is an execution token,
 7265: and the @i{xt} part represents either @code{execute} or
 7266: @code{compile,}@footnote{Depending upon the compilation semantics of the
 7267: word. If the word has default compilation semantics, the @i{xt} will
 7268: represent @code{compile,}. Otherwise (e.g., for immediate words), the
 7269: @i{xt} will represent @code{execute}.}. However, don't rely on that
 7270: knowledge, unless necessary; future versions of Gforth may introduce
 7271: unusual compilation tokens (e.g., a compilation token that represents
 7272: the compilation semantics of a literal).
 7273: 
 7274: You can perform the compilation semantics represented by the compilation
 7275: token with @code{execute}.  You can compile the compilation semantics
 7276: with @code{postpone,}. I.e., @code{COMP' @i{word} postpone,} is
 7277: equivalent to @code{postpone @i{word}}.
 7278: 
 7279: doc-[comp']
 7280: doc-comp'
 7281: doc-postpone,
 7282: 
 7283: @node Name token,  , Compilation token, Tokens for Words
 7284: @subsection Name token
 7285: 
 7286: @cindex name token
 7287: Gforth represents named words by the @dfn{name token}, (@i{nt}).  Name
 7288: token is an abstract data type that occurs as argument or result of the
 7289: words below.
 7290: 
 7291: @c !! put this elswhere?
 7292: @cindex name field address
 7293: @cindex NFA
 7294: The closest thing to the nt in older Forth systems is the name field
 7295: address (NFA), but there are significant differences: in older Forth
 7296: systems each word had a unique NFA, LFA, CFA and PFA (in this order, or
 7297: LFA, NFA, CFA, PFA) and there were words for getting from one to the
 7298: next.  In contrast, in Gforth 0@dots{}n nts correspond to one xt; there
 7299: is a link field in the structure identified by the name token, but
 7300: searching usually uses a hash table external to these structures; the
 7301: name in Gforth has a cell-wide count-and-flags field, and the nt is not
 7302: implemented as the address of that count field.
 7303: 
 7304: doc-find-name
 7305: doc-latest
 7306: doc->name
 7307: doc-name>int
 7308: doc-name?int
 7309: doc-name>comp
 7310: doc-name>string
 7311: doc-id.
 7312: doc-.name
 7313: doc-.id
 7314: 
 7315: @c ----------------------------------------------------------
 7316: @node Compiling words, The Text Interpreter, Tokens for Words, Words
 7317: @section Compiling words
 7318: @cindex compiling words
 7319: @cindex macros
 7320: 
 7321: In contrast to most other languages, Forth has no strict boundary
 7322: between compilation and run-time.  E.g., you can run arbitrary code
 7323: between defining words (or for computing data used by defining words
 7324: like @code{constant}). Moreover, @code{Immediate} (@pxref{Interpretation
 7325: and Compilation Semantics} and @code{[}...@code{]} (see below) allow
 7326: running arbitrary code while compiling a colon definition (exception:
 7327: you must not allot dictionary space).
 7328: 
 7329: @menu
 7330: * Literals::                    Compiling data values
 7331: * Macros::                      Compiling words
 7332: @end menu
 7333: 
 7334: @node Literals, Macros, Compiling words, Compiling words
 7335: @subsection Literals
 7336: @cindex Literals
 7337: 
 7338: The simplest and most frequent example is to compute a literal during
 7339: compilation.  E.g., the following definition prints an array of strings,
 7340: one string per line:
 7341: 
 7342: @example
 7343: : .strings ( addr u -- ) \ gforth
 7344:     2* cells bounds U+DO
 7345: 	cr i 2@@ type
 7346:     2 cells +LOOP ;  
 7347: @end example
 7348: 
 7349: With a simple-minded compiler like Gforth's, this computes @code{2
 7350: cells} on every loop iteration.  You can compute this value once and for
 7351: all at compile time and compile it into the definition like this:
 7352: 
 7353: @example
 7354: : .strings ( addr u -- ) \ gforth
 7355:     2* cells bounds U+DO
 7356: 	cr i 2@@ type
 7357:     [ 2 cells ] literal +LOOP ;  
 7358: @end example
 7359: 
 7360: @code{[} switches the text interpreter to interpret state (you will get
 7361: an @code{ok} prompt if you type this example interactively and insert a
 7362: newline between @code{[} and @code{]}), so it performs the
 7363: interpretation semantics of @code{2 cells}; this computes a number.
 7364: @code{]} switches the text interpreter back into compile state.  It then
 7365: performs @code{Literal}'s compilation semantics, which are to compile
 7366: this number into the current word.  You can decompile the word with
 7367: @code{see .strings} to see the effect on the compiled code.
 7368: 
 7369: You can also optimize the @code{2* cells} into @code{[ 2 cells ] literal
 7370: *} in this way.
 7371: 
 7372: doc-[
 7373: doc-]
 7374: doc-literal
 7375: doc-]L
 7376: 
 7377: There are also words for compiling other data types than single cells as
 7378: literals:
 7379: 
 7380: doc-2literal
 7381: doc-fliteral
 7382: doc-sliteral
 7383: 
 7384: @cindex colon-sys, passing data across @code{:}
 7385: @cindex @code{:}, passing data across
 7386: You might be tempted to pass data from outside a colon definition to the
 7387: inside on the data stack.  This does not work, because @code{:} puhes a
 7388: colon-sys, making stuff below unaccessible.  E.g., this does not work:
 7389: 
 7390: @example
 7391: 5 : foo literal ; \ error: "unstructured"
 7392: @end example
 7393: 
 7394: Instead, you have to pass the value in some other way, e.g., through a
 7395: variable:
 7396: 
 7397: @example
 7398: variable temp
 7399: 5 temp !
 7400: : foo [ temp @@ ] literal ;
 7401: @end example
 7402: 
 7403: 
 7404: @node Macros,  , Literals, Compiling words
 7405: @subsection Macros
 7406: @cindex Macros
 7407: @cindex compiling compilation semantics
 7408: 
 7409: @code{Literal} and friends compile data values into the current
 7410: definition.  You can also write words that compile other words into the
 7411: current definition.  E.g.,
 7412: 
 7413: @example
 7414: : compile-+ ( -- ) \ compiled code: ( n1 n2 -- n )
 7415:   POSTPONE + ;
 7416: 
 7417: : foo ( n1 n2 -- n )
 7418:   [ compile-+ ] ;
 7419: 1 2 foo .
 7420: @end example
 7421: 
 7422: This is equivalent to @code{: foo + ;} (@code{see foo} to check this).
 7423: What happens in this example?  @code{Postpone} compiles the compilation
 7424: semantics of @code{+} into @code{compile-+}; later the text interpreter
 7425: executes @code{compile-+} and thus the compilation semantics of +, which
 7426: compile (the execution semantics of) @code{+} into
 7427: @code{foo}.@footnote{A recent RFI answer requires that compiling words
 7428: should only be executed in compile state, so this example is not
 7429: guaranteed to work on all standard systems, but on any decent system it
 7430: will work.}
 7431: 
 7432: doc-postpone
 7433: 
 7434: Compiling words like @code{compile-+} are usually immediate (or similar)
 7435: so you do not have to switch to interpret state to execute them;
 7436: modifying the last example accordingly produces:
 7437: 
 7438: @example
 7439: : [compile-+] ( compilation: --; interpretation: -- )
 7440:   \ compiled code: ( n1 n2 -- n )
 7441:   POSTPONE + ; immediate
 7442: 
 7443: : foo ( n1 n2 -- n )
 7444:   [compile-+] ;
 7445: 1 2 foo .
 7446: @end example
 7447: 
 7448: You will occassionally find the need to POSTPONE several words;
 7449: putting POSTPONE before each such word is cumbersome, so Gforth
 7450: provides a more convenient syntax: @code{]] ... [[}.  This
 7451: allows us to write @code{[compile-+]} as:
 7452: 
 7453: @example
 7454: : [compile-+] ( compilation: --; interpretation: -- )
 7455:   ]] + [[ ; immediate
 7456: @end example
 7457: 
 7458: doc-]]
 7459: doc-[[
 7460: 
 7461: The unusual direction of the brackets indicates their function:
 7462: @code{]]} switches from compilation to postponing (i.e., compilation
 7463: of compilation), just like @code{]} switches from immediate execution
 7464: (interpretation) to compilation.  Conversely, @code{[[} switches from
 7465: postponing to compilation, ananlogous to @code{[} which switches from
 7466: compilation to immediate execution.
 7467: 
 7468: The real advantage of @code{]] }...@code{ [[} becomes apparent when
 7469: there are many words to POSTPONE.  E.g., the word
 7470: @code{compile-map-array} (@pxref{Advanced macros Tutorial}) can be
 7471: written much shorter as follows:
 7472: 
 7473: @example
 7474: : compile-map-array ( compilation: xt -- ; run-time: ... addr u -- ... )
 7475: \ at run-time, execute xt ( ... x -- ... ) for each element of the
 7476: \ array beginning at addr and containing u elements
 7477:   @{ xt @}
 7478:   ]] cells over + swap ?do
 7479:     i @@ [[ xt compile, 
 7480:   1 cells ]]L +loop [[ ;
 7481: @end example
 7482: 
 7483: This example also uses @code{]]L} as a shortcut for @code{]] literal}.
 7484: There are also other shortcuts
 7485: 
 7486: doc-]]L
 7487: doc-]]2L
 7488: doc-]]FL
 7489: doc-]]SL
 7490: 
 7491: Note that parsing words don't parse at postpone time; if you want to
 7492: provide the parsed string right away, you have to switch back to
 7493: compilation:
 7494: 
 7495: @example
 7496: ]] ... [[ s" some string" ]]2L ... [[
 7497: ]] ... [[ ['] + ]]L ... [[
 7498: @end example
 7499: 
 7500: Definitions of @code{]]} and friends in ANS Forth are provided in
 7501: @file{compat/macros.fs}.
 7502: 
 7503: Immediate compiling words are similar to macros in other languages (in
 7504: particular, Lisp).  The important differences to macros in, e.g., C are:
 7505: 
 7506: @itemize @bullet
 7507: 
 7508: @item
 7509: You use the same language for defining and processing macros, not a
 7510: separate preprocessing language and processor.
 7511: 
 7512: @item
 7513: Consequently, the full power of Forth is available in macro definitions.
 7514: E.g., you can perform arbitrarily complex computations, or generate
 7515: different code conditionally or in a loop (e.g., @pxref{Advanced macros
 7516: Tutorial}).  This power is very useful when writing a parser generators
 7517: or other code-generating software.
 7518: 
 7519: @item
 7520: Macros defined using @code{postpone} etc. deal with the language at a
 7521: higher level than strings; name binding happens at macro definition
 7522: time, so you can avoid the pitfalls of name collisions that can happen
 7523: in C macros.  Of course, Forth is a liberal language and also allows to
 7524: shoot yourself in the foot with text-interpreted macros like
 7525: 
 7526: @example
 7527: : [compile-+] s" +" evaluate ; immediate
 7528: @end example
 7529: 
 7530: Apart from binding the name at macro use time, using @code{evaluate}
 7531: also makes your definition @code{state}-smart (@pxref{state-smartness}).
 7532: @end itemize
 7533: 
 7534: You may want the macro to compile a number into a word.  The word to do
 7535: it is @code{literal}, but you have to @code{postpone} it, so its
 7536: compilation semantics take effect when the macro is executed, not when
 7537: it is compiled:
 7538: 
 7539: @example
 7540: : [compile-5] ( -- ) \ compiled code: ( -- n )
 7541:   5 POSTPONE literal ; immediate
 7542: 
 7543: : foo [compile-5] ;
 7544: foo .
 7545: @end example
 7546: 
 7547: You may want to pass parameters to a macro, that the macro should
 7548: compile into the current definition.  If the parameter is a number, then
 7549: you can use @code{postpone literal} (similar for other values).
 7550: 
 7551: If you want to pass a word that is to be compiled, the usual way is to
 7552: pass an execution token and @code{compile,} it:
 7553: 
 7554: @example
 7555: : twice1 ( xt -- ) \ compiled code: ... -- ...
 7556:   dup compile, compile, ;
 7557: 
 7558: : 2+ ( n1 -- n2 )
 7559:   [ ' 1+ twice1 ] ;
 7560: @end example
 7561: 
 7562: doc-compile,
 7563: 
 7564: An alternative available in Gforth, that allows you to pass compile-only
 7565: words as parameters is to use the compilation token (@pxref{Compilation
 7566: token}).  The same example in this technique:
 7567: 
 7568: @example
 7569: : twice ( ... ct -- ... ) \ compiled code: ... -- ...
 7570:   2dup 2>r execute 2r> execute ;
 7571: 
 7572: : 2+ ( n1 -- n2 )
 7573:   [ comp' 1+ twice ] ;
 7574: @end example
 7575: 
 7576: In the example above @code{2>r} and @code{2r>} ensure that @code{twice}
 7577: works even if the executed compilation semantics has an effect on the
 7578: data stack.
 7579: 
 7580: You can also define complete definitions with these words; this provides
 7581: an alternative to using @code{does>} (@pxref{User-defined Defining
 7582: Words}).  E.g., instead of
 7583: 
 7584: @example
 7585: : curry+ ( n1 "name" -- )
 7586:     CREATE ,
 7587: DOES> ( n2 -- n1+n2 )
 7588:     @@ + ;
 7589: @end example
 7590: 
 7591: you could define
 7592: 
 7593: @example
 7594: : curry+ ( n1 "name" -- )
 7595:   \ name execution: ( n2 -- n1+n2 )
 7596:   >r : r> POSTPONE literal POSTPONE + POSTPONE ; ;
 7597: 
 7598: -3 curry+ 3-
 7599: see 3-
 7600: @end example
 7601: 
 7602: The sequence @code{>r : r>} is necessary, because @code{:} puts a
 7603: colon-sys on the data stack that makes everything below it unaccessible.
 7604: 
 7605: This way of writing defining words is sometimes more, sometimes less
 7606: convenient than using @code{does>} (@pxref{Advanced does> usage
 7607: example}).  One advantage of this method is that it can be optimized
 7608: better, because the compiler knows that the value compiled with
 7609: @code{literal} is fixed, whereas the data associated with a
 7610: @code{create}d word can be changed.
 7611: 
 7612: @c doc-[compile] !! not properly documented
 7613: 
 7614: @c ----------------------------------------------------------
 7615: @node The Text Interpreter, The Input Stream, Compiling words, Words
 7616: @section  The Text Interpreter
 7617: @cindex interpreter - outer
 7618: @cindex text interpreter
 7619: @cindex outer interpreter
 7620: 
 7621: @c Should we really describe all these ugly details?  IMO the text
 7622: @c interpreter should be much cleaner, but that may not be possible within
 7623: @c ANS Forth. - anton
 7624: @c nac-> I wanted to explain how it works to show how you can exploit
 7625: @c it in your own programs. When I was writing a cross-compiler, figuring out
 7626: @c some of these gory details was very helpful to me. None of the textbooks
 7627: @c I've seen cover it, and the most modern Forth textbook -- Forth Inc's,
 7628: @c seems to positively avoid going into too much detail for some of
 7629: @c the internals.
 7630: 
 7631: @c anton: ok.  I wonder, though, if this is the right place; for some stuff
 7632: @c it is; for the ugly details, I would prefer another place.  I wonder
 7633: @c whether we should have a chapter before "Words" that describes some
 7634: @c basic concepts referred to in words, and a chapter after "Words" that
 7635: @c describes implementation details.
 7636: 
 7637: The text interpreter@footnote{This is an expanded version of the
 7638: material in @ref{Introducing the Text Interpreter}.} is an endless loop
 7639: that processes input from the current input device. It is also called
 7640: the outer interpreter, in contrast to the inner interpreter
 7641: (@pxref{Engine}) which executes the compiled Forth code on interpretive
 7642: implementations.
 7643: 
 7644: @cindex interpret state
 7645: @cindex compile state
 7646: The text interpreter operates in one of two states: @dfn{interpret
 7647: state} and @dfn{compile state}. The current state is defined by the
 7648: aptly-named variable @code{state}.
 7649: 
 7650: This section starts by describing how the text interpreter behaves when
 7651: it is in interpret state, processing input from the user input device --
 7652: the keyboard. This is the mode that a Forth system is in after it starts
 7653: up.
 7654: 
 7655: @cindex input buffer
 7656: @cindex terminal input buffer
 7657: The text interpreter works from an area of memory called the @dfn{input
 7658: buffer}@footnote{When the text interpreter is processing input from the
 7659: keyboard, this area of memory is called the @dfn{terminal input buffer}
 7660: (TIB) and is addressed by the (obsolescent) words @code{TIB} and
 7661: @code{#TIB}.}, which stores your keyboard input when you press the
 7662: @key{RET} key. Starting at the beginning of the input buffer, it skips
 7663: leading spaces (called @dfn{delimiters}) then parses a string (a
 7664: sequence of non-space characters) until it reaches either a space
 7665: character or the end of the buffer. Having parsed a string, it makes two
 7666: attempts to process it:
 7667: 
 7668: @cindex dictionary
 7669: @itemize @bullet
 7670: @item
 7671: It looks for the string in a @dfn{dictionary} of definitions. If the
 7672: string is found, the string names a @dfn{definition} (also known as a
 7673: @dfn{word}) and the dictionary search returns information that allows
 7674: the text interpreter to perform the word's @dfn{interpretation
 7675: semantics}. In most cases, this simply means that the word will be
 7676: executed.
 7677: @item
 7678: If the string is not found in the dictionary, the text interpreter
 7679: attempts to treat it as a number, using the rules described in
 7680: @ref{Number Conversion}. If the string represents a legal number in the
 7681: current radix, the number is pushed onto a parameter stack (the data
 7682: stack for integers, the floating-point stack for floating-point
 7683: numbers).
 7684: @end itemize
 7685: 
 7686: If both attempts fail, or if the word is found in the dictionary but has
 7687: no interpretation semantics@footnote{This happens if the word was
 7688: defined as @code{COMPILE-ONLY}.} the text interpreter discards the
 7689: remainder of the input buffer, issues an error message and waits for
 7690: more input. If one of the attempts succeeds, the text interpreter
 7691: repeats the parsing process until the whole of the input buffer has been
 7692: processed, at which point it prints the status message ``@code{ ok}''
 7693: and waits for more input.
 7694: 
 7695: @c anton: this should be in the input stream subsection (or below it)
 7696: 
 7697: @cindex parse area
 7698: The text interpreter keeps track of its position in the input buffer by
 7699: updating a variable called @code{>IN} (pronounced ``to-in''). The value
 7700: of @code{>IN} starts out as 0, indicating an offset of 0 from the start
 7701: of the input buffer. The region from offset @code{>IN @@} to the end of
 7702: the input buffer is called the @dfn{parse area}@footnote{In other words,
 7703: the text interpreter processes the contents of the input buffer by
 7704: parsing strings from the parse area until the parse area is empty.}.
 7705: This example shows how @code{>IN} changes as the text interpreter parses
 7706: the input buffer:
 7707: 
 7708: @example
 7709: : remaining >IN @@ SOURCE 2 PICK - -ROT + SWAP
 7710:   CR ." ->" TYPE ." <-" ; IMMEDIATE 
 7711: 
 7712: 1 2 3 remaining + remaining . 
 7713: 
 7714: : foo 1 2 3 remaining SWAP remaining ;
 7715: @end example
 7716: 
 7717: @noindent
 7718: The result is:
 7719: 
 7720: @example
 7721: ->+ remaining .<-
 7722: ->.<-5  ok
 7723: 
 7724: ->SWAP remaining ;-<
 7725: ->;<-  ok
 7726: @end example
 7727: 
 7728: @cindex parsing words
 7729: The value of @code{>IN} can also be modified by a word in the input
 7730: buffer that is executed by the text interpreter.  This means that a word
 7731: can ``trick'' the text interpreter into either skipping a section of the
 7732: input buffer@footnote{This is how parsing words work.} or into parsing a
 7733: section twice. For example:
 7734: 
 7735: @example
 7736: : lat ." <<foo>>" ;
 7737: : flat ." <<bar>>" >IN DUP @@ 3 - SWAP ! ;
 7738: @end example
 7739: 
 7740: @noindent
 7741: When @code{flat} is executed, this output is produced@footnote{Exercise
 7742: for the reader: what would happen if the @code{3} were replaced with
 7743: @code{4}?}:
 7744: 
 7745: @example
 7746: <<bar>><<foo>>
 7747: @end example
 7748: 
 7749: This technique can be used to work around some of the interoperability
 7750: problems of parsing words.  Of course, it's better to avoid parsing
 7751: words where possible.
 7752: 
 7753: @noindent
 7754: Two important notes about the behaviour of the text interpreter:
 7755: 
 7756: @itemize @bullet
 7757: @item
 7758: It processes each input string to completion before parsing additional
 7759: characters from the input buffer.
 7760: @item
 7761: It treats the input buffer as a read-only region (and so must your code).
 7762: @end itemize
 7763: 
 7764: @noindent
 7765: When the text interpreter is in compile state, its behaviour changes in
 7766: these ways:
 7767: 
 7768: @itemize @bullet
 7769: @item
 7770: If a parsed string is found in the dictionary, the text interpreter will
 7771: perform the word's @dfn{compilation semantics}. In most cases, this
 7772: simply means that the execution semantics of the word will be appended
 7773: to the current definition.
 7774: @item
 7775: When a number is encountered, it is compiled into the current definition
 7776: (as a literal) rather than being pushed onto a parameter stack.
 7777: @item
 7778: If an error occurs, @code{state} is modified to put the text interpreter
 7779: back into interpret state.
 7780: @item
 7781: Each time a line is entered from the keyboard, Gforth prints
 7782: ``@code{ compiled}'' rather than `` @code{ok}''.
 7783: @end itemize
 7784: 
 7785: @cindex text interpreter - input sources
 7786: When the text interpreter is using an input device other than the
 7787: keyboard, its behaviour changes in these ways:
 7788: 
 7789: @itemize @bullet
 7790: @item
 7791: When the parse area is empty, the text interpreter attempts to refill
 7792: the input buffer from the input source. When the input source is
 7793: exhausted, the input source is set back to the previous input source.
 7794: @item
 7795: It doesn't print out ``@code{ ok}'' or ``@code{ compiled}'' messages each
 7796: time the parse area is emptied.
 7797: @item
 7798: If an error occurs, the input source is set back to the user input
 7799: device.
 7800: @end itemize
 7801: 
 7802: You can read about this in more detail in @ref{Input Sources}.
 7803: 
 7804: doc->in
 7805: doc-source
 7806: 
 7807: doc-tib
 7808: doc-#tib
 7809: 
 7810: 
 7811: @menu
 7812: * Input Sources::               
 7813: * Number Conversion::           
 7814: * Interpret/Compile states::    
 7815: * Interpreter Directives::      
 7816: @end menu
 7817: 
 7818: @node Input Sources, Number Conversion, The Text Interpreter, The Text Interpreter
 7819: @subsection Input Sources
 7820: @cindex input sources
 7821: @cindex text interpreter - input sources
 7822: 
 7823: By default, the text interpreter processes input from the user input
 7824: device (the keyboard) when Forth starts up. The text interpreter can
 7825: process input from any of these sources:
 7826: 
 7827: @itemize @bullet
 7828: @item
 7829: The user input device -- the keyboard.
 7830: @item
 7831: A file, using the words described in @ref{Forth source files}.
 7832: @item
 7833: A block, using the words described in @ref{Blocks}.
 7834: @item
 7835: A text string, using @code{evaluate}.
 7836: @end itemize
 7837: 
 7838: A program can identify the current input device from the values of
 7839: @code{source-id} and @code{blk}.
 7840: 
 7841: 
 7842: doc-source-id
 7843: doc-blk
 7844: 
 7845: doc-save-input
 7846: doc-restore-input
 7847: 
 7848: doc-evaluate
 7849: doc-query
 7850: 
 7851: 
 7852: 
 7853: @node Number Conversion, Interpret/Compile states, Input Sources, The Text Interpreter
 7854: @subsection Number Conversion
 7855: @cindex number conversion
 7856: @cindex double-cell numbers, input format
 7857: @cindex input format for double-cell numbers
 7858: @cindex single-cell numbers, input format
 7859: @cindex input format for single-cell numbers
 7860: @cindex floating-point numbers, input format
 7861: @cindex input format for floating-point numbers
 7862: 
 7863: This section describes the rules that the text interpreter uses when it
 7864: tries to convert a string into a number.
 7865: 
 7866: Let <digit> represent any character that is a legal digit in the current
 7867: number base@footnote{For example, 0-9 when the number base is decimal or
 7868: 0-9, A-F when the number base is hexadecimal.}.
 7869: 
 7870: Let <decimal digit> represent any character in the range 0-9.
 7871: 
 7872: Let @{@i{a b}@} represent the @i{optional} presence of any of the characters
 7873: in the braces (@i{a} or @i{b} or neither).
 7874: 
 7875: Let * represent any number of instances of the previous character
 7876: (including none).
 7877: 
 7878: Let any other character represent itself.
 7879: 
 7880: @noindent
 7881: Now, the conversion rules are:
 7882: 
 7883: @itemize @bullet
 7884: @item
 7885: A string of the form <digit><digit>* is treated as a single-precision
 7886: (cell-sized) positive integer. Examples are 0 123 6784532 32343212343456 42
 7887: @item
 7888: A string of the form -<digit><digit>* is treated as a single-precision
 7889: (cell-sized) negative integer, and is represented using 2's-complement
 7890: arithmetic. Examples are -45 -5681 -0
 7891: @item
 7892: A string of the form <digit><digit>*.<digit>* is treated as a double-precision
 7893: (double-cell-sized) positive integer. Examples are 3465. 3.465 34.65
 7894: (all three of these represent the same number).
 7895: @item
 7896: A string of the form -<digit><digit>*.<digit>* is treated as a
 7897: double-precision (double-cell-sized) negative integer, and is
 7898: represented using 2's-complement arithmetic. Examples are -3465. -3.465
 7899: -34.65 (all three of these represent the same number).
 7900: @item
 7901: A string of the form @{+ -@}<decimal digit>@{.@}<decimal digit>*@{e
 7902: E@}@{+ -@}<decimal digit><decimal digit>* is treated as a floating-point
 7903: number. Examples are 1e 1e0 1.e 1.e0 +1e+0 (which all represent the same
 7904: number) +12.E-4
 7905: @end itemize
 7906: 
 7907: By default, the number base used for integer number conversion is
 7908: given by the contents of the variable @code{base}.  Note that a lot of
 7909: confusion can result from unexpected values of @code{base}.  If you
 7910: change @code{base} anywhere, make sure to save the old value and
 7911: restore it afterwards; better yet, use @code{base-execute}, which does
 7912: this for you.  In general I recommend keeping @code{base} decimal, and
 7913: using the prefixes described below for the popular non-decimal bases.
 7914: 
 7915: doc-dpl
 7916: doc-base-execute
 7917: doc-base
 7918: doc-hex
 7919: doc-decimal
 7920: 
 7921: @cindex '-prefix for character strings
 7922: @cindex &-prefix for decimal numbers
 7923: @cindex #-prefix for decimal numbers
 7924: @cindex %-prefix for binary numbers
 7925: @cindex $-prefix for hexadecimal numbers
 7926: @cindex 0x-prefix for hexadecimal numbers
 7927: Gforth allows you to override the value of @code{base} by using a
 7928: prefix@footnote{Some Forth implementations provide a similar scheme by
 7929: implementing @code{$} etc. as parsing words that process the subsequent
 7930: number in the input stream and push it onto the stack. For example, see
 7931: @cite{Number Conversion and Literals}, by Wil Baden; Forth Dimensions
 7932: 20(3) pages 26--27. In such implementations, unlike in Gforth, a space
 7933: is required between the prefix and the number.} before the first digit
 7934: of an (integer) number. The following prefixes are supported:
 7935: 
 7936: @itemize @bullet
 7937: @item
 7938: @code{&} -- decimal
 7939: @item
 7940: @code{#} -- decimal
 7941: @item
 7942: @code{%} -- binary
 7943: @item
 7944: @code{$} -- hexadecimal
 7945: @item
 7946: @code{0x} -- hexadecimal, if base<33.
 7947: @item
 7948: @code{'} -- numeric value (e.g., ASCII code) of next character; an
 7949: optional @code{'} may be present after the character.
 7950: @end itemize
 7951: 
 7952: Here are some examples, with the equivalent decimal number shown after
 7953: in braces:
 7954: 
 7955: -$41 (-65), %1001101 (205), %1001.0001 (145 - a double-precision number),
 7956: 'A (65),
 7957: -'a' (-97),
 7958: &905 (905), $abc (2478), $ABC (2478).
 7959: 
 7960: @cindex number conversion - traps for the unwary
 7961: @noindent
 7962: Number conversion has a number of traps for the unwary:
 7963: 
 7964: @itemize @bullet
 7965: @item
 7966: You cannot determine the current number base using the code sequence
 7967: @code{base @@ .} -- the number base is always 10 in the current number
 7968: base. Instead, use something like @code{base @@ dec.}
 7969: @item
 7970: If the number base is set to a value greater than 14 (for example,
 7971: hexadecimal), the number 123E4 is ambiguous; the conversion rules allow
 7972: it to be intepreted as either a single-precision integer or a
 7973: floating-point number (Gforth treats it as an integer). The ambiguity
 7974: can be resolved by explicitly stating the sign of the mantissa and/or
 7975: exponent: 123E+4 or +123E4 -- if the number base is decimal, no
 7976: ambiguity arises; either representation will be treated as a
 7977: floating-point number.
 7978: @item
 7979: There is a word @code{bin} but it does @i{not} set the number base!
 7980: It is used to specify file types.
 7981: @item
 7982: ANS Forth requires the @code{.} of a double-precision number to be the
 7983: final character in the string.  Gforth allows the @code{.} to be
 7984: anywhere after the first digit.
 7985: @item
 7986: The number conversion process does not check for overflow.
 7987: @item
 7988: In an ANS Forth program @code{base} is required to be decimal when
 7989: converting floating-point numbers.  In Gforth, number conversion to
 7990: floating-point numbers always uses base &10, irrespective of the value
 7991: of @code{base}.
 7992: @end itemize
 7993: 
 7994: You can read numbers into your programs with the words described in
 7995: @ref{Line input and conversion}.
 7996: 
 7997: @node Interpret/Compile states, Interpreter Directives, Number Conversion, The Text Interpreter
 7998: @subsection Interpret/Compile states
 7999: @cindex Interpret/Compile states
 8000: 
 8001: A standard program is not permitted to change @code{state}
 8002: explicitly. However, it can change @code{state} implicitly, using the
 8003: words @code{[} and @code{]}. When @code{[} is executed it switches
 8004: @code{state} to interpret state, and therefore the text interpreter
 8005: starts interpreting. When @code{]} is executed it switches @code{state}
 8006: to compile state and therefore the text interpreter starts
 8007: compiling. The most common usage for these words is for switching into
 8008: interpret state and back from within a colon definition; this technique
 8009: can be used to compile a literal (for an example, @pxref{Literals}) or
 8010: for conditional compilation (for an example, @pxref{Interpreter
 8011: Directives}).
 8012: 
 8013: 
 8014: @c This is a bad example: It's non-standard, and it's not necessary.
 8015: @c However, I can't think of a good example for switching into compile
 8016: @c state when there is no current word (@code{state}-smart words are not a
 8017: @c good reason).  So maybe we should use an example for switching into
 8018: @c interpret @code{state} in a colon def. - anton
 8019: @c nac-> I agree. I started out by putting in the example, then realised
 8020: @c that it was non-ANS, so wrote more words around it. I hope this
 8021: @c re-written version is acceptable to you. I do want to keep the example
 8022: @c as it is helpful for showing what is and what is not portable, particularly
 8023: @c where it outlaws a style in common use.
 8024: 
 8025: @c anton: it's more important to show what's portable.  After we have done
 8026: @c that, we can also show what's not.  In any case, I have written a
 8027: @c section Compiling Words which also deals with [ ].
 8028: 
 8029: @c  !! The following example does not work in Gforth 0.5.9 or later.
 8030: 
 8031: @c  @code{[} and @code{]} also give you the ability to switch into compile
 8032: @c  state and back, but we cannot think of any useful Standard application
 8033: @c  for this ability. Pre-ANS Forth textbooks have examples like this:
 8034: 
 8035: @c  @example
 8036: @c  : AA ." this is A" ;
 8037: @c  : BB ." this is B" ;
 8038: @c  : CC ." this is C" ;
 8039: 
 8040: @c  create table ] aa bb cc [
 8041: 
 8042: @c  : go ( n -- ) \ n is offset into table.. 0 for 1st entry
 8043: @c    cells table + @@ execute ;
 8044: @c  @end example
 8045: 
 8046: @c  This example builds a jump table; @code{0 go} will display ``@code{this
 8047: @c  is A}''. Using @code{[} and @code{]} in this example is equivalent to
 8048: @c  defining @code{table} like this:
 8049: 
 8050: @c  @example
 8051: @c  create table ' aa COMPILE, ' bb COMPILE, ' cc COMPILE,
 8052: @c  @end example
 8053: 
 8054: @c  The problem with this code is that the definition of @code{table} is not
 8055: @c  portable -- it @i{compile}s execution tokens into code space. Whilst it
 8056: @c  @i{may} work on systems where code space and data space co-incide, the
 8057: @c  Standard only allows data space to be assigned for a @code{CREATE}d
 8058: @c  word. In addition, the Standard only allows @code{@@} to access data
 8059: @c  space, whilst this example is using it to access code space. The only
 8060: @c  portable, Standard way to build this table is to build it in data space,
 8061: @c  like this:
 8062: 
 8063: @c  @example
 8064: @c  create table ' aa , ' bb , ' cc ,
 8065: @c  @end example
 8066: 
 8067: @c  doc-state
 8068: 
 8069: 
 8070: @node Interpreter Directives,  , Interpret/Compile states, The Text Interpreter
 8071: @subsection Interpreter Directives
 8072: @cindex interpreter directives
 8073: @cindex conditional compilation
 8074: 
 8075: These words are usually used in interpret state; typically to control
 8076: which parts of a source file are processed by the text
 8077: interpreter. There are only a few ANS Forth Standard words, but Gforth
 8078: supplements these with a rich set of immediate control structure words
 8079: to compensate for the fact that the non-immediate versions can only be
 8080: used in compile state (@pxref{Control Structures}). Typical usages:
 8081: 
 8082: @example
 8083: FALSE Constant HAVE-ASSEMBLER
 8084: .
 8085: .
 8086: HAVE-ASSEMBLER [IF]
 8087: : ASSEMBLER-FEATURE
 8088:   ...
 8089: ;
 8090: [ENDIF]
 8091: .
 8092: .
 8093: : SEE
 8094:   ... \ general-purpose SEE code
 8095:   [ HAVE-ASSEMBLER [IF] ]
 8096:   ... \ assembler-specific SEE code
 8097:   [ [ENDIF] ]
 8098: ;
 8099: @end example
 8100: 
 8101: 
 8102: doc-[IF]
 8103: doc-[ELSE]
 8104: doc-[THEN]
 8105: doc-[ENDIF]
 8106: 
 8107: doc-[IFDEF]
 8108: doc-[IFUNDEF]
 8109: 
 8110: doc-[?DO]
 8111: doc-[DO]
 8112: doc-[FOR]
 8113: doc-[LOOP]
 8114: doc-[+LOOP]
 8115: doc-[NEXT]
 8116: 
 8117: doc-[BEGIN]
 8118: doc-[UNTIL]
 8119: doc-[AGAIN]
 8120: doc-[WHILE]
 8121: doc-[REPEAT]
 8122: 
 8123: 
 8124: @c -------------------------------------------------------------
 8125: @node The Input Stream, Word Lists, The Text Interpreter, Words
 8126: @section The Input Stream
 8127: @cindex input stream
 8128: 
 8129: @c !! integrate this better with the "Text Interpreter" section
 8130: The text interpreter reads from the input stream, which can come from
 8131: several sources (@pxref{Input Sources}).  Some words, in particular
 8132: defining words, but also words like @code{'}, read parameters from the
 8133: input stream instead of from the stack.
 8134: 
 8135: Such words are called parsing words, because they parse the input
 8136: stream.  Parsing words are hard to use in other words, because it is
 8137: hard to pass program-generated parameters through the input stream.
 8138: They also usually have an unintuitive combination of interpretation and
 8139: compilation semantics when implemented naively, leading to various
 8140: approaches that try to produce a more intuitive behaviour
 8141: (@pxref{Combined words}).
 8142: 
 8143: It should be obvious by now that parsing words are a bad idea.  If you
 8144: want to implement a parsing word for convenience, also provide a factor
 8145: of the word that does not parse, but takes the parameters on the stack.
 8146: To implement the parsing word on top if it, you can use the following
 8147: words:
 8148: 
 8149: @c anton: these belong in the input stream section
 8150: doc-parse
 8151: doc-parse-name
 8152: doc-parse-word
 8153: doc-name
 8154: doc-word
 8155: doc-refill
 8156: 
 8157: Conversely, if you have the bad luck (or lack of foresight) to have to
 8158: deal with parsing words without having such factors, how do you pass a
 8159: string that is not in the input stream to it?
 8160: 
 8161: doc-execute-parsing
 8162: 
 8163: A definition of this word in ANS Forth is provided in
 8164: @file{compat/execute-parsing.fs}.
 8165: 
 8166: If you want to run a parsing word on a file, the following word should
 8167: help:
 8168: 
 8169: doc-execute-parsing-file
 8170: 
 8171: @c -------------------------------------------------------------
 8172: @node Word Lists, Environmental Queries, The Input Stream, Words
 8173: @section Word Lists
 8174: @cindex word lists
 8175: @cindex header space
 8176: 
 8177: A wordlist is a list of named words; you can add new words and look up
 8178: words by name (and you can remove words in a restricted way with
 8179: markers).  Every named (and @code{reveal}ed) word is in one wordlist.
 8180: 
 8181: @cindex search order stack
 8182: The text interpreter searches the wordlists present in the search order
 8183: (a stack of wordlists), from the top to the bottom.  Within each
 8184: wordlist, the search starts conceptually at the newest word; i.e., if
 8185: two words in a wordlist have the same name, the newer word is found.
 8186: 
 8187: @cindex compilation word list
 8188: New words are added to the @dfn{compilation wordlist} (aka current
 8189: wordlist).
 8190: 
 8191: @cindex wid
 8192: A word list is identified by a cell-sized word list identifier (@i{wid})
 8193: in much the same way as a file is identified by a file handle. The
 8194: numerical value of the wid has no (portable) meaning, and might change
 8195: from session to session.
 8196: 
 8197: The ANS Forth ``Search order'' word set is intended to provide a set of
 8198: low-level tools that allow various different schemes to be
 8199: implemented. Gforth also provides @code{vocabulary}, a traditional Forth
 8200: word.  @file{compat/vocabulary.fs} provides an implementation in ANS
 8201: Forth.
 8202: 
 8203: @comment TODO: locals section refers to here, saying that every word list (aka
 8204: @comment vocabulary) has its own methods for searching etc. Need to document that.
 8205: @c anton: but better in a separate subsection on wordlist internals
 8206: 
 8207: @comment TODO: document markers, reveal, tables, mappedwordlist
 8208: 
 8209: @comment the gforthman- prefix is used to pick out the true definition of a
 8210: @comment word from the source files, rather than some alias.
 8211: 
 8212: doc-forth-wordlist
 8213: doc-definitions
 8214: doc-get-current
 8215: doc-set-current
 8216: doc-get-order
 8217: doc-set-order
 8218: doc-wordlist
 8219: doc-table
 8220: doc->order
 8221: doc-previous
 8222: doc-also
 8223: doc-forth
 8224: doc-only
 8225: doc-order
 8226: 
 8227: doc-find
 8228: doc-search-wordlist
 8229: 
 8230: doc-words
 8231: doc-vlist
 8232: @c doc-words-deferred
 8233: 
 8234: @c doc-mappedwordlist @c map-structure undefined, implemantation-specific
 8235: doc-root
 8236: doc-vocabulary
 8237: doc-seal
 8238: doc-vocs
 8239: doc-current
 8240: doc-context
 8241: 
 8242: 
 8243: @menu
 8244: * Vocabularies::                
 8245: * Why use word lists?::         
 8246: * Word list example::           
 8247: @end menu
 8248: 
 8249: @node Vocabularies, Why use word lists?, Word Lists, Word Lists
 8250: @subsection Vocabularies
 8251: @cindex Vocabularies, detailed explanation
 8252: 
 8253: Here is an example of creating and using a new wordlist using ANS
 8254: Forth words:
 8255: 
 8256: @example
 8257: wordlist constant my-new-words-wordlist
 8258: : my-new-words get-order nip my-new-words-wordlist swap set-order ;
 8259: 
 8260: \ add it to the search order
 8261: also my-new-words
 8262: 
 8263: \ alternatively, add it to the search order and make it
 8264: \ the compilation word list
 8265: also my-new-words definitions
 8266: \ type "order" to see the problem
 8267: @end example
 8268: 
 8269: The problem with this example is that @code{order} has no way to
 8270: associate the name @code{my-new-words} with the wid of the word list (in
 8271: Gforth, @code{order} and @code{vocs} will display @code{???}  for a wid
 8272: that has no associated name). There is no Standard way of associating a
 8273: name with a wid.
 8274: 
 8275: In Gforth, this example can be re-coded using @code{vocabulary}, which
 8276: associates a name with a wid:
 8277: 
 8278: @example
 8279: vocabulary my-new-words
 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: my-new-words definitions
 8287: \ type "order" to see that the problem is solved
 8288: @end example
 8289: 
 8290: 
 8291: @node Why use word lists?, Word list example, Vocabularies, Word Lists
 8292: @subsection Why use word lists?
 8293: @cindex word lists - why use them?
 8294: 
 8295: Here are some reasons why people use wordlists:
 8296: 
 8297: @itemize @bullet
 8298: 
 8299: @c anton: Gforth's hashing implementation makes the search speed
 8300: @c independent from the number of words.  But it is linear with the number
 8301: @c of wordlists that have to be searched, so in effect using more wordlists
 8302: @c actually slows down compilation.
 8303: 
 8304: @c @item
 8305: @c To improve compilation speed by reducing the number of header space
 8306: @c entries that must be searched. This is achieved by creating a new
 8307: @c word list that contains all of the definitions that are used in the
 8308: @c definition of a Forth system but which would not usually be used by
 8309: @c programs running on that system. That word list would be on the search
 8310: @c list when the Forth system was compiled but would be removed from the
 8311: @c search list for normal operation. This can be a useful technique for
 8312: @c low-performance systems (for example, 8-bit processors in embedded
 8313: @c systems) but is unlikely to be necessary in high-performance desktop
 8314: @c systems.
 8315: 
 8316: @item
 8317: To prevent a set of words from being used outside the context in which
 8318: they are valid. Two classic examples of this are an integrated editor
 8319: (all of the edit commands are defined in a separate word list; the
 8320: search order is set to the editor word list when the editor is invoked;
 8321: the old search order is restored when the editor is terminated) and an
 8322: integrated assembler (the op-codes for the machine are defined in a
 8323: separate word list which is used when a @code{CODE} word is defined).
 8324: 
 8325: @item
 8326: To organize the words of an application or library into a user-visible
 8327: set (in @code{forth-wordlist} or some other common wordlist) and a set
 8328: of helper words used just for the implementation (hidden in a separate
 8329: wordlist).  This keeps @code{words}' output smaller, separates
 8330: implementation and interface, and reduces the chance of name conflicts
 8331: within the common wordlist.
 8332: 
 8333: @item
 8334: To prevent a name-space clash between multiple definitions with the same
 8335: name. For example, when building a cross-compiler you might have a word
 8336: @code{IF} that generates conditional code for your target system. By
 8337: placing this definition in a different word list you can control whether
 8338: the host system's @code{IF} or the target system's @code{IF} get used in
 8339: any particular context by controlling the order of the word lists on the
 8340: search order stack.
 8341: 
 8342: @end itemize
 8343: 
 8344: The downsides of using wordlists are:
 8345: 
 8346: @itemize
 8347: 
 8348: @item
 8349: Debugging becomes more cumbersome.
 8350: 
 8351: @item
 8352: Name conflicts worked around with wordlists are still there, and you
 8353: have to arrange the search order carefully to get the desired results;
 8354: if you forget to do that, you get hard-to-find errors (as in any case
 8355: where you read the code differently from the compiler; @code{see} can
 8356: help seeing which of several possible words the name resolves to in such
 8357: cases).  @code{See} displays just the name of the words, not what
 8358: wordlist they belong to, so it might be misleading.  Using unique names
 8359: is a better approach to avoid name conflicts.
 8360: 
 8361: @item
 8362: You have to explicitly undo any changes to the search order.  In many
 8363: cases it would be more convenient if this happened implicitly.  Gforth
 8364: currently does not provide such a feature, but it may do so in the
 8365: future.
 8366: @end itemize
 8367: 
 8368: 
 8369: @node Word list example,  , Why use word lists?, Word Lists
 8370: @subsection Word list example
 8371: @cindex word lists - example
 8372: 
 8373: The following example is from the
 8374: @uref{http://www.complang.tuwien.ac.at/forth/garbage-collection.zip,
 8375: garbage collector} and uses wordlists to separate public words from
 8376: helper words:
 8377: 
 8378: @example
 8379: get-current ( wid )
 8380: vocabulary garbage-collector also garbage-collector definitions
 8381: ... \ define helper words
 8382: ( wid ) set-current \ restore original (i.e., public) compilation wordlist
 8383: ... \ define the public (i.e., API) words
 8384:     \ they can refer to the helper words
 8385: previous \ restore original search order (helper words become invisible)
 8386: @end example
 8387: 
 8388: @c -------------------------------------------------------------
 8389: @node Environmental Queries, Files, Word Lists, Words
 8390: @section Environmental Queries
 8391: @cindex environmental queries
 8392: 
 8393: ANS Forth introduced the idea of ``environmental queries'' as a way
 8394: for a program running on a system to determine certain characteristics of the system.
 8395: The Standard specifies a number of strings that might be recognised by a system.
 8396: 
 8397: The Standard requires that the header space used for environmental queries
 8398: be distinct from the header space used for definitions.
 8399: 
 8400: Typically, environmental queries are supported by creating a set of
 8401: definitions in a word list that is @i{only} used during environmental
 8402: queries; that is what Gforth does. There is no Standard way of adding
 8403: definitions to the set of recognised environmental queries, but any
 8404: implementation that supports the loading of optional word sets must have
 8405: some mechanism for doing this (after loading the word set, the
 8406: associated environmental query string must return @code{true}). In
 8407: Gforth, the word list used to honour environmental queries can be
 8408: manipulated just like any other word list.
 8409: 
 8410: 
 8411: doc-environment?
 8412: doc-environment-wordlist
 8413: 
 8414: doc-gforth
 8415: doc-os-class
 8416: 
 8417: 
 8418: Note that, whilst the documentation for (e.g.) @code{gforth} shows it
 8419: returning two items on the stack, querying it using @code{environment?}
 8420: will return an additional item; the @code{true} flag that shows that the
 8421: string was recognised.
 8422: 
 8423: @comment TODO Document the standard strings or note where they are documented herein
 8424: 
 8425: Here are some examples of using environmental queries:
 8426: 
 8427: @example
 8428: s" address-unit-bits" environment? 0=
 8429: [IF]
 8430:      cr .( environmental attribute address-units-bits unknown... ) cr
 8431: [ELSE]
 8432:      drop \ ensure balanced stack effect
 8433: [THEN]
 8434: 
 8435: \ this might occur in the prelude of a standard program that uses THROW
 8436: s" exception" environment? [IF]
 8437:    0= [IF]
 8438:       : throw abort" exception thrown" ;
 8439:    [THEN]
 8440: [ELSE] \ we don't know, so make sure
 8441:    : throw abort" exception thrown" ;
 8442: [THEN]
 8443: 
 8444: s" gforth" environment? [IF] .( Gforth version ) TYPE
 8445:                         [ELSE] .( Not Gforth..) [THEN]
 8446: 
 8447: \ a program using v*
 8448: s" gforth" environment? [IF]
 8449:   s" 0.5.0" compare 0< [IF] \ v* is a primitive since 0.5.0
 8450:    : v* ( f_addr1 nstride1 f_addr2 nstride2 ucount -- r )
 8451:      >r swap 2swap swap 0e r> 0 ?DO
 8452:        dup f@@ over + 2swap dup f@@ f* f+ over + 2swap
 8453:      LOOP
 8454:      2drop 2drop ; 
 8455:   [THEN]
 8456: [ELSE] \ 
 8457:   : v* ( f_addr1 nstride1 f_addr2 nstride2 ucount -- r )
 8458:   ...
 8459: [THEN]
 8460: @end example
 8461: 
 8462: Here is an example of adding a definition to the environment word list:
 8463: 
 8464: @example
 8465: get-current environment-wordlist set-current
 8466: true constant block
 8467: true constant block-ext
 8468: set-current
 8469: @end example
 8470: 
 8471: You can see what definitions are in the environment word list like this:
 8472: 
 8473: @example
 8474: environment-wordlist >order words previous
 8475: @end example
 8476: 
 8477: 
 8478: @c -------------------------------------------------------------
 8479: @node Files, Blocks, Environmental Queries, Words
 8480: @section Files
 8481: @cindex files
 8482: @cindex I/O - file-handling
 8483: 
 8484: Gforth provides facilities for accessing files that are stored in the
 8485: host operating system's file-system. Files that are processed by Gforth
 8486: can be divided into two categories:
 8487: 
 8488: @itemize @bullet
 8489: @item
 8490: Files that are processed by the Text Interpreter (@dfn{Forth source files}).
 8491: @item
 8492: Files that are processed by some other program (@dfn{general files}).
 8493: @end itemize
 8494: 
 8495: @menu
 8496: * Forth source files::          
 8497: * General files::               
 8498: * Redirection::                 
 8499: * Search Paths::                
 8500: @end menu
 8501: 
 8502: @c -------------------------------------------------------------
 8503: @node Forth source files, General files, Files, Files
 8504: @subsection Forth source files
 8505: @cindex including files
 8506: @cindex Forth source files
 8507: 
 8508: The simplest way to interpret the contents of a file is to use one of
 8509: these two formats:
 8510: 
 8511: @example
 8512: include mysource.fs
 8513: s" mysource.fs" included
 8514: @end example
 8515: 
 8516: You usually want to include a file only if it is not included already
 8517: (by, say, another source file). In that case, you can use one of these
 8518: three formats:
 8519: 
 8520: @example
 8521: require mysource.fs
 8522: needs mysource.fs
 8523: s" mysource.fs" required
 8524: @end example
 8525: 
 8526: @cindex stack effect of included files
 8527: @cindex including files, stack effect
 8528: It is good practice to write your source files such that interpreting them
 8529: does not change the stack. Source files designed in this way can be used with
 8530: @code{required} and friends without complications. For example:
 8531: 
 8532: @example
 8533: 1024 require foo.fs drop
 8534: @end example
 8535: 
 8536: Here you want to pass the argument 1024 (e.g., a buffer size) to
 8537: @file{foo.fs}.  Interpreting @file{foo.fs} has the stack effect ( n -- n
 8538: ), which allows its use with @code{require}.  Of course with such
 8539: parameters to required files, you have to ensure that the first
 8540: @code{require} fits for all uses (i.e., @code{require} it early in the
 8541: master load file).
 8542: 
 8543: doc-include-file
 8544: doc-included
 8545: doc-included?
 8546: doc-include
 8547: doc-required
 8548: doc-require
 8549: doc-needs
 8550: @c doc-init-included-files @c internal
 8551: doc-sourcefilename
 8552: doc-sourceline#
 8553: 
 8554: A definition in ANS Forth for @code{required} is provided in
 8555: @file{compat/required.fs}.
 8556: 
 8557: @c -------------------------------------------------------------
 8558: @node General files, Redirection, Forth source files, Files
 8559: @subsection General files
 8560: @cindex general files
 8561: @cindex file-handling
 8562: 
 8563: Files are opened/created by name and type. The following file access
 8564: methods (FAMs) are recognised:
 8565: 
 8566: @cindex fam (file access method)
 8567: doc-r/o
 8568: doc-r/w
 8569: doc-w/o
 8570: doc-bin
 8571: 
 8572: 
 8573: When a file is opened/created, it returns a file identifier,
 8574: @i{wfileid} that is used for all other file commands. All file
 8575: commands also return a status value, @i{wior}, that is 0 for a
 8576: successful operation and an implementation-defined non-zero value in the
 8577: case of an error.
 8578: 
 8579: 
 8580: doc-open-file
 8581: doc-create-file
 8582: 
 8583: doc-close-file
 8584: doc-delete-file
 8585: doc-rename-file
 8586: doc-read-file
 8587: doc-read-line
 8588: doc-key-file
 8589: doc-key?-file
 8590: doc-write-file
 8591: doc-write-line
 8592: doc-emit-file
 8593: doc-flush-file
 8594: 
 8595: doc-file-status
 8596: doc-file-position
 8597: doc-reposition-file
 8598: doc-file-size
 8599: doc-resize-file
 8600: 
 8601: doc-slurp-file
 8602: doc-slurp-fid
 8603: doc-stdin
 8604: doc-stdout
 8605: doc-stderr
 8606: 
 8607: @c ---------------------------------------------------------
 8608: @node Redirection, Search Paths, General files, Files
 8609: @subsection Redirection
 8610: @cindex Redirection
 8611: @cindex Input Redirection
 8612: @cindex Output Redirection
 8613: 
 8614: You can redirect the output of @code{type} and @code{emit} and all the
 8615: words that use them (all output words that don't have an explicit
 8616: target file) to an arbitrary file with the @code{outfile-execute},
 8617: used like this:
 8618: 
 8619: @example
 8620: : some-warning ( n -- )
 8621:     cr ." warning# " . ;
 8622: 
 8623: : print-some-warning ( n -- )
 8624:     ['] some-warning stderr outfile-execute ;
 8625: @end example
 8626: 
 8627: After @code{some-warning} is executed, the original output direction
 8628: is restored; this construct is safe against exceptions.  Similarly,
 8629: there is @code{infile-execute} for redirecting the input of @code{key}
 8630: and its users (any input word that does not take a file explicitly).
 8631: 
 8632: doc-outfile-execute
 8633: doc-infile-execute
 8634: 
 8635: If you do not want to redirect the input or output to a file, you can
 8636: also make use of the fact that @code{key}, @code{emit} and @code{type}
 8637: are deferred words (@pxref{Deferred Words}).  However, in that case
 8638: you have to worry about the restoration and the protection against
 8639: exceptions yourself; also, note that for redirecting the output in
 8640: this way, you have to redirect both @code{emit} and @code{type}.
 8641: 
 8642: @c ---------------------------------------------------------
 8643: @node Search Paths,  , Redirection, Files
 8644: @subsection Search Paths
 8645: @cindex path for @code{included}
 8646: @cindex file search path
 8647: @cindex @code{include} search path
 8648: @cindex search path for files
 8649: 
 8650: If you specify an absolute filename (i.e., a filename starting with
 8651: @file{/} or @file{~}, or with @file{:} in the second position (as in
 8652: @samp{C:...})) for @code{included} and friends, that file is included
 8653: just as you would expect.
 8654: 
 8655: If the filename starts with @file{./}, this refers to the directory that
 8656: the present file was @code{included} from.  This allows files to include
 8657: other files relative to their own position (irrespective of the current
 8658: working directory or the absolute position).  This feature is essential
 8659: for libraries consisting of several files, where a file may include
 8660: other files from the library.  It corresponds to @code{#include "..."}
 8661: in C. If the current input source is not a file, @file{.} refers to the
 8662: directory of the innermost file being included, or, if there is no file
 8663: being included, to the current working directory.
 8664: 
 8665: For relative filenames (not starting with @file{./}), Gforth uses a
 8666: search path similar to Forth's search order (@pxref{Word Lists}). It
 8667: tries to find the given filename in the directories present in the path,
 8668: and includes the first one it finds. There are separate search paths for
 8669: Forth source files and general files.  If the search path contains the
 8670: directory @file{.}, this refers to the directory of the current file, or
 8671: the working directory, as if the file had been specified with @file{./}.
 8672: 
 8673: Use @file{~+} to refer to the current working directory (as in the
 8674: @code{bash}).
 8675: 
 8676: @c anton: fold the following subsubsections into this subsection?
 8677: 
 8678: @menu
 8679: * Source Search Paths::         
 8680: * General Search Paths::        
 8681: @end menu
 8682: 
 8683: @c ---------------------------------------------------------
 8684: @node Source Search Paths, General Search Paths, Search Paths, Search Paths
 8685: @subsubsection Source Search Paths
 8686: @cindex search path control, source files
 8687: 
 8688: The search path is initialized when you start Gforth (@pxref{Invoking
 8689: Gforth}). You can display it and change it using @code{fpath} in
 8690: combination with the general path handling words.
 8691: 
 8692: doc-fpath
 8693: @c the functionality of the following words is easily available through
 8694: @c   fpath and the general path words.  The may go away.
 8695: @c doc-.fpath
 8696: @c doc-fpath+
 8697: @c doc-fpath=
 8698: @c doc-open-fpath-file
 8699: 
 8700: @noindent
 8701: Here is an example of using @code{fpath} and @code{require}:
 8702: 
 8703: @example
 8704: fpath path= /usr/lib/forth/|./
 8705: require timer.fs
 8706: @end example
 8707: 
 8708: 
 8709: @c ---------------------------------------------------------
 8710: @node General Search Paths,  , Source Search Paths, Search Paths
 8711: @subsubsection General Search Paths
 8712: @cindex search path control, source files
 8713: 
 8714: Your application may need to search files in several directories, like
 8715: @code{included} does. To facilitate this, Gforth allows you to define
 8716: and use your own search paths, by providing generic equivalents of the
 8717: Forth search path words:
 8718: 
 8719: doc-open-path-file
 8720: doc-path-allot
 8721: doc-clear-path
 8722: doc-also-path
 8723: doc-.path
 8724: doc-path+
 8725: doc-path=
 8726: 
 8727: @c anton: better define a word for it, say "path-allot ( ucount -- path-addr )
 8728: 
 8729: Here's an example of creating an empty search path:
 8730: @c
 8731: @example
 8732: create mypath 500 path-allot \ maximum length 500 chars (is checked)
 8733: @end example
 8734: 
 8735: @c -------------------------------------------------------------
 8736: @node Blocks, Other I/O, Files, Words
 8737: @section Blocks
 8738: @cindex I/O - blocks
 8739: @cindex blocks
 8740: 
 8741: When you run Gforth on a modern desk-top computer, it runs under the
 8742: control of an operating system which provides certain services.  One of
 8743: these services is @var{file services}, which allows Forth source code
 8744: and data to be stored in files and read into Gforth (@pxref{Files}).
 8745: 
 8746: Traditionally, Forth has been an important programming language on
 8747: systems where it has interfaced directly to the underlying hardware with
 8748: no intervening operating system. Forth provides a mechanism, called
 8749: @dfn{blocks}, for accessing mass storage on such systems.
 8750: 
 8751: A block is a 1024-byte data area, which can be used to hold data or
 8752: Forth source code. No structure is imposed on the contents of the
 8753: block. A block is identified by its number; blocks are numbered
 8754: contiguously from 1 to an implementation-defined maximum.
 8755: 
 8756: A typical system that used blocks but no operating system might use a
 8757: single floppy-disk drive for mass storage, with the disks formatted to
 8758: provide 256-byte sectors. Blocks would be implemented by assigning the
 8759: first four sectors of the disk to block 1, the second four sectors to
 8760: block 2 and so on, up to the limit of the capacity of the disk. The disk
 8761: would not contain any file system information, just the set of blocks.
 8762: 
 8763: @cindex blocks file
 8764: On systems that do provide file services, blocks are typically
 8765: implemented by storing a sequence of blocks within a single @dfn{blocks
 8766: file}.  The size of the blocks file will be an exact multiple of 1024
 8767: bytes, corresponding to the number of blocks it contains. This is the
 8768: mechanism that Gforth uses.
 8769: 
 8770: @cindex @file{blocks.fb}
 8771: Only one blocks file can be open at a time. If you use block words without
 8772: having specified a blocks file, Gforth defaults to the blocks file
 8773: @file{blocks.fb}. Gforth uses the Forth search path when attempting to
 8774: locate a blocks file (@pxref{Source Search Paths}).
 8775: 
 8776: @cindex block buffers
 8777: When you read and write blocks under program control, Gforth uses a
 8778: number of @dfn{block buffers} as intermediate storage. These buffers are
 8779: not used when you use @code{load} to interpret the contents of a block.
 8780: 
 8781: The behaviour of the block buffers is analagous to that of a cache.
 8782: Each block buffer has three states:
 8783: 
 8784: @itemize @bullet
 8785: @item
 8786: Unassigned
 8787: @item
 8788: Assigned-clean
 8789: @item
 8790: Assigned-dirty
 8791: @end itemize
 8792: 
 8793: Initially, all block buffers are @i{unassigned}. In order to access a
 8794: block, the block (specified by its block number) must be assigned to a
 8795: block buffer.
 8796: 
 8797: The assignment of a block to a block buffer is performed by @code{block}
 8798: or @code{buffer}. Use @code{block} when you wish to modify the existing
 8799: contents of a block. Use @code{buffer} when you don't care about the
 8800: existing contents of the block@footnote{The ANS Forth definition of
 8801: @code{buffer} is intended not to cause disk I/O; if the data associated
 8802: with the particular block is already stored in a block buffer due to an
 8803: earlier @code{block} command, @code{buffer} will return that block
 8804: buffer and the existing contents of the block will be
 8805: available. Otherwise, @code{buffer} will simply assign a new, empty
 8806: block buffer for the block.}.
 8807: 
 8808: Once a block has been assigned to a block buffer using @code{block} or
 8809: @code{buffer}, that block buffer becomes the @i{current block
 8810: buffer}. Data may only be manipulated (read or written) within the
 8811: current block buffer.
 8812: 
 8813: When the contents of the current block buffer has been modified it is
 8814: necessary, @emph{before calling @code{block} or @code{buffer} again}, to
 8815: either abandon the changes (by doing nothing) or mark the block as
 8816: changed (assigned-dirty), using @code{update}. Using @code{update} does
 8817: not change the blocks file; it simply changes a block buffer's state to
 8818: @i{assigned-dirty}.  The block will be written implicitly when it's
 8819: buffer is needed for another block, or explicitly by @code{flush} or
 8820: @code{save-buffers}.
 8821: 
 8822: word @code{Flush} writes all @i{assigned-dirty} blocks back to the
 8823: blocks file on disk. Leaving Gforth with @code{bye} also performs a
 8824: @code{flush}.
 8825: 
 8826: In Gforth, @code{block} and @code{buffer} use a @i{direct-mapped}
 8827: algorithm to assign a block buffer to a block. That means that any
 8828: particular block can only be assigned to one specific block buffer,
 8829: called (for the particular operation) the @i{victim buffer}. If the
 8830: victim buffer is @i{unassigned} or @i{assigned-clean} it is allocated to
 8831: the new block immediately. If it is @i{assigned-dirty} its current
 8832: contents are written back to the blocks file on disk before it is
 8833: allocated to the new block.
 8834: 
 8835: Although no structure is imposed on the contents of a block, it is
 8836: traditional to display the contents as 16 lines each of 64 characters.  A
 8837: block provides a single, continuous stream of input (for example, it
 8838: acts as a single parse area) -- there are no end-of-line characters
 8839: within a block, and no end-of-file character at the end of a
 8840: block. There are two consequences of this:
 8841: 
 8842: @itemize @bullet
 8843: @item
 8844: The last character of one line wraps straight into the first character
 8845: of the following line
 8846: @item
 8847: The word @code{\} -- comment to end of line -- requires special
 8848: treatment; in the context of a block it causes all characters until the
 8849: end of the current 64-character ``line'' to be ignored.
 8850: @end itemize
 8851: 
 8852: In Gforth, when you use @code{block} with a non-existent block number,
 8853: the current blocks file will be extended to the appropriate size and the
 8854: block buffer will be initialised with spaces.
 8855: 
 8856: Gforth includes a simple block editor (type @code{use blocked.fb 0 list}
 8857: for details) but doesn't encourage the use of blocks; the mechanism is
 8858: only provided for backward compatibility -- ANS Forth requires blocks to
 8859: be available when files are.
 8860: 
 8861: Common techniques that are used when working with blocks include:
 8862: 
 8863: @itemize @bullet
 8864: @item
 8865: A screen editor that allows you to edit blocks without leaving the Forth
 8866: environment.
 8867: @item
 8868: Shadow screens; where every code block has an associated block
 8869: containing comments (for example: code in odd block numbers, comments in
 8870: even block numbers). Typically, the block editor provides a convenient
 8871: mechanism to toggle between code and comments.
 8872: @item
 8873: Load blocks; a single block (typically block 1) contains a number of
 8874: @code{thru} commands which @code{load} the whole of the application.
 8875: @end itemize
 8876: 
 8877: See Frank Sergeant's Pygmy Forth to see just how well blocks can be
 8878: integrated into a Forth programming environment.
 8879: 
 8880: @comment TODO what about errors on open-blocks?
 8881: 
 8882: doc-open-blocks
 8883: doc-use
 8884: doc-block-offset
 8885: doc-get-block-fid
 8886: doc-block-position
 8887: 
 8888: doc-list
 8889: doc-scr
 8890: 
 8891: doc-block
 8892: doc-buffer
 8893: 
 8894: doc-empty-buffers
 8895: doc-empty-buffer
 8896: doc-update
 8897: doc-updated?
 8898: doc-save-buffers
 8899: doc-save-buffer
 8900: doc-flush
 8901: 
 8902: doc-load
 8903: doc-thru
 8904: doc-+load
 8905: doc-+thru
 8906: doc---gforthman--->
 8907: doc-block-included
 8908: 
 8909: 
 8910: @c -------------------------------------------------------------
 8911: @node Other I/O, OS command line arguments, Blocks, Words
 8912: @section Other I/O
 8913: @cindex I/O - keyboard and display
 8914: 
 8915: @menu
 8916: * Simple numeric output::       Predefined formats
 8917: * Formatted numeric output::    Formatted (pictured) output
 8918: * String Formats::              How Forth stores strings in memory
 8919: * Displaying characters and strings::  Other stuff
 8920: * Terminal output::             Cursor positioning etc.
 8921: * Single-key input::            
 8922: * Line input and conversion::   
 8923: * Pipes::                       How to create your own pipes
 8924: * Xchars and Unicode::          Non-ASCII characters
 8925: @end menu
 8926: 
 8927: @node Simple numeric output, Formatted numeric output, Other I/O, Other I/O
 8928: @subsection Simple numeric output
 8929: @cindex numeric output - simple/free-format
 8930: 
 8931: The simplest output functions are those that display numbers from the
 8932: data or floating-point stacks. Floating-point output is always displayed
 8933: using base 10. Numbers displayed from the data stack use the value stored
 8934: in @code{base}.
 8935: 
 8936: 
 8937: doc-.
 8938: doc-dec.
 8939: doc-hex.
 8940: doc-u.
 8941: doc-.r
 8942: doc-u.r
 8943: doc-d.
 8944: doc-ud.
 8945: doc-d.r
 8946: doc-ud.r
 8947: doc-f.
 8948: doc-fe.
 8949: doc-fs.
 8950: doc-f.rdp
 8951: 
 8952: Examples of printing the number 1234.5678E23 in the different floating-point output
 8953: formats are shown below:
 8954: 
 8955: @example
 8956: f. 123456779999999000000000000.
 8957: fe. 123.456779999999E24
 8958: fs. 1.23456779999999E26
 8959: @end example
 8960: 
 8961: 
 8962: @node Formatted numeric output, String Formats, Simple numeric output, Other I/O
 8963: @subsection Formatted numeric output
 8964: @cindex formatted numeric output
 8965: @cindex pictured numeric output
 8966: @cindex numeric output - formatted
 8967: 
 8968: Forth traditionally uses a technique called @dfn{pictured numeric
 8969: output} for formatted printing of integers.  In this technique, digits
 8970: are extracted from the number (using the current output radix defined by
 8971: @code{base}), converted to ASCII codes and appended to a string that is
 8972: built in a scratch-pad area of memory (@pxref{core-idef,
 8973: Implementation-defined options, Implementation-defined
 8974: options}). Arbitrary characters can be appended to the string during the
 8975: extraction process. The completed string is specified by an address
 8976: and length and can be manipulated (@code{TYPE}ed, copied, modified)
 8977: under program control.
 8978: 
 8979: All of the integer output words described in the previous section
 8980: (@pxref{Simple numeric output}) are implemented in Gforth using pictured
 8981: numeric output.
 8982: 
 8983: Three important things to remember about pictured numeric output:
 8984: 
 8985: @itemize @bullet
 8986: @item
 8987: It always operates on double-precision numbers; to display a
 8988: single-precision number, convert it first (for ways of doing this
 8989: @pxref{Double precision}).
 8990: @item
 8991: It always treats the double-precision number as though it were
 8992: unsigned. The examples below show ways of printing signed numbers.
 8993: @item
 8994: The string is built up from right to left; least significant digit first.
 8995: @end itemize
 8996: 
 8997: 
 8998: doc-<#
 8999: doc-<<#
 9000: doc-#
 9001: doc-#s
 9002: doc-hold
 9003: doc-sign
 9004: doc-#>
 9005: doc-#>>
 9006: 
 9007: doc-represent
 9008: doc-f>str-rdp
 9009: doc-f>buf-rdp
 9010: 
 9011: 
 9012: @noindent
 9013: Here are some examples of using pictured numeric output:
 9014: 
 9015: @example
 9016: : my-u. ( u -- )
 9017:   \ Simplest use of pns.. behaves like Standard u. 
 9018:   0              \ convert to unsigned double
 9019:   <<#            \ start conversion
 9020:   #s             \ convert all digits
 9021:   #>             \ complete conversion
 9022:   TYPE SPACE     \ display, with trailing space
 9023:   #>> ;          \ release hold area
 9024: 
 9025: : cents-only ( u -- )
 9026:   0              \ convert to unsigned double
 9027:   <<#            \ start conversion
 9028:   # #            \ convert two least-significant digits
 9029:   #>             \ complete conversion, discard other digits
 9030:   TYPE SPACE     \ display, with trailing space
 9031:   #>> ;          \ release hold area
 9032: 
 9033: : dollars-and-cents ( u -- )
 9034:   0              \ convert to unsigned double
 9035:   <<#            \ start conversion
 9036:   # #            \ convert two least-significant digits
 9037:   [char] . hold  \ insert decimal point
 9038:   #s             \ convert remaining digits
 9039:   [char] $ hold  \ append currency symbol
 9040:   #>             \ complete conversion
 9041:   TYPE SPACE     \ display, with trailing space
 9042:   #>> ;          \ release hold area
 9043: 
 9044: : my-. ( n -- )
 9045:   \ handling negatives.. behaves like Standard .
 9046:   s>d            \ convert to signed double
 9047:   swap over dabs \ leave sign byte followed by unsigned double
 9048:   <<#            \ start conversion
 9049:   #s             \ convert all digits
 9050:   rot sign       \ get at sign byte, append "-" if needed
 9051:   #>             \ complete conversion
 9052:   TYPE SPACE     \ display, with trailing space
 9053:   #>> ;          \ release hold area
 9054: 
 9055: : account. ( n -- )
 9056:   \ accountants don't like minus signs, they use parentheses
 9057:   \ for negative numbers
 9058:   s>d            \ convert to signed double
 9059:   swap over dabs \ leave sign byte followed by unsigned double
 9060:   <<#            \ start conversion
 9061:   2 pick         \ get copy of sign byte
 9062:   0< IF [char] ) hold THEN \ right-most character of output
 9063:   #s             \ convert all digits
 9064:   rot            \ get at sign byte
 9065:   0< IF [char] ( hold THEN
 9066:   #>             \ complete conversion
 9067:   TYPE SPACE     \ display, with trailing space
 9068:   #>> ;          \ release hold area
 9069: 
 9070: @end example
 9071: 
 9072: Here are some examples of using these words:
 9073: 
 9074: @example
 9075: 1 my-u. 1
 9076: hex -1 my-u. decimal FFFFFFFF
 9077: 1 cents-only 01
 9078: 1234 cents-only 34
 9079: 2 dollars-and-cents $0.02
 9080: 1234 dollars-and-cents $12.34
 9081: 123 my-. 123
 9082: -123 my. -123
 9083: 123 account. 123
 9084: -456 account. (456)
 9085: @end example
 9086: 
 9087: 
 9088: @node String Formats, Displaying characters and strings, Formatted numeric output, Other I/O
 9089: @subsection String Formats
 9090: @cindex strings - see character strings
 9091: @cindex character strings - formats
 9092: @cindex I/O - see character strings
 9093: @cindex counted strings
 9094: 
 9095: @c anton: this does not really belong here; maybe the memory section,
 9096: @c  or the principles chapter
 9097: 
 9098: Forth commonly uses two different methods for representing character
 9099: strings:
 9100: 
 9101: @itemize @bullet
 9102: @item
 9103: @cindex address of counted string
 9104: @cindex counted string
 9105: As a @dfn{counted string}, represented by a @i{c-addr}. The char
 9106: addressed by @i{c-addr} contains a character-count, @i{n}, of the
 9107: string and the string occupies the subsequent @i{n} char addresses in
 9108: memory.
 9109: @item
 9110: As cell pair on the stack; @i{c-addr u}, where @i{u} is the length
 9111: of the string in characters, and @i{c-addr} is the address of the
 9112: first byte of the string.
 9113: @end itemize
 9114: 
 9115: ANS Forth encourages the use of the second format when representing
 9116: strings.
 9117: 
 9118: 
 9119: doc-count
 9120: 
 9121: 
 9122: For words that move, copy and search for strings see @ref{Memory
 9123: Blocks}. For words that display characters and strings see
 9124: @ref{Displaying characters and strings}.
 9125: 
 9126: @node Displaying characters and strings, Terminal output, String Formats, Other I/O
 9127: @subsection Displaying characters and strings
 9128: @cindex characters - compiling and displaying
 9129: @cindex character strings - compiling and displaying
 9130: 
 9131: This section starts with a glossary of Forth words and ends with a set
 9132: of examples.
 9133: 
 9134: doc-bl
 9135: doc-space
 9136: doc-spaces
 9137: doc-emit
 9138: doc-toupper
 9139: doc-."
 9140: doc-.(
 9141: doc-.\"
 9142: doc-type
 9143: doc-typewhite
 9144: doc-cr
 9145: @cindex cursor control
 9146: doc-s"
 9147: doc-s\"
 9148: doc-c"
 9149: doc-char
 9150: doc-[char]
 9151: 
 9152: 
 9153: @noindent
 9154: As an example, consider the following text, stored in a file @file{test.fs}:
 9155: 
 9156: @example
 9157: .( text-1)
 9158: : my-word
 9159:   ." text-2" cr
 9160:   .( text-3)
 9161: ;
 9162: 
 9163: ." text-4"
 9164: 
 9165: : my-char
 9166:   [char] ALPHABET emit
 9167:   char emit
 9168: ;
 9169: @end example
 9170: 
 9171: When you load this code into Gforth, the following output is generated:
 9172: 
 9173: @example
 9174: @kbd{include test.fs @key{RET}} text-1text-3text-4 ok
 9175: @end example
 9176: 
 9177: @itemize @bullet
 9178: @item
 9179: Messages @code{text-1} and @code{text-3} are displayed because @code{.(} 
 9180: is an immediate word; it behaves in the same way whether it is used inside
 9181: or outside a colon definition.
 9182: @item
 9183: Message @code{text-4} is displayed because of Gforth's added interpretation
 9184: semantics for @code{."}.
 9185: @item
 9186: Message @code{text-2} is @i{not} displayed, because the text interpreter
 9187: performs the compilation semantics for @code{."} within the definition of
 9188: @code{my-word}.
 9189: @end itemize
 9190: 
 9191: Here are some examples of executing @code{my-word} and @code{my-char}:
 9192: 
 9193: @example
 9194: @kbd{my-word @key{RET}} text-2
 9195:  ok
 9196: @kbd{my-char fred @key{RET}} Af ok
 9197: @kbd{my-char jim @key{RET}} Aj ok
 9198: @end example
 9199: 
 9200: @itemize @bullet
 9201: @item
 9202: Message @code{text-2} is displayed because of the run-time behaviour of
 9203: @code{."}.
 9204: @item
 9205: @code{[char]} compiles the ``A'' from ``ALPHABET'' and puts its display code
 9206: on the stack at run-time. @code{emit} always displays the character
 9207: when @code{my-char} is executed.
 9208: @item
 9209: @code{char} parses a string at run-time and the second @code{emit} displays
 9210: the first character of the string.
 9211: @item
 9212: If you type @code{see my-char} you can see that @code{[char]} discarded
 9213: the text ``LPHABET'' and only compiled the display code for ``A'' into the
 9214: definition of @code{my-char}.
 9215: @end itemize
 9216: 
 9217: 
 9218: @node Terminal output, Single-key input, Displaying characters and strings, Other I/O
 9219: @subsection Terminal output
 9220: @cindex output to terminal
 9221: @cindex terminal output
 9222: 
 9223: If you are outputting to a terminal, you may want to control the
 9224: positioning of the cursor:
 9225: @cindex cursor positioning
 9226: 
 9227: doc-at-xy
 9228: 
 9229: In order to know where to position the cursor, it is often helpful to
 9230: know the size of the screen:
 9231: @cindex terminal size 
 9232: 
 9233: doc-form
 9234: 
 9235: And sometimes you want to use:
 9236: @cindex clear screen
 9237: 
 9238: doc-page
 9239: 
 9240: Note that on non-terminals you should use @code{12 emit}, not
 9241: @code{page}, to get a form feed.
 9242: 
 9243: 
 9244: @node Single-key input, Line input and conversion, Terminal output, Other I/O
 9245: @subsection Single-key input
 9246: @cindex single-key input
 9247: @cindex input, single-key
 9248: 
 9249: If you want to get a single printable character, you can use
 9250: @code{key}; to check whether a character is available for @code{key},
 9251: you can use @code{key?}.
 9252: 
 9253: doc-key
 9254: doc-key?
 9255: 
 9256: If you want to process a mix of printable and non-printable
 9257: characters, you can do that with @code{ekey} and friends.  @code{Ekey}
 9258: produces a keyboard event that you have to convert into a character
 9259: with @code{ekey>char} or into a key identifier with @code{ekey>fkey}.
 9260: 
 9261: Typical code for using EKEY looks like this:
 9262: 
 9263: @example
 9264: ekey ekey>char if ( c )
 9265:   ... \ do something with the character
 9266: else ekey>fkey if ( key-id )
 9267:   case
 9268:     k-up                                  of ... endof
 9269:     k-f1                                  of ... endof
 9270:     k-left k-shift-mask or k-ctrl-mask or of ... endof
 9271:     ...
 9272:   endcase
 9273: else ( keyboard-event )
 9274:   drop \ just ignore an unknown keyboard event type
 9275: then then
 9276: @end example
 9277: 
 9278: doc-ekey
 9279: doc-ekey>char
 9280: doc-ekey>fkey
 9281: doc-ekey?
 9282: 
 9283: The key identifiers for cursor keys are:
 9284: 
 9285: doc-k-left
 9286: doc-k-right
 9287: doc-k-up
 9288: doc-k-down
 9289: doc-k-home
 9290: doc-k-end
 9291: doc-k-prior
 9292: doc-k-next
 9293: doc-k-insert
 9294: doc-k-delete
 9295: 
 9296: The key identifiers for function keys (aka keypad keys) are:
 9297: 
 9298: doc-k-f1
 9299: doc-k-f2
 9300: doc-k-f3
 9301: doc-k-f4
 9302: doc-k-f5
 9303: doc-k-f6
 9304: doc-k-f7
 9305: doc-k-f8
 9306: doc-k-f9
 9307: doc-k-f10
 9308: doc-k-f11
 9309: doc-k-f12
 9310: 
 9311: Note that @code{k-f11} and @code{k-f12} are not as widely available.
 9312: 
 9313: You can combine these key identifiers with masks for various shift keys:
 9314: 
 9315: doc-k-shift-mask
 9316: doc-k-ctrl-mask
 9317: doc-k-alt-mask
 9318: 
 9319: Note that, even if a Forth system has @code{ekey>fkey} and the key
 9320: identifier words, the keys are not necessarily available or it may not
 9321: necessarily be able to report all the keys and all the possible
 9322: combinations with shift masks.  Therefore, write your programs in such
 9323: a way that they are still useful even if the keys and key combinations
 9324: cannot be pressed or are not recognized.
 9325: 
 9326: Examples: Older keyboards often do not have an F11 and F12 key.  If
 9327: you run Gforth in an xterm, the xterm catches a number of combinations
 9328: (e.g., @key{Shift-Up}), and never passes it to Gforth.  Finally,
 9329: Gforth currently does not recognize and report combinations with
 9330: multiple shift keys (so the @key{shift-ctrl-left} case in the example
 9331: above would never be entered).
 9332: 
 9333: Gforth recognizes various keys available on ANSI terminals (in MS-DOS
 9334: you need the ANSI.SYS driver to get that behaviour); it works by
 9335: recognizing the escape sequences that ANSI terminals send when such a
 9336: key is pressed.  If you have a terminal that sends other escape
 9337: sequences, you will not get useful results on Gforth.  Other Forth
 9338: systems may work in a different way.
 9339: 
 9340: Gforth also provides a few words for outputting names of function
 9341: keys:
 9342: 
 9343: doc-fkey.
 9344: doc-simple-fkey-string
 9345: 
 9346: 
 9347: @node  Line input and conversion, Pipes, Single-key input, Other I/O
 9348: @subsection Line input and conversion
 9349: @cindex line input from terminal
 9350: @cindex input, linewise from terminal
 9351: @cindex convertin strings to numbers
 9352: @cindex I/O - see input
 9353: 
 9354: For ways of storing character strings in memory see @ref{String Formats}.
 9355: 
 9356: @comment TODO examples for >number >float accept key key? pad parse word refill
 9357: @comment then index them
 9358: 
 9359: Words for inputting one line from the keyboard:
 9360: 
 9361: doc-accept
 9362: doc-edit-line
 9363: 
 9364: Conversion words:
 9365: 
 9366: doc-s>number?
 9367: doc-s>unumber?
 9368: doc->number
 9369: doc->float
 9370: 
 9371: 
 9372: @comment obsolescent words..
 9373: Obsolescent input and conversion words:
 9374: 
 9375: doc-convert
 9376: doc-expect
 9377: doc-span
 9378: 
 9379: 
 9380: @node Pipes, Xchars and Unicode, Line input and conversion, Other I/O
 9381: @subsection Pipes
 9382: @cindex pipes, creating your own
 9383: 
 9384: In addition to using Gforth in pipes created by other processes
 9385: (@pxref{Gforth in pipes}), you can create your own pipe with
 9386: @code{open-pipe}, and read from or write to it.
 9387: 
 9388: doc-open-pipe
 9389: doc-close-pipe
 9390: 
 9391: If you write to a pipe, Gforth can throw a @code{broken-pipe-error}; if
 9392: you don't catch this exception, Gforth will catch it and exit, usually
 9393: silently (@pxref{Gforth in pipes}).  Since you probably do not want
 9394: this, you should wrap a @code{catch} or @code{try} block around the code
 9395: from @code{open-pipe} to @code{close-pipe}, so you can deal with the
 9396: problem yourself, and then return to regular processing.
 9397: 
 9398: doc-broken-pipe-error
 9399: 
 9400: @node Xchars and Unicode,  , Pipes, Other I/O
 9401: @subsection Xchars and Unicode
 9402: 
 9403: ASCII is only appropriate for the English language. Most western
 9404: languages however fit somewhat into the Forth frame, since a byte is
 9405: sufficient to encode the few special characters in each (though not
 9406: always the same encoding can be used; latin-1 is most widely used,
 9407: though). For other languages, different char-sets have to be used,
 9408: several of them variable-width. Most prominent representant is
 9409: UTF-8. Let's call these extended characters xchars. The primitive
 9410: fixed-size characters stored as bytes are called pchars in this
 9411: section.
 9412: 
 9413: The xchar words add a few data types:
 9414: 
 9415: @itemize
 9416: 
 9417: @item
 9418: @var{xc} is an extended char (xchar) on the stack. It occupies one cell,
 9419: and is a subset of unsigned cell. Note: UTF-8 can not store more that
 9420: 31 bits; on 16 bit systems, only the UCS16 subset of the UTF-8
 9421: character set can be used.
 9422: 
 9423: @item
 9424: @var{xc-addr} is the address of an xchar in memory. Alignment
 9425: requirements are the same as @var{c-addr}. The memory representation of an
 9426: xchar differs from the stack representation, and depends on the
 9427: encoding used. An xchar may use a variable number of pchars in memory.
 9428: 
 9429: @item
 9430: @var{xc-addr} @var{u} is a buffer of xchars in memory, starting at
 9431: @var{xc-addr}, @var{u} pchars long.
 9432: 
 9433: @end itemize
 9434: 
 9435: doc-xc-size
 9436: doc-x-size
 9437: doc-xc@+
 9438: doc-xc!+?
 9439: doc-xchar+
 9440: doc-xchar-
 9441: doc-+x/string
 9442: doc-x\string-
 9443: doc--trailing-garbage
 9444: doc-x-width
 9445: doc-xkey
 9446: doc-xemit
 9447: 
 9448: There's a new environment query
 9449: 
 9450: doc-xchar-encoding
 9451: 
 9452: @node OS command line arguments, Locals, Other I/O, Words
 9453: @section OS command line arguments
 9454: @cindex OS command line arguments
 9455: @cindex command line arguments, OS
 9456: @cindex arguments, OS command line
 9457: 
 9458: The usual way to pass arguments to Gforth programs on the command line
 9459: is via the @option{-e} option, e.g.
 9460: 
 9461: @example
 9462: gforth -e "123 456" foo.fs -e bye
 9463: @end example
 9464: 
 9465: However, you may want to interpret the command-line arguments directly.
 9466: In that case, you can access the (image-specific) command-line arguments
 9467: through @code{next-arg}:
 9468: 
 9469: doc-next-arg
 9470: 
 9471: Here's an example program @file{echo.fs} for @code{next-arg}:
 9472: 
 9473: @example
 9474: : echo ( -- )
 9475:     begin
 9476: 	next-arg 2dup 0 0 d<> while
 9477: 	    type space
 9478:     repeat
 9479:     2drop ;
 9480: 
 9481: echo cr bye
 9482: @end example
 9483: 
 9484: This can be invoked with
 9485: 
 9486: @example
 9487: gforth echo.fs hello world
 9488: @end example
 9489: 
 9490: and it will print
 9491: 
 9492: @example
 9493: hello world
 9494: @end example
 9495: 
 9496: The next lower level of dealing with the OS command line are the
 9497: following words:
 9498: 
 9499: doc-arg
 9500: doc-shift-args
 9501: 
 9502: Finally, at the lowest level Gforth provides the following words:
 9503: 
 9504: doc-argc
 9505: doc-argv
 9506: 
 9507: @c -------------------------------------------------------------
 9508: @node Locals, Structures, OS command line arguments, Words
 9509: @section Locals
 9510: @cindex locals
 9511: 
 9512: Local variables can make Forth programming more enjoyable and Forth
 9513: programs easier to read. Unfortunately, the locals of ANS Forth are
 9514: laden with restrictions. Therefore, we provide not only the ANS Forth
 9515: locals wordset, but also our own, more powerful locals wordset (we
 9516: implemented the ANS Forth locals wordset through our locals wordset).
 9517: 
 9518: The ideas in this section have also been published in M. Anton Ertl,
 9519: @cite{@uref{http://www.complang.tuwien.ac.at/papers/ertl94l.ps.gz,
 9520: Automatic Scoping of Local Variables}}, EuroForth '94.
 9521: 
 9522: @menu
 9523: * Gforth locals::               
 9524: * ANS Forth locals::            
 9525: @end menu
 9526: 
 9527: @node Gforth locals, ANS Forth locals, Locals, Locals
 9528: @subsection Gforth locals
 9529: @cindex Gforth locals
 9530: @cindex locals, Gforth style
 9531: 
 9532: Locals can be defined with
 9533: 
 9534: @example
 9535: @{ local1 local2 ... -- comment @}
 9536: @end example
 9537: or
 9538: @example
 9539: @{ local1 local2 ... @}
 9540: @end example
 9541: 
 9542: E.g.,
 9543: @example
 9544: : max @{ n1 n2 -- n3 @}
 9545:  n1 n2 > if
 9546:    n1
 9547:  else
 9548:    n2
 9549:  endif ;
 9550: @end example
 9551: 
 9552: The similarity of locals definitions with stack comments is intended. A
 9553: locals definition often replaces the stack comment of a word. The order
 9554: of the locals corresponds to the order in a stack comment and everything
 9555: after the @code{--} is really a comment.
 9556: 
 9557: This similarity has one disadvantage: It is too easy to confuse locals
 9558: declarations with stack comments, causing bugs and making them hard to
 9559: find. However, this problem can be avoided by appropriate coding
 9560: conventions: Do not use both notations in the same program. If you do,
 9561: they should be distinguished using additional means, e.g. by position.
 9562: 
 9563: @cindex types of locals
 9564: @cindex locals types
 9565: The name of the local may be preceded by a type specifier, e.g.,
 9566: @code{F:} for a floating point value:
 9567: 
 9568: @example
 9569: : CX* @{ F: Ar F: Ai F: Br F: Bi -- Cr Ci @}
 9570: \ complex multiplication
 9571:  Ar Br f* Ai Bi f* f-
 9572:  Ar Bi f* Ai Br f* f+ ;
 9573: @end example
 9574: 
 9575: @cindex flavours of locals
 9576: @cindex locals flavours
 9577: @cindex value-flavoured locals
 9578: @cindex variable-flavoured locals
 9579: Gforth currently supports cells (@code{W:}, @code{W^}), doubles
 9580: (@code{D:}, @code{D^}), floats (@code{F:}, @code{F^}) and characters
 9581: (@code{C:}, @code{C^}) in two flavours: a value-flavoured local (defined
 9582: with @code{W:}, @code{D:} etc.) produces its value and can be changed
 9583: with @code{TO}. A variable-flavoured local (defined with @code{W^} etc.)
 9584: produces its address (which becomes invalid when the variable's scope is
 9585: left). E.g., the standard word @code{emit} can be defined in terms of
 9586: @code{type} like this:
 9587: 
 9588: @example
 9589: : emit @{ C^ char* -- @}
 9590:     char* 1 type ;
 9591: @end example
 9592: 
 9593: @cindex default type of locals
 9594: @cindex locals, default type
 9595: A local without type specifier is a @code{W:} local. Both flavours of
 9596: locals are initialized with values from the data or FP stack.
 9597: 
 9598: Currently there is no way to define locals with user-defined data
 9599: structures, but we are working on it.
 9600: 
 9601: Gforth allows defining locals everywhere in a colon definition. This
 9602: poses the following questions:
 9603: 
 9604: @menu
 9605: * Where are locals visible by name?::  
 9606: * How long do locals live?::    
 9607: * Locals programming style::    
 9608: * Locals implementation::       
 9609: @end menu
 9610: 
 9611: @node Where are locals visible by name?, How long do locals live?, Gforth locals, Gforth locals
 9612: @subsubsection Where are locals visible by name?
 9613: @cindex locals visibility
 9614: @cindex visibility of locals
 9615: @cindex scope of locals
 9616: 
 9617: Basically, the answer is that locals are visible where you would expect
 9618: it in block-structured languages, and sometimes a little longer. If you
 9619: want to restrict the scope of a local, enclose its definition in
 9620: @code{SCOPE}...@code{ENDSCOPE}.
 9621: 
 9622: 
 9623: doc-scope
 9624: doc-endscope
 9625: 
 9626: 
 9627: These words behave like control structure words, so you can use them
 9628: with @code{CS-PICK} and @code{CS-ROLL} to restrict the scope in
 9629: arbitrary ways.
 9630: 
 9631: If you want a more exact answer to the visibility question, here's the
 9632: basic principle: A local is visible in all places that can only be
 9633: reached through the definition of the local@footnote{In compiler
 9634: construction terminology, all places dominated by the definition of the
 9635: local.}. In other words, it is not visible in places that can be reached
 9636: without going through the definition of the local. E.g., locals defined
 9637: in @code{IF}...@code{ENDIF} are visible until the @code{ENDIF}, locals
 9638: defined in @code{BEGIN}...@code{UNTIL} are visible after the
 9639: @code{UNTIL} (until, e.g., a subsequent @code{ENDSCOPE}).
 9640: 
 9641: The reasoning behind this solution is: We want to have the locals
 9642: visible as long as it is meaningful. The user can always make the
 9643: visibility shorter by using explicit scoping. In a place that can
 9644: only be reached through the definition of a local, the meaning of a
 9645: local name is clear. In other places it is not: How is the local
 9646: initialized at the control flow path that does not contain the
 9647: definition? Which local is meant, if the same name is defined twice in
 9648: two independent control flow paths?
 9649: 
 9650: This should be enough detail for nearly all users, so you can skip the
 9651: rest of this section. If you really must know all the gory details and
 9652: options, read on.
 9653: 
 9654: In order to implement this rule, the compiler has to know which places
 9655: are unreachable. It knows this automatically after @code{AHEAD},
 9656: @code{AGAIN}, @code{EXIT} and @code{LEAVE}; in other cases (e.g., after
 9657: most @code{THROW}s), you can use the word @code{UNREACHABLE} to tell the
 9658: compiler that the control flow never reaches that place. If
 9659: @code{UNREACHABLE} is not used where it could, the only consequence is
 9660: that the visibility of some locals is more limited than the rule above
 9661: says. If @code{UNREACHABLE} is used where it should not (i.e., if you
 9662: lie to the compiler), buggy code will be produced.
 9663: 
 9664: 
 9665: doc-unreachable
 9666: 
 9667: 
 9668: Another problem with this rule is that at @code{BEGIN}, the compiler
 9669: does not know which locals will be visible on the incoming
 9670: back-edge. All problems discussed in the following are due to this
 9671: ignorance of the compiler (we discuss the problems using @code{BEGIN}
 9672: loops as examples; the discussion also applies to @code{?DO} and other
 9673: loops). Perhaps the most insidious example is:
 9674: @example
 9675: AHEAD
 9676: BEGIN
 9677:   x
 9678: [ 1 CS-ROLL ] THEN
 9679:   @{ x @}
 9680:   ...
 9681: UNTIL
 9682: @end example
 9683: 
 9684: This should be legal according to the visibility rule. The use of
 9685: @code{x} can only be reached through the definition; but that appears
 9686: textually below the use.
 9687: 
 9688: From this example it is clear that the visibility rules cannot be fully
 9689: implemented without major headaches. Our implementation treats common
 9690: cases as advertised and the exceptions are treated in a safe way: The
 9691: compiler makes a reasonable guess about the locals visible after a
 9692: @code{BEGIN}; if it is too pessimistic, the
 9693: user will get a spurious error about the local not being defined; if the
 9694: compiler is too optimistic, it will notice this later and issue a
 9695: warning. In the case above the compiler would complain about @code{x}
 9696: being undefined at its use. You can see from the obscure examples in
 9697: this section that it takes quite unusual control structures to get the
 9698: compiler into trouble, and even then it will often do fine.
 9699: 
 9700: If the @code{BEGIN} is reachable from above, the most optimistic guess
 9701: is that all locals visible before the @code{BEGIN} will also be
 9702: visible after the @code{BEGIN}. This guess is valid for all loops that
 9703: are entered only through the @code{BEGIN}, in particular, for normal
 9704: @code{BEGIN}...@code{WHILE}...@code{REPEAT} and
 9705: @code{BEGIN}...@code{UNTIL} loops and it is implemented in our
 9706: compiler. When the branch to the @code{BEGIN} is finally generated by
 9707: @code{AGAIN} or @code{UNTIL}, the compiler checks the guess and
 9708: warns the user if it was too optimistic:
 9709: @example
 9710: IF
 9711:   @{ x @}
 9712: BEGIN
 9713:   \ x ? 
 9714: [ 1 cs-roll ] THEN
 9715:   ...
 9716: UNTIL
 9717: @end example
 9718: 
 9719: Here, @code{x} lives only until the @code{BEGIN}, but the compiler
 9720: optimistically assumes that it lives until the @code{THEN}. It notices
 9721: this difference when it compiles the @code{UNTIL} and issues a
 9722: warning. The user can avoid the warning, and make sure that @code{x}
 9723: is not used in the wrong area by using explicit scoping:
 9724: @example
 9725: IF
 9726:   SCOPE
 9727:   @{ x @}
 9728:   ENDSCOPE
 9729: BEGIN
 9730: [ 1 cs-roll ] THEN
 9731:   ...
 9732: UNTIL
 9733: @end example
 9734: 
 9735: Since the guess is optimistic, there will be no spurious error messages
 9736: about undefined locals.
 9737: 
 9738: If the @code{BEGIN} is not reachable from above (e.g., after
 9739: @code{AHEAD} or @code{EXIT}), the compiler cannot even make an
 9740: optimistic guess, as the locals visible after the @code{BEGIN} may be
 9741: defined later. Therefore, the compiler assumes that no locals are
 9742: visible after the @code{BEGIN}. However, the user can use
 9743: @code{ASSUME-LIVE} to make the compiler assume that the same locals are
 9744: visible at the BEGIN as at the point where the top control-flow stack
 9745: item was created.
 9746: 
 9747: 
 9748: doc-assume-live
 9749: 
 9750: 
 9751: @noindent
 9752: E.g.,
 9753: @example
 9754: @{ x @}
 9755: AHEAD
 9756: ASSUME-LIVE
 9757: BEGIN
 9758:   x
 9759: [ 1 CS-ROLL ] THEN
 9760:   ...
 9761: UNTIL
 9762: @end example
 9763: 
 9764: Other cases where the locals are defined before the @code{BEGIN} can be
 9765: handled by inserting an appropriate @code{CS-ROLL} before the
 9766: @code{ASSUME-LIVE} (and changing the control-flow stack manipulation
 9767: behind the @code{ASSUME-LIVE}).
 9768: 
 9769: Cases where locals are defined after the @code{BEGIN} (but should be
 9770: visible immediately after the @code{BEGIN}) can only be handled by
 9771: rearranging the loop. E.g., the ``most insidious'' example above can be
 9772: arranged into:
 9773: @example
 9774: BEGIN
 9775:   @{ x @}
 9776:   ... 0=
 9777: WHILE
 9778:   x
 9779: REPEAT
 9780: @end example
 9781: 
 9782: @node How long do locals live?, Locals programming style, Where are locals visible by name?, Gforth locals
 9783: @subsubsection How long do locals live?
 9784: @cindex locals lifetime
 9785: @cindex lifetime of locals
 9786: 
 9787: The right answer for the lifetime question would be: A local lives at
 9788: least as long as it can be accessed. For a value-flavoured local this
 9789: means: until the end of its visibility. However, a variable-flavoured
 9790: local could be accessed through its address far beyond its visibility
 9791: scope. Ultimately, this would mean that such locals would have to be
 9792: garbage collected. Since this entails un-Forth-like implementation
 9793: complexities, I adopted the same cowardly solution as some other
 9794: languages (e.g., C): The local lives only as long as it is visible;
 9795: afterwards its address is invalid (and programs that access it
 9796: afterwards are erroneous).
 9797: 
 9798: @node Locals programming style, Locals implementation, How long do locals live?, Gforth locals
 9799: @subsubsection Locals programming style
 9800: @cindex locals programming style
 9801: @cindex programming style, locals
 9802: 
 9803: The freedom to define locals anywhere has the potential to change
 9804: programming styles dramatically. In particular, the need to use the
 9805: return stack for intermediate storage vanishes. Moreover, all stack
 9806: manipulations (except @code{PICK}s and @code{ROLL}s with run-time
 9807: determined arguments) can be eliminated: If the stack items are in the
 9808: wrong order, just write a locals definition for all of them; then
 9809: write the items in the order you want.
 9810: 
 9811: This seems a little far-fetched and eliminating stack manipulations is
 9812: unlikely to become a conscious programming objective. Still, the number
 9813: of stack manipulations will be reduced dramatically if local variables
 9814: are used liberally (e.g., compare @code{max} (@pxref{Gforth locals}) with
 9815: a traditional implementation of @code{max}).
 9816: 
 9817: This shows one potential benefit of locals: making Forth programs more
 9818: readable. Of course, this benefit will only be realized if the
 9819: programmers continue to honour the principle of factoring instead of
 9820: using the added latitude to make the words longer.
 9821: 
 9822: @cindex single-assignment style for locals
 9823: Using @code{TO} can and should be avoided.  Without @code{TO},
 9824: every value-flavoured local has only a single assignment and many
 9825: advantages of functional languages apply to Forth. I.e., programs are
 9826: easier to analyse, to optimize and to read: It is clear from the
 9827: definition what the local stands for, it does not turn into something
 9828: different later.
 9829: 
 9830: E.g., a definition using @code{TO} might look like this:
 9831: @example
 9832: : strcmp @{ addr1 u1 addr2 u2 -- n @}
 9833:  u1 u2 min 0
 9834:  ?do
 9835:    addr1 c@@ addr2 c@@ -
 9836:    ?dup-if
 9837:      unloop exit
 9838:    then
 9839:    addr1 char+ TO addr1
 9840:    addr2 char+ TO addr2
 9841:  loop
 9842:  u1 u2 - ;
 9843: @end example
 9844: Here, @code{TO} is used to update @code{addr1} and @code{addr2} at
 9845: every loop iteration. @code{strcmp} is a typical example of the
 9846: readability problems of using @code{TO}. When you start reading
 9847: @code{strcmp}, you think that @code{addr1} refers to the start of the
 9848: string. Only near the end of the loop you realize that it is something
 9849: else.
 9850: 
 9851: This can be avoided by defining two locals at the start of the loop that
 9852: are initialized with the right value for the current iteration.
 9853: @example
 9854: : strcmp @{ addr1 u1 addr2 u2 -- n @}
 9855:  addr1 addr2
 9856:  u1 u2 min 0 
 9857:  ?do @{ s1 s2 @}
 9858:    s1 c@@ s2 c@@ -
 9859:    ?dup-if
 9860:      unloop exit
 9861:    then
 9862:    s1 char+ s2 char+
 9863:  loop
 9864:  2drop
 9865:  u1 u2 - ;
 9866: @end example
 9867: Here it is clear from the start that @code{s1} has a different value
 9868: in every loop iteration.
 9869: 
 9870: @node Locals implementation,  , Locals programming style, Gforth locals
 9871: @subsubsection Locals implementation
 9872: @cindex locals implementation
 9873: @cindex implementation of locals
 9874: 
 9875: @cindex locals stack
 9876: Gforth uses an extra locals stack. The most compelling reason for
 9877: this is that the return stack is not float-aligned; using an extra stack
 9878: also eliminates the problems and restrictions of using the return stack
 9879: as locals stack. Like the other stacks, the locals stack grows toward
 9880: lower addresses. A few primitives allow an efficient implementation:
 9881: 
 9882: 
 9883: doc-@local#
 9884: doc-f@local#
 9885: doc-laddr#
 9886: doc-lp+!#
 9887: doc-lp!
 9888: doc->l
 9889: doc-f>l
 9890: 
 9891: 
 9892: In addition to these primitives, some specializations of these
 9893: primitives for commonly occurring inline arguments are provided for
 9894: efficiency reasons, e.g., @code{@@local0} as specialization of
 9895: @code{@@local#} for the inline argument 0. The following compiling words
 9896: compile the right specialized version, or the general version, as
 9897: appropriate:
 9898: 
 9899: 
 9900: @c doc-compile-@local
 9901: @c doc-compile-f@local
 9902: doc-compile-lp+!
 9903: 
 9904: 
 9905: Combinations of conditional branches and @code{lp+!#} like
 9906: @code{?branch-lp+!#} (the locals pointer is only changed if the branch
 9907: is taken) are provided for efficiency and correctness in loops.
 9908: 
 9909: A special area in the dictionary space is reserved for keeping the
 9910: local variable names. @code{@{} switches the dictionary pointer to this
 9911: area and @code{@}} switches it back and generates the locals
 9912: initializing code. @code{W:} etc.@ are normal defining words. This
 9913: special area is cleared at the start of every colon definition.
 9914: 
 9915: @cindex word list for defining locals
 9916: A special feature of Gforth's dictionary is used to implement the
 9917: definition of locals without type specifiers: every word list (aka
 9918: vocabulary) has its own methods for searching
 9919: etc. (@pxref{Word Lists}). For the present purpose we defined a word list
 9920: with a special search method: When it is searched for a word, it
 9921: actually creates that word using @code{W:}. @code{@{} changes the search
 9922: order to first search the word list containing @code{@}}, @code{W:} etc.,
 9923: and then the word list for defining locals without type specifiers.
 9924: 
 9925: The lifetime rules support a stack discipline within a colon
 9926: definition: The lifetime of a local is either nested with other locals
 9927: lifetimes or it does not overlap them.
 9928: 
 9929: At @code{BEGIN}, @code{IF}, and @code{AHEAD} no code for locals stack
 9930: pointer manipulation is generated. Between control structure words
 9931: locals definitions can push locals onto the locals stack. @code{AGAIN}
 9932: is the simplest of the other three control flow words. It has to
 9933: restore the locals stack depth of the corresponding @code{BEGIN}
 9934: before branching. The code looks like this:
 9935: @format
 9936: @code{lp+!#} current-locals-size @minus{} dest-locals-size
 9937: @code{branch} <begin>
 9938: @end format
 9939: 
 9940: @code{UNTIL} is a little more complicated: If it branches back, it
 9941: must adjust the stack just like @code{AGAIN}. But if it falls through,
 9942: the locals stack must not be changed. The compiler generates the
 9943: following code:
 9944: @format
 9945: @code{?branch-lp+!#} <begin> current-locals-size @minus{} dest-locals-size
 9946: @end format
 9947: The locals stack pointer is only adjusted if the branch is taken.
 9948: 
 9949: @code{THEN} can produce somewhat inefficient code:
 9950: @format
 9951: @code{lp+!#} current-locals-size @minus{} orig-locals-size
 9952: <orig target>:
 9953: @code{lp+!#} orig-locals-size @minus{} new-locals-size
 9954: @end format
 9955: The second @code{lp+!#} adjusts the locals stack pointer from the
 9956: level at the @i{orig} point to the level after the @code{THEN}. The
 9957: first @code{lp+!#} adjusts the locals stack pointer from the current
 9958: level to the level at the orig point, so the complete effect is an
 9959: adjustment from the current level to the right level after the
 9960: @code{THEN}.
 9961: 
 9962: @cindex locals information on the control-flow stack
 9963: @cindex control-flow stack items, locals information
 9964: In a conventional Forth implementation a dest control-flow stack entry
 9965: is just the target address and an orig entry is just the address to be
 9966: patched. Our locals implementation adds a word list to every orig or dest
 9967: item. It is the list of locals visible (or assumed visible) at the point
 9968: described by the entry. Our implementation also adds a tag to identify
 9969: the kind of entry, in particular to differentiate between live and dead
 9970: (reachable and unreachable) orig entries.
 9971: 
 9972: A few unusual operations have to be performed on locals word lists:
 9973: 
 9974: 
 9975: doc-common-list
 9976: doc-sub-list?
 9977: doc-list-size
 9978: 
 9979: 
 9980: Several features of our locals word list implementation make these
 9981: operations easy to implement: The locals word lists are organised as
 9982: linked lists; the tails of these lists are shared, if the lists
 9983: contain some of the same locals; and the address of a name is greater
 9984: than the address of the names behind it in the list.
 9985: 
 9986: Another important implementation detail is the variable
 9987: @code{dead-code}. It is used by @code{BEGIN} and @code{THEN} to
 9988: determine if they can be reached directly or only through the branch
 9989: that they resolve. @code{dead-code} is set by @code{UNREACHABLE},
 9990: @code{AHEAD}, @code{EXIT} etc., and cleared at the start of a colon
 9991: definition, by @code{BEGIN} and usually by @code{THEN}.
 9992: 
 9993: Counted loops are similar to other loops in most respects, but
 9994: @code{LEAVE} requires special attention: It performs basically the same
 9995: service as @code{AHEAD}, but it does not create a control-flow stack
 9996: entry. Therefore the information has to be stored elsewhere;
 9997: traditionally, the information was stored in the target fields of the
 9998: branches created by the @code{LEAVE}s, by organizing these fields into a
 9999: linked list. Unfortunately, this clever trick does not provide enough
10000: space for storing our extended control flow information. Therefore, we
10001: introduce another stack, the leave stack. It contains the control-flow
10002: stack entries for all unresolved @code{LEAVE}s.
10003: 
10004: Local names are kept until the end of the colon definition, even if
10005: they are no longer visible in any control-flow path. In a few cases
10006: this may lead to increased space needs for the locals name area, but
10007: usually less than reclaiming this space would cost in code size.
10008: 
10009: 
10010: @node ANS Forth locals,  , Gforth locals, Locals
10011: @subsection ANS Forth locals
10012: @cindex locals, ANS Forth style
10013: 
10014: The ANS Forth locals wordset does not define a syntax for locals, but
10015: words that make it possible to define various syntaxes. One of the
10016: possible syntaxes is a subset of the syntax we used in the Gforth locals
10017: wordset, i.e.:
10018: 
10019: @example
10020: @{ local1 local2 ... -- comment @}
10021: @end example
10022: @noindent
10023: or
10024: @example
10025: @{ local1 local2 ... @}
10026: @end example
10027: 
10028: The order of the locals corresponds to the order in a stack comment. The
10029: restrictions are:
10030: 
10031: @itemize @bullet
10032: @item
10033: Locals can only be cell-sized values (no type specifiers are allowed).
10034: @item
10035: Locals can be defined only outside control structures.
10036: @item
10037: Locals can interfere with explicit usage of the return stack. For the
10038: exact (and long) rules, see the standard. If you don't use return stack
10039: accessing words in a definition using locals, you will be all right. The
10040: purpose of this rule is to make locals implementation on the return
10041: stack easier.
10042: @item
10043: The whole definition must be in one line.
10044: @end itemize
10045: 
10046: Locals defined in ANS Forth behave like @code{VALUE}s
10047: (@pxref{Values}). I.e., they are initialized from the stack. Using their
10048: name produces their value. Their value can be changed using @code{TO}.
10049: 
10050: Since the syntax above is supported by Gforth directly, you need not do
10051: anything to use it. If you want to port a program using this syntax to
10052: another ANS Forth system, use @file{compat/anslocal.fs} to implement the
10053: syntax on the other system.
10054: 
10055: Note that a syntax shown in the standard, section A.13 looks
10056: similar, but is quite different in having the order of locals
10057: reversed. Beware!
10058: 
10059: The ANS Forth locals wordset itself consists of one word:
10060: 
10061: doc-(local)
10062: 
10063: The ANS Forth locals extension wordset defines a syntax using
10064: @code{locals|}, but it is so awful that we strongly recommend not to use
10065: it. We have implemented this syntax to make porting to Gforth easy, but
10066: do not document it here. The problem with this syntax is that the locals
10067: are defined in an order reversed with respect to the standard stack
10068: comment notation, making programs harder to read, and easier to misread
10069: and miswrite. The only merit of this syntax is that it is easy to
10070: implement using the ANS Forth locals wordset.
10071: 
10072: 
10073: @c ----------------------------------------------------------
10074: @node Structures, Object-oriented Forth, Locals, Words
10075: @section  Structures
10076: @cindex structures
10077: @cindex records
10078: 
10079: This section presents the structure package that comes with Gforth. A
10080: version of the package implemented in ANS Forth is available in
10081: @file{compat/struct.fs}. This package was inspired by a posting on
10082: comp.lang.forth in 1989 (unfortunately I don't remember, by whom;
10083: possibly John Hayes). A version of this section has been published in
10084: M. Anton Ertl,
10085: @uref{http://www.complang.tuwien.ac.at/forth/objects/structs.html, Yet
10086: Another Forth Structures Package}, Forth Dimensions 19(3), pages
10087: 13--16. Marcel Hendrix provided helpful comments.
10088: 
10089: @menu
10090: * Why explicit structure support?::  
10091: * Structure Usage::             
10092: * Structure Naming Convention::  
10093: * Structure Implementation::    
10094: * Structure Glossary::          
10095: * Forth200x Structures::        
10096: @end menu
10097: 
10098: @node Why explicit structure support?, Structure Usage, Structures, Structures
10099: @subsection Why explicit structure support?
10100: 
10101: @cindex address arithmetic for structures
10102: @cindex structures using address arithmetic
10103: If we want to use a structure containing several fields, we could simply
10104: reserve memory for it, and access the fields using address arithmetic
10105: (@pxref{Address arithmetic}). As an example, consider a structure with
10106: the following fields
10107: 
10108: @table @code
10109: @item a
10110: is a float
10111: @item b
10112: is a cell
10113: @item c
10114: is a float
10115: @end table
10116: 
10117: Given the (float-aligned) base address of the structure we get the
10118: address of the field
10119: 
10120: @table @code
10121: @item a
10122: without doing anything further.
10123: @item b
10124: with @code{float+}
10125: @item c
10126: with @code{float+ cell+ faligned}
10127: @end table
10128: 
10129: It is easy to see that this can become quite tiring. 
10130: 
10131: Moreover, it is not very readable, because seeing a
10132: @code{cell+} tells us neither which kind of structure is
10133: accessed nor what field is accessed; we have to somehow infer the kind
10134: of structure, and then look up in the documentation, which field of
10135: that structure corresponds to that offset.
10136: 
10137: Finally, this kind of address arithmetic also causes maintenance
10138: troubles: If you add or delete a field somewhere in the middle of the
10139: structure, you have to find and change all computations for the fields
10140: afterwards.
10141: 
10142: So, instead of using @code{cell+} and friends directly, how
10143: about storing the offsets in constants:
10144: 
10145: @example
10146: 0 constant a-offset
10147: 0 float+ constant b-offset
10148: 0 float+ cell+ faligned c-offset
10149: @end example
10150: 
10151: Now we can get the address of field @code{x} with @code{x-offset
10152: +}. This is much better in all respects. Of course, you still
10153: have to change all later offset definitions if you add a field. You can
10154: fix this by declaring the offsets in the following way:
10155: 
10156: @example
10157: 0 constant a-offset
10158: a-offset float+ constant b-offset
10159: b-offset cell+ faligned constant c-offset
10160: @end example
10161: 
10162: Since we always use the offsets with @code{+}, we could use a defining
10163: word @code{cfield} that includes the @code{+} in the action of the
10164: defined word:
10165: 
10166: @example
10167: : cfield ( n "name" -- )
10168:     create ,
10169: does> ( name execution: addr1 -- addr2 )
10170:     @@ + ;
10171: 
10172: 0 cfield a
10173: 0 a float+ cfield b
10174: 0 b cell+ faligned cfield c
10175: @end example
10176: 
10177: Instead of @code{x-offset +}, we now simply write @code{x}.
10178: 
10179: The structure field words now can be used quite nicely. However,
10180: their definition is still a bit cumbersome: We have to repeat the
10181: name, the information about size and alignment is distributed before
10182: and after the field definitions etc.  The structure package presented
10183: here addresses these problems.
10184: 
10185: @node Structure Usage, Structure Naming Convention, Why explicit structure support?, Structures
10186: @subsection Structure Usage
10187: @cindex structure usage
10188: 
10189: @cindex @code{field} usage
10190: @cindex @code{struct} usage
10191: @cindex @code{end-struct} usage
10192: You can define a structure for a (data-less) linked list with:
10193: @example
10194: struct
10195:     cell% field list-next
10196: end-struct list%
10197: @end example
10198: 
10199: With the address of the list node on the stack, you can compute the
10200: address of the field that contains the address of the next node with
10201: @code{list-next}. E.g., you can determine the length of a list
10202: with:
10203: 
10204: @example
10205: : list-length ( list -- n )
10206: \ "list" is a pointer to the first element of a linked list
10207: \ "n" is the length of the list
10208:     0 BEGIN ( list1 n1 )
10209:         over
10210:     WHILE ( list1 n1 )
10211:         1+ swap list-next @@ swap
10212:     REPEAT
10213:     nip ;
10214: @end example
10215: 
10216: You can reserve memory for a list node in the dictionary with
10217: @code{list% %allot}, which leaves the address of the list node on the
10218: stack. For the equivalent allocation on the heap you can use @code{list%
10219: %alloc} (or, for an @code{allocate}-like stack effect (i.e., with ior),
10220: use @code{list% %allocate}). You can get the the size of a list
10221: node with @code{list% %size} and its alignment with @code{list%
10222: %alignment}.
10223: 
10224: Note that in ANS Forth the body of a @code{create}d word is
10225: @code{aligned} but not necessarily @code{faligned};
10226: therefore, if you do a:
10227: 
10228: @example
10229: create @emph{name} foo% %allot drop
10230: @end example
10231: 
10232: @noindent
10233: then the memory alloted for @code{foo%} is guaranteed to start at the
10234: body of @code{@emph{name}} only if @code{foo%} contains only character,
10235: cell and double fields.  Therefore, if your structure contains floats,
10236: better use
10237: 
10238: @example
10239: foo% %allot constant @emph{name}
10240: @end example
10241: 
10242: @cindex structures containing structures
10243: You can include a structure @code{foo%} as a field of
10244: another structure, like this:
10245: @example
10246: struct
10247: ...
10248:     foo% field ...
10249: ...
10250: end-struct ...
10251: @end example
10252: 
10253: @cindex structure extension
10254: @cindex extended records
10255: Instead of starting with an empty structure, you can extend an
10256: existing structure. E.g., a plain linked list without data, as defined
10257: above, is hardly useful; You can extend it to a linked list of integers,
10258: like this:@footnote{This feature is also known as @emph{extended
10259: records}. It is the main innovation in the Oberon language; in other
10260: words, adding this feature to Modula-2 led Wirth to create a new
10261: language, write a new compiler etc.  Adding this feature to Forth just
10262: required a few lines of code.}
10263: 
10264: @example
10265: list%
10266:     cell% field intlist-int
10267: end-struct intlist%
10268: @end example
10269: 
10270: @code{intlist%} is a structure with two fields:
10271: @code{list-next} and @code{intlist-int}.
10272: 
10273: @cindex structures containing arrays
10274: You can specify an array type containing @emph{n} elements of
10275: type @code{foo%} like this:
10276: 
10277: @example
10278: foo% @emph{n} *
10279: @end example
10280: 
10281: You can use this array type in any place where you can use a normal
10282: type, e.g., when defining a @code{field}, or with
10283: @code{%allot}.
10284: 
10285: @cindex first field optimization
10286: The first field is at the base address of a structure and the word for
10287: this field (e.g., @code{list-next}) actually does not change the address
10288: on the stack. You may be tempted to leave it away in the interest of
10289: run-time and space efficiency. This is not necessary, because the
10290: structure package optimizes this case: If you compile a first-field
10291: words, no code is generated. So, in the interest of readability and
10292: maintainability you should include the word for the field when accessing
10293: the field.
10294: 
10295: 
10296: @node Structure Naming Convention, Structure Implementation, Structure Usage, Structures
10297: @subsection Structure Naming Convention
10298: @cindex structure naming convention
10299: 
10300: The field names that come to (my) mind are often quite generic, and,
10301: if used, would cause frequent name clashes. E.g., many structures
10302: probably contain a @code{counter} field. The structure names
10303: that come to (my) mind are often also the logical choice for the names
10304: of words that create such a structure.
10305: 
10306: Therefore, I have adopted the following naming conventions: 
10307: 
10308: @itemize @bullet
10309: @cindex field naming convention
10310: @item
10311: The names of fields are of the form
10312: @code{@emph{struct}-@emph{field}}, where
10313: @code{@emph{struct}} is the basic name of the structure, and
10314: @code{@emph{field}} is the basic name of the field. You can
10315: think of field words as converting the (address of the)
10316: structure into the (address of the) field.
10317: 
10318: @cindex structure naming convention
10319: @item
10320: The names of structures are of the form
10321: @code{@emph{struct}%}, where
10322: @code{@emph{struct}} is the basic name of the structure.
10323: @end itemize
10324: 
10325: This naming convention does not work that well for fields of extended
10326: structures; e.g., the integer list structure has a field
10327: @code{intlist-int}, but has @code{list-next}, not
10328: @code{intlist-next}.
10329: 
10330: @node Structure Implementation, Structure Glossary, Structure Naming Convention, Structures
10331: @subsection Structure Implementation
10332: @cindex structure implementation
10333: @cindex implementation of structures
10334: 
10335: The central idea in the implementation is to pass the data about the
10336: structure being built on the stack, not in some global
10337: variable. Everything else falls into place naturally once this design
10338: decision is made.
10339: 
10340: The type description on the stack is of the form @emph{align
10341: size}. Keeping the size on the top-of-stack makes dealing with arrays
10342: very simple.
10343: 
10344: @code{field} is a defining word that uses @code{Create}
10345: and @code{DOES>}. The body of the field contains the offset
10346: of the field, and the normal @code{DOES>} action is simply:
10347: 
10348: @example
10349: @@ +
10350: @end example
10351: 
10352: @noindent
10353: i.e., add the offset to the address, giving the stack effect
10354: @i{addr1 -- addr2} for a field.
10355: 
10356: @cindex first field optimization, implementation
10357: This simple structure is slightly complicated by the optimization
10358: for fields with offset 0, which requires a different
10359: @code{DOES>}-part (because we cannot rely on there being
10360: something on the stack if such a field is invoked during
10361: compilation). Therefore, we put the different @code{DOES>}-parts
10362: in separate words, and decide which one to invoke based on the
10363: offset. For a zero offset, the field is basically a noop; it is
10364: immediate, and therefore no code is generated when it is compiled.
10365: 
10366: @node Structure Glossary, Forth200x Structures, Structure Implementation, Structures
10367: @subsection Structure Glossary
10368: @cindex structure glossary
10369: 
10370: 
10371: doc-%align
10372: doc-%alignment
10373: doc-%alloc
10374: doc-%allocate
10375: doc-%allot
10376: doc-cell%
10377: doc-char%
10378: doc-dfloat%
10379: doc-double%
10380: doc-end-struct
10381: doc-field
10382: doc-float%
10383: doc-naligned
10384: doc-sfloat%
10385: doc-%size
10386: doc-struct
10387: 
10388: 
10389: @node Forth200x Structures,  , Structure Glossary, Structures
10390: @subsection Forth200x Structures
10391: @cindex Structures in Forth200x
10392: 
10393: The Forth 200x standard defines a slightly less convenient form of
10394: structures.  In general (when using @code{field+}, you have to perform
10395: the alignment yourself, but there are a number of convenience words
10396: (e.g., @code{field:} that perform the alignment for you.
10397: 
10398: A typical usage example is:
10399: 
10400: @example
10401: 0
10402:   field:                   s-a
10403:   faligned 2 floats +field s-b
10404: constant s-struct
10405: @end example
10406: 
10407: An alternative way of writing this structure is:
10408: 
10409: @example
10410: begin-structure s-struct
10411:   field:                   s-a
10412:   faligned 2 floats +field s-b
10413: end-structure
10414: @end example
10415: 
10416: doc-begin-structure
10417: doc-end-structure
10418: doc-+field
10419: doc-cfield:
10420: doc-field:
10421: doc-2field:
10422: doc-ffield:
10423: doc-sffield:
10424: doc-dffield:
10425: 
10426: @c -------------------------------------------------------------
10427: @node Object-oriented Forth, Programming Tools, Structures, Words
10428: @section Object-oriented Forth
10429: 
10430: Gforth comes with three packages for object-oriented programming:
10431: @file{objects.fs}, @file{oof.fs}, and @file{mini-oof.fs}; none of them
10432: is preloaded, so you have to @code{include} them before use. The most
10433: important differences between these packages (and others) are discussed
10434: in @ref{Comparison with other object models}. All packages are written
10435: in ANS Forth and can be used with any other ANS Forth.
10436: 
10437: @menu
10438: * Why object-oriented programming?::  
10439: * Object-Oriented Terminology::  
10440: * Objects::                     
10441: * OOF::                         
10442: * Mini-OOF::                    
10443: * Comparison with other object models::  
10444: @end menu
10445: 
10446: @c ----------------------------------------------------------------
10447: @node Why object-oriented programming?, Object-Oriented Terminology, Object-oriented Forth, Object-oriented Forth
10448: @subsection Why object-oriented programming?
10449: @cindex object-oriented programming motivation
10450: @cindex motivation for object-oriented programming
10451: 
10452: Often we have to deal with several data structures (@emph{objects}),
10453: that have to be treated similarly in some respects, but differently in
10454: others. Graphical objects are the textbook example: circles, triangles,
10455: dinosaurs, icons, and others, and we may want to add more during program
10456: development. We want to apply some operations to any graphical object,
10457: e.g., @code{draw} for displaying it on the screen. However, @code{draw}
10458: has to do something different for every kind of object.
10459: @comment TODO add some other operations eg perimeter, area
10460: @comment and tie in to concrete examples later..
10461: 
10462: We could implement @code{draw} as a big @code{CASE}
10463: control structure that executes the appropriate code depending on the
10464: kind of object to be drawn. This would be not be very elegant, and,
10465: moreover, we would have to change @code{draw} every time we add
10466: a new kind of graphical object (say, a spaceship).
10467: 
10468: What we would rather do is: When defining spaceships, we would tell
10469: the system: ``Here's how you @code{draw} a spaceship; you figure
10470: out the rest''.
10471: 
10472: This is the problem that all systems solve that (rightfully) call
10473: themselves object-oriented; the object-oriented packages presented here
10474: solve this problem (and not much else).
10475: @comment TODO ?list properties of oo systems.. oo vs o-based?
10476: 
10477: @c ------------------------------------------------------------------------
10478: @node Object-Oriented Terminology, Objects, Why object-oriented programming?, Object-oriented Forth
10479: @subsection Object-Oriented Terminology
10480: @cindex object-oriented terminology
10481: @cindex terminology for object-oriented programming
10482: 
10483: This section is mainly for reference, so you don't have to understand
10484: all of it right away.  The terminology is mainly Smalltalk-inspired.  In
10485: short:
10486: 
10487: @table @emph
10488: @cindex class
10489: @item class
10490: a data structure definition with some extras.
10491: 
10492: @cindex object
10493: @item object
10494: an instance of the data structure described by the class definition.
10495: 
10496: @cindex instance variables
10497: @item instance variables
10498: fields of the data structure.
10499: 
10500: @cindex selector
10501: @cindex method selector
10502: @cindex virtual function
10503: @item selector
10504: (or @emph{method selector}) a word (e.g.,
10505: @code{draw}) that performs an operation on a variety of data
10506: structures (classes). A selector describes @emph{what} operation to
10507: perform. In C++ terminology: a (pure) virtual function.
10508: 
10509: @cindex method
10510: @item method
10511: the concrete definition that performs the operation
10512: described by the selector for a specific class. A method specifies
10513: @emph{how} the operation is performed for a specific class.
10514: 
10515: @cindex selector invocation
10516: @cindex message send
10517: @cindex invoking a selector
10518: @item selector invocation
10519: a call of a selector. One argument of the call (the TOS (top-of-stack))
10520: is used for determining which method is used. In Smalltalk terminology:
10521: a message (consisting of the selector and the other arguments) is sent
10522: to the object.
10523: 
10524: @cindex receiving object
10525: @item receiving object
10526: the object used for determining the method executed by a selector
10527: invocation. In the @file{objects.fs} model, it is the object that is on
10528: the TOS when the selector is invoked. (@emph{Receiving} comes from
10529: the Smalltalk @emph{message} terminology.)
10530: 
10531: @cindex child class
10532: @cindex parent class
10533: @cindex inheritance
10534: @item child class
10535: a class that has (@emph{inherits}) all properties (instance variables,
10536: selectors, methods) from a @emph{parent class}. In Smalltalk
10537: terminology: The subclass inherits from the superclass. In C++
10538: terminology: The derived class inherits from the base class.
10539: 
10540: @end table
10541: 
10542: @c If you wonder about the message sending terminology, it comes from
10543: @c a time when each object had it's own task and objects communicated via
10544: @c message passing; eventually the Smalltalk developers realized that
10545: @c they can do most things through simple (indirect) calls. They kept the
10546: @c terminology.
10547: 
10548: @c --------------------------------------------------------------
10549: @node Objects, OOF, Object-Oriented Terminology, Object-oriented Forth
10550: @subsection The @file{objects.fs} model
10551: @cindex objects
10552: @cindex object-oriented programming
10553: 
10554: @cindex @file{objects.fs}
10555: @cindex @file{oof.fs}
10556: 
10557: This section describes the @file{objects.fs} package. This material also
10558: has been published in M. Anton Ertl,
10559: @cite{@uref{http://www.complang.tuwien.ac.at/forth/objects/objects.html,
10560: Yet Another Forth Objects Package}}, Forth Dimensions 19(2), pages
10561: 37--43.
10562: @c McKewan's and Zsoter's packages
10563: 
10564: This section assumes that you have read @ref{Structures}.
10565: 
10566: The techniques on which this model is based have been used to implement
10567: the parser generator, Gray, and have also been used in Gforth for
10568: implementing the various flavours of word lists (hashed or not,
10569: case-sensitive or not, special-purpose word lists for locals etc.).
10570: 
10571: 
10572: @menu
10573: * Properties of the Objects model::  
10574: * Basic Objects Usage::         
10575: * The Objects base class::      
10576: * Creating objects::            
10577: * Object-Oriented Programming Style::  
10578: * Class Binding::               
10579: * Method conveniences::         
10580: * Classes and Scoping::         
10581: * Dividing classes::            
10582: * Object Interfaces::           
10583: * Objects Implementation::      
10584: * Objects Glossary::            
10585: @end menu
10586: 
10587: Marcel Hendrix provided helpful comments on this section.
10588: 
10589: @node Properties of the Objects model, Basic Objects Usage, Objects, Objects
10590: @subsubsection Properties of the @file{objects.fs} model
10591: @cindex @file{objects.fs} properties
10592: 
10593: @itemize @bullet
10594: @item
10595: It is straightforward to pass objects on the stack. Passing
10596: selectors on the stack is a little less convenient, but possible.
10597: 
10598: @item
10599: Objects are just data structures in memory, and are referenced by their
10600: address. You can create words for objects with normal defining words
10601: like @code{constant}. Likewise, there is no difference between instance
10602: variables that contain objects and those that contain other data.
10603: 
10604: @item
10605: Late binding is efficient and easy to use.
10606: 
10607: @item
10608: It avoids parsing, and thus avoids problems with state-smartness
10609: and reduced extensibility; for convenience there are a few parsing
10610: words, but they have non-parsing counterparts. There are also a few
10611: defining words that parse. This is hard to avoid, because all standard
10612: defining words parse (except @code{:noname}); however, such
10613: words are not as bad as many other parsing words, because they are not
10614: state-smart.
10615: 
10616: @item
10617: It does not try to incorporate everything. It does a few things and does
10618: them well (IMO). In particular, this model was not designed to support
10619: information hiding (although it has features that may help); you can use
10620: a separate package for achieving this.
10621: 
10622: @item
10623: It is layered; you don't have to learn and use all features to use this
10624: model. Only a few features are necessary (@pxref{Basic Objects Usage},
10625: @pxref{The Objects base class}, @pxref{Creating objects}.), the others
10626: are optional and independent of each other.
10627: 
10628: @item
10629: An implementation in ANS Forth is available.
10630: 
10631: @end itemize
10632: 
10633: 
10634: @node Basic Objects Usage, The Objects base class, Properties of the Objects model, Objects
10635: @subsubsection Basic @file{objects.fs} Usage
10636: @cindex basic objects usage
10637: @cindex objects, basic usage
10638: 
10639: You can define a class for graphical objects like this:
10640: 
10641: @cindex @code{class} usage
10642: @cindex @code{end-class} usage
10643: @cindex @code{selector} usage
10644: @example
10645: object class \ "object" is the parent class
10646:   selector draw ( x y graphical -- )
10647: end-class graphical
10648: @end example
10649: 
10650: This code defines a class @code{graphical} with an
10651: operation @code{draw}.  We can perform the operation
10652: @code{draw} on any @code{graphical} object, e.g.:
10653: 
10654: @example
10655: 100 100 t-rex draw
10656: @end example
10657: 
10658: @noindent
10659: where @code{t-rex} is a word (say, a constant) that produces a
10660: graphical object.
10661: 
10662: @comment TODO add a 2nd operation eg perimeter.. and use for
10663: @comment a concrete example
10664: 
10665: @cindex abstract class
10666: How do we create a graphical object? With the present definitions,
10667: we cannot create a useful graphical object. The class
10668: @code{graphical} describes graphical objects in general, but not
10669: any concrete graphical object type (C++ users would call it an
10670: @emph{abstract class}); e.g., there is no method for the selector
10671: @code{draw} in the class @code{graphical}.
10672: 
10673: For concrete graphical objects, we define child classes of the
10674: class @code{graphical}, e.g.:
10675: 
10676: @cindex @code{overrides} usage
10677: @cindex @code{field} usage in class definition
10678: @example
10679: graphical class \ "graphical" is the parent class
10680:   cell% field circle-radius
10681: 
10682: :noname ( x y circle -- )
10683:   circle-radius @@ draw-circle ;
10684: overrides draw
10685: 
10686: :noname ( n-radius circle -- )
10687:   circle-radius ! ;
10688: overrides construct
10689: 
10690: end-class circle
10691: @end example
10692: 
10693: Here we define a class @code{circle} as a child of @code{graphical},
10694: with field @code{circle-radius} (which behaves just like a field
10695: (@pxref{Structures}); it defines (using @code{overrides}) new methods
10696: for the selectors @code{draw} and @code{construct} (@code{construct} is
10697: defined in @code{object}, the parent class of @code{graphical}).
10698: 
10699: Now we can create a circle on the heap (i.e.,
10700: @code{allocate}d memory) with:
10701: 
10702: @cindex @code{heap-new} usage
10703: @example
10704: 50 circle heap-new constant my-circle
10705: @end example
10706: 
10707: @noindent
10708: @code{heap-new} invokes @code{construct}, thus
10709: initializing the field @code{circle-radius} with 50. We can draw
10710: this new circle at (100,100) with:
10711: 
10712: @example
10713: 100 100 my-circle draw
10714: @end example
10715: 
10716: @cindex selector invocation, restrictions
10717: @cindex class definition, restrictions
10718: Note: You can only invoke a selector if the object on the TOS
10719: (the receiving object) belongs to the class where the selector was
10720: defined or one of its descendents; e.g., you can invoke
10721: @code{draw} only for objects belonging to @code{graphical}
10722: or its descendents (e.g., @code{circle}).  Immediately before
10723: @code{end-class}, the search order has to be the same as
10724: immediately after @code{class}.
10725: 
10726: @node The Objects base class, Creating objects, Basic Objects Usage, Objects
10727: @subsubsection The @file{object.fs} base class
10728: @cindex @code{object} class
10729: 
10730: When you define a class, you have to specify a parent class.  So how do
10731: you start defining classes? There is one class available from the start:
10732: @code{object}. It is ancestor for all classes and so is the
10733: only class that has no parent. It has two selectors: @code{construct}
10734: and @code{print}.
10735: 
10736: @node Creating objects, Object-Oriented Programming Style, The Objects base class, Objects
10737: @subsubsection Creating objects
10738: @cindex creating objects
10739: @cindex object creation
10740: @cindex object allocation options
10741: 
10742: @cindex @code{heap-new} discussion
10743: @cindex @code{dict-new} discussion
10744: @cindex @code{construct} discussion
10745: You can create and initialize an object of a class on the heap with
10746: @code{heap-new} ( ... class -- object ) and in the dictionary
10747: (allocation with @code{allot}) with @code{dict-new} (
10748: ... class -- object ). Both words invoke @code{construct}, which
10749: consumes the stack items indicated by "..." above.
10750: 
10751: @cindex @code{init-object} discussion
10752: @cindex @code{class-inst-size} discussion
10753: If you want to allocate memory for an object yourself, you can get its
10754: alignment and size with @code{class-inst-size 2@@} ( class --
10755: align size ). Once you have memory for an object, you can initialize
10756: it with @code{init-object} ( ... class object -- );
10757: @code{construct} does only a part of the necessary work.
10758: 
10759: @node Object-Oriented Programming Style, Class Binding, Creating objects, Objects
10760: @subsubsection Object-Oriented Programming Style
10761: @cindex object-oriented programming style
10762: @cindex programming style, object-oriented
10763: 
10764: This section is not exhaustive.
10765: 
10766: @cindex stack effects of selectors
10767: @cindex selectors and stack effects
10768: In general, it is a good idea to ensure that all methods for the
10769: same selector have the same stack effect: when you invoke a selector,
10770: you often have no idea which method will be invoked, so, unless all
10771: methods have the same stack effect, you will not know the stack effect
10772: of the selector invocation.
10773: 
10774: One exception to this rule is methods for the selector
10775: @code{construct}. We know which method is invoked, because we
10776: specify the class to be constructed at the same place. Actually, I
10777: defined @code{construct} as a selector only to give the users a
10778: convenient way to specify initialization. The way it is used, a
10779: mechanism different from selector invocation would be more natural
10780: (but probably would take more code and more space to explain).
10781: 
10782: @node Class Binding, Method conveniences, Object-Oriented Programming Style, Objects
10783: @subsubsection Class Binding
10784: @cindex class binding
10785: @cindex early binding
10786: 
10787: @cindex late binding
10788: Normal selector invocations determine the method at run-time depending
10789: on the class of the receiving object. This run-time selection is called
10790: @i{late binding}.
10791: 
10792: Sometimes it's preferable to invoke a different method. For example,
10793: you might want to use the simple method for @code{print}ing
10794: @code{object}s instead of the possibly long-winded @code{print} method
10795: of the receiver class. You can achieve this by replacing the invocation
10796: of @code{print} with:
10797: 
10798: @cindex @code{[bind]} usage
10799: @example
10800: [bind] object print
10801: @end example
10802: 
10803: @noindent
10804: in compiled code or:
10805: 
10806: @cindex @code{bind} usage
10807: @example
10808: bind object print
10809: @end example
10810: 
10811: @cindex class binding, alternative to
10812: @noindent
10813: in interpreted code. Alternatively, you can define the method with a
10814: name (e.g., @code{print-object}), and then invoke it through the
10815: name. Class binding is just a (often more convenient) way to achieve
10816: the same effect; it avoids name clutter and allows you to invoke
10817: methods directly without naming them first.
10818: 
10819: @cindex superclass binding
10820: @cindex parent class binding
10821: A frequent use of class binding is this: When we define a method
10822: for a selector, we often want the method to do what the selector does
10823: in the parent class, and a little more. There is a special word for
10824: this purpose: @code{[parent]}; @code{[parent]
10825: @emph{selector}} is equivalent to @code{[bind] @emph{parent
10826: selector}}, where @code{@emph{parent}} is the parent
10827: class of the current class. E.g., a method definition might look like:
10828: 
10829: @cindex @code{[parent]} usage
10830: @example
10831: :noname
10832:   dup [parent] foo \ do parent's foo on the receiving object
10833:   ... \ do some more
10834: ; overrides foo
10835: @end example
10836: 
10837: @cindex class binding as optimization
10838: In @cite{Object-oriented programming in ANS Forth} (Forth Dimensions,
10839: March 1997), Andrew McKewan presents class binding as an optimization
10840: technique. I recommend not using it for this purpose unless you are in
10841: an emergency. Late binding is pretty fast with this model anyway, so the
10842: benefit of using class binding is small; the cost of using class binding
10843: where it is not appropriate is reduced maintainability.
10844: 
10845: While we are at programming style questions: You should bind
10846: selectors only to ancestor classes of the receiving object. E.g., say,
10847: you know that the receiving object is of class @code{foo} or its
10848: descendents; then you should bind only to @code{foo} and its
10849: ancestors.
10850: 
10851: @node Method conveniences, Classes and Scoping, Class Binding, Objects
10852: @subsubsection Method conveniences
10853: @cindex method conveniences
10854: 
10855: In a method you usually access the receiving object pretty often.  If
10856: you define the method as a plain colon definition (e.g., with
10857: @code{:noname}), you may have to do a lot of stack
10858: gymnastics. To avoid this, you can define the method with @code{m:
10859: ... ;m}. E.g., you could define the method for
10860: @code{draw}ing a @code{circle} with
10861: 
10862: @cindex @code{this} usage
10863: @cindex @code{m:} usage
10864: @cindex @code{;m} usage
10865: @example
10866: m: ( x y circle -- )
10867:   ( x y ) this circle-radius @@ draw-circle ;m
10868: @end example
10869: 
10870: @cindex @code{exit} in @code{m: ... ;m}
10871: @cindex @code{exitm} discussion
10872: @cindex @code{catch} in @code{m: ... ;m}
10873: When this method is executed, the receiver object is removed from the
10874: stack; you can access it with @code{this} (admittedly, in this
10875: example the use of @code{m: ... ;m} offers no advantage). Note
10876: that I specify the stack effect for the whole method (i.e. including
10877: the receiver object), not just for the code between @code{m:}
10878: and @code{;m}. You cannot use @code{exit} in
10879: @code{m:...;m}; instead, use
10880: @code{exitm}.@footnote{Moreover, for any word that calls
10881: @code{catch} and was defined before loading
10882: @code{objects.fs}, you have to redefine it like I redefined
10883: @code{catch}: @code{: catch this >r catch r> to-this ;}}
10884: 
10885: @cindex @code{inst-var} usage
10886: You will frequently use sequences of the form @code{this
10887: @emph{field}} (in the example above: @code{this
10888: circle-radius}). If you use the field only in this way, you can
10889: define it with @code{inst-var} and eliminate the
10890: @code{this} before the field name. E.g., the @code{circle}
10891: class above could also be defined with:
10892: 
10893: @example
10894: graphical class
10895:   cell% inst-var radius
10896: 
10897: m: ( x y circle -- )
10898:   radius @@ draw-circle ;m
10899: overrides draw
10900: 
10901: m: ( n-radius circle -- )
10902:   radius ! ;m
10903: overrides construct
10904: 
10905: end-class circle
10906: @end example
10907: 
10908: @code{radius} can only be used in @code{circle} and its
10909: descendent classes and inside @code{m:...;m}.
10910: 
10911: @cindex @code{inst-value} usage
10912: You can also define fields with @code{inst-value}, which is
10913: to @code{inst-var} what @code{value} is to
10914: @code{variable}.  You can change the value of such a field with
10915: @code{[to-inst]}.  E.g., we could also define the class
10916: @code{circle} like this:
10917: 
10918: @example
10919: graphical class
10920:   inst-value radius
10921: 
10922: m: ( x y circle -- )
10923:   radius draw-circle ;m
10924: overrides draw
10925: 
10926: m: ( n-radius circle -- )
10927:   [to-inst] radius ;m
10928: overrides construct
10929: 
10930: end-class circle
10931: @end example
10932: 
10933: @c !! :m is easy to confuse with m:.  Another name would be better.
10934: 
10935: @c Finally, you can define named methods with @code{:m}.  One use of this
10936: @c feature is the definition of words that occur only in one class and are
10937: @c not intended to be overridden, but which still need method context
10938: @c (e.g., for accessing @code{inst-var}s).  Another use is for methods that
10939: @c would be bound frequently, if defined anonymously.
10940: 
10941: 
10942: @node Classes and Scoping, Dividing classes, Method conveniences, Objects
10943: @subsubsection Classes and Scoping
10944: @cindex classes and scoping
10945: @cindex scoping and classes
10946: 
10947: Inheritance is frequent, unlike structure extension. This exacerbates
10948: the problem with the field name convention (@pxref{Structure Naming
10949: Convention}): One always has to remember in which class the field was
10950: originally defined; changing a part of the class structure would require
10951: changes for renaming in otherwise unaffected code.
10952: 
10953: @cindex @code{inst-var} visibility
10954: @cindex @code{inst-value} visibility
10955: To solve this problem, I added a scoping mechanism (which was not in my
10956: original charter): A field defined with @code{inst-var} (or
10957: @code{inst-value}) is visible only in the class where it is defined and in
10958: the descendent classes of this class.  Using such fields only makes
10959: sense in @code{m:}-defined methods in these classes anyway.
10960: 
10961: This scoping mechanism allows us to use the unadorned field name,
10962: because name clashes with unrelated words become much less likely.
10963: 
10964: @cindex @code{protected} discussion
10965: @cindex @code{private} discussion
10966: Once we have this mechanism, we can also use it for controlling the
10967: visibility of other words: All words defined after
10968: @code{protected} are visible only in the current class and its
10969: descendents. @code{public} restores the compilation
10970: (i.e. @code{current}) word list that was in effect before. If you
10971: have several @code{protected}s without an intervening
10972: @code{public} or @code{set-current}, @code{public}
10973: will restore the compilation word list in effect before the first of
10974: these @code{protected}s.
10975: 
10976: @node Dividing classes, Object Interfaces, Classes and Scoping, Objects
10977: @subsubsection Dividing classes
10978: @cindex Dividing classes
10979: @cindex @code{methods}...@code{end-methods}
10980: 
10981: You may want to do the definition of methods separate from the
10982: definition of the class, its selectors, fields, and instance variables,
10983: i.e., separate the implementation from the definition.  You can do this
10984: in the following way:
10985: 
10986: @example
10987: graphical class
10988:   inst-value radius
10989: end-class circle
10990: 
10991: ... \ do some other stuff
10992: 
10993: circle methods \ now we are ready
10994: 
10995: m: ( x y circle -- )
10996:   radius draw-circle ;m
10997: overrides draw
10998: 
10999: m: ( n-radius circle -- )
11000:   [to-inst] radius ;m
11001: overrides construct
11002: 
11003: end-methods
11004: @end example
11005: 
11006: You can use several @code{methods}...@code{end-methods} sections.  The
11007: only things you can do to the class in these sections are: defining
11008: methods, and overriding the class's selectors.  You must not define new
11009: selectors or fields.
11010: 
11011: Note that you often have to override a selector before using it.  In
11012: particular, you usually have to override @code{construct} with a new
11013: method before you can invoke @code{heap-new} and friends.  E.g., you
11014: must not create a circle before the @code{overrides construct} sequence
11015: in the example above.
11016: 
11017: @node Object Interfaces, Objects Implementation, Dividing classes, Objects
11018: @subsubsection Object Interfaces
11019: @cindex object interfaces
11020: @cindex interfaces for objects
11021: 
11022: In this model you can only call selectors defined in the class of the
11023: receiving objects or in one of its ancestors. If you call a selector
11024: with a receiving object that is not in one of these classes, the
11025: result is undefined; if you are lucky, the program crashes
11026: immediately.
11027: 
11028: @cindex selectors common to hardly-related classes
11029: Now consider the case when you want to have a selector (or several)
11030: available in two classes: You would have to add the selector to a
11031: common ancestor class, in the worst case to @code{object}. You
11032: may not want to do this, e.g., because someone else is responsible for
11033: this ancestor class.
11034: 
11035: The solution for this problem is interfaces. An interface is a
11036: collection of selectors. If a class implements an interface, the
11037: selectors become available to the class and its descendents. A class
11038: can implement an unlimited number of interfaces. For the problem
11039: discussed above, we would define an interface for the selector(s), and
11040: both classes would implement the interface.
11041: 
11042: As an example, consider an interface @code{storage} for
11043: writing objects to disk and getting them back, and a class
11044: @code{foo} that implements it. The code would look like this:
11045: 
11046: @cindex @code{interface} usage
11047: @cindex @code{end-interface} usage
11048: @cindex @code{implementation} usage
11049: @example
11050: interface
11051:   selector write ( file object -- )
11052:   selector read1 ( file object -- )
11053: end-interface storage
11054: 
11055: bar class
11056:   storage implementation
11057: 
11058: ... overrides write
11059: ... overrides read1
11060: ...
11061: end-class foo
11062: @end example
11063: 
11064: @noindent
11065: (I would add a word @code{read} @i{( file -- object )} that uses
11066: @code{read1} internally, but that's beyond the point illustrated
11067: here.)
11068: 
11069: Note that you cannot use @code{protected} in an interface; and
11070: of course you cannot define fields.
11071: 
11072: In the Neon model, all selectors are available for all classes;
11073: therefore it does not need interfaces. The price you pay in this model
11074: is slower late binding, and therefore, added complexity to avoid late
11075: binding.
11076: 
11077: @node Objects Implementation, Objects Glossary, Object Interfaces, Objects
11078: @subsubsection @file{objects.fs} Implementation
11079: @cindex @file{objects.fs} implementation
11080: 
11081: @cindex @code{object-map} discussion
11082: An object is a piece of memory, like one of the data structures
11083: described with @code{struct...end-struct}. It has a field
11084: @code{object-map} that points to the method map for the object's
11085: class.
11086: 
11087: @cindex method map
11088: @cindex virtual function table
11089: The @emph{method map}@footnote{This is Self terminology; in C++
11090: terminology: virtual function table.} is an array that contains the
11091: execution tokens (@i{xt}s) of the methods for the object's class. Each
11092: selector contains an offset into a method map.
11093: 
11094: @cindex @code{selector} implementation, class
11095: @code{selector} is a defining word that uses
11096: @code{CREATE} and @code{DOES>}. The body of the
11097: selector contains the offset; the @code{DOES>} action for a
11098: class selector is, basically:
11099: 
11100: @example
11101: ( object addr ) @@ over object-map @@ + @@ execute
11102: @end example
11103: 
11104: Since @code{object-map} is the first field of the object, it
11105: does not generate any code. As you can see, calling a selector has a
11106: small, constant cost.
11107: 
11108: @cindex @code{current-interface} discussion
11109: @cindex class implementation and representation
11110: A class is basically a @code{struct} combined with a method
11111: map. During the class definition the alignment and size of the class
11112: are passed on the stack, just as with @code{struct}s, so
11113: @code{field} can also be used for defining class
11114: fields. However, passing more items on the stack would be
11115: inconvenient, so @code{class} builds a data structure in memory,
11116: which is accessed through the variable
11117: @code{current-interface}. After its definition is complete, the
11118: class is represented on the stack by a pointer (e.g., as parameter for
11119: a child class definition).
11120: 
11121: A new class starts off with the alignment and size of its parent,
11122: and a copy of the parent's method map. Defining new fields extends the
11123: size and alignment; likewise, defining new selectors extends the
11124: method map. @code{overrides} just stores a new @i{xt} in the method
11125: map at the offset given by the selector.
11126: 
11127: @cindex class binding, implementation
11128: Class binding just gets the @i{xt} at the offset given by the selector
11129: from the class's method map and @code{compile,}s (in the case of
11130: @code{[bind]}) it.
11131: 
11132: @cindex @code{this} implementation
11133: @cindex @code{catch} and @code{this}
11134: @cindex @code{this} and @code{catch}
11135: I implemented @code{this} as a @code{value}. At the
11136: start of an @code{m:...;m} method the old @code{this} is
11137: stored to the return stack and restored at the end; and the object on
11138: the TOS is stored @code{TO this}. This technique has one
11139: disadvantage: If the user does not leave the method via
11140: @code{;m}, but via @code{throw} or @code{exit},
11141: @code{this} is not restored (and @code{exit} may
11142: crash). To deal with the @code{throw} problem, I have redefined
11143: @code{catch} to save and restore @code{this}; the same
11144: should be done with any word that can catch an exception. As for
11145: @code{exit}, I simply forbid it (as a replacement, there is
11146: @code{exitm}).
11147: 
11148: @cindex @code{inst-var} implementation
11149: @code{inst-var} is just the same as @code{field}, with
11150: a different @code{DOES>} action:
11151: @example
11152: @@ this +
11153: @end example
11154: Similar for @code{inst-value}.
11155: 
11156: @cindex class scoping implementation
11157: Each class also has a word list that contains the words defined with
11158: @code{inst-var} and @code{inst-value}, and its protected
11159: words. It also has a pointer to its parent. @code{class} pushes
11160: the word lists of the class and all its ancestors onto the search order stack,
11161: and @code{end-class} drops them.
11162: 
11163: @cindex interface implementation
11164: An interface is like a class without fields, parent and protected
11165: words; i.e., it just has a method map. If a class implements an
11166: interface, its method map contains a pointer to the method map of the
11167: interface. The positive offsets in the map are reserved for class
11168: methods, therefore interface map pointers have negative
11169: offsets. Interfaces have offsets that are unique throughout the
11170: system, unlike class selectors, whose offsets are only unique for the
11171: classes where the selector is available (invokable).
11172: 
11173: This structure means that interface selectors have to perform one
11174: indirection more than class selectors to find their method. Their body
11175: contains the interface map pointer offset in the class method map, and
11176: the method offset in the interface method map. The
11177: @code{does>} action for an interface selector is, basically:
11178: 
11179: @example
11180: ( object selector-body )
11181: 2dup selector-interface @@ ( object selector-body object interface-offset )
11182: swap object-map @@ + @@ ( object selector-body map )
11183: swap selector-offset @@ + @@ execute
11184: @end example
11185: 
11186: where @code{object-map} and @code{selector-offset} are
11187: first fields and generate no code.
11188: 
11189: As a concrete example, consider the following code:
11190: 
11191: @example
11192: interface
11193:   selector if1sel1
11194:   selector if1sel2
11195: end-interface if1
11196: 
11197: object class
11198:   if1 implementation
11199:   selector cl1sel1
11200:   cell% inst-var cl1iv1
11201: 
11202: ' m1 overrides construct
11203: ' m2 overrides if1sel1
11204: ' m3 overrides if1sel2
11205: ' m4 overrides cl1sel2
11206: end-class cl1
11207: 
11208: create obj1 object dict-new drop
11209: create obj2 cl1    dict-new drop
11210: @end example
11211: 
11212: The data structure created by this code (including the data structure
11213: for @code{object}) is shown in the
11214: @uref{objects-implementation.eps,figure}, assuming a cell size of 4.
11215: @comment TODO add this diagram..
11216: 
11217: @node Objects Glossary,  , Objects Implementation, Objects
11218: @subsubsection @file{objects.fs} Glossary
11219: @cindex @file{objects.fs} Glossary
11220: 
11221: 
11222: doc---objects-bind
11223: doc---objects-<bind>
11224: doc---objects-bind'
11225: doc---objects-[bind]
11226: doc---objects-class
11227: doc---objects-class->map
11228: doc---objects-class-inst-size
11229: doc---objects-class-override!
11230: doc---objects-class-previous
11231: doc---objects-class>order
11232: doc---objects-construct
11233: doc---objects-current'
11234: doc---objects-[current]
11235: doc---objects-current-interface
11236: doc---objects-dict-new
11237: doc---objects-end-class
11238: doc---objects-end-class-noname
11239: doc---objects-end-interface
11240: doc---objects-end-interface-noname
11241: doc---objects-end-methods
11242: doc---objects-exitm
11243: doc---objects-heap-new
11244: doc---objects-implementation
11245: doc---objects-init-object
11246: doc---objects-inst-value
11247: doc---objects-inst-var
11248: doc---objects-interface
11249: doc---objects-m:
11250: doc---objects-:m
11251: doc---objects-;m
11252: doc---objects-method
11253: doc---objects-methods
11254: doc---objects-object
11255: doc---objects-overrides
11256: doc---objects-[parent]
11257: doc---objects-print
11258: doc---objects-protected
11259: doc---objects-public
11260: doc---objects-selector
11261: doc---objects-this
11262: doc---objects-<to-inst>
11263: doc---objects-[to-inst]
11264: doc---objects-to-this
11265: doc---objects-xt-new
11266: 
11267: 
11268: @c -------------------------------------------------------------
11269: @node OOF, Mini-OOF, Objects, Object-oriented Forth
11270: @subsection The @file{oof.fs} model
11271: @cindex oof
11272: @cindex object-oriented programming
11273: 
11274: @cindex @file{objects.fs}
11275: @cindex @file{oof.fs}
11276: 
11277: This section describes the @file{oof.fs} package.
11278: 
11279: The package described in this section has been used in bigFORTH since 1991, and
11280: used for two large applications: a chromatographic system used to
11281: create new medicaments, and a graphic user interface library (MINOS).
11282: 
11283: You can find a description (in German) of @file{oof.fs} in @cite{Object
11284: oriented bigFORTH} by Bernd Paysan, published in @cite{Vierte Dimension}
11285: 10(2), 1994.
11286: 
11287: @menu
11288: * Properties of the OOF model::  
11289: * Basic OOF Usage::             
11290: * The OOF base class::          
11291: * Class Declaration::           
11292: * Class Implementation::        
11293: @end menu
11294: 
11295: @node Properties of the OOF model, Basic OOF Usage, OOF, OOF
11296: @subsubsection Properties of the @file{oof.fs} model
11297: @cindex @file{oof.fs} properties
11298: 
11299: @itemize @bullet
11300: @item
11301: This model combines object oriented programming with information
11302: hiding. It helps you writing large application, where scoping is
11303: necessary, because it provides class-oriented scoping.
11304: 
11305: @item
11306: Named objects, object pointers, and object arrays can be created,
11307: selector invocation uses the ``object selector'' syntax. Selector invocation
11308: to objects and/or selectors on the stack is a bit less convenient, but
11309: possible.
11310: 
11311: @item
11312: Selector invocation and instance variable usage of the active object is
11313: straightforward, since both make use of the active object.
11314: 
11315: @item
11316: Late binding is efficient and easy to use.
11317: 
11318: @item
11319: State-smart objects parse selectors. However, extensibility is provided
11320: using a (parsing) selector @code{postpone} and a selector @code{'}.
11321: 
11322: @item
11323: An implementation in ANS Forth is available.
11324: 
11325: @end itemize
11326: 
11327: 
11328: @node Basic OOF Usage, The OOF base class, Properties of the OOF model, OOF
11329: @subsubsection Basic @file{oof.fs} Usage
11330: @cindex @file{oof.fs} usage
11331: 
11332: This section uses the same example as for @code{objects} (@pxref{Basic Objects Usage}).
11333: 
11334: You can define a class for graphical objects like this:
11335: 
11336: @cindex @code{class} usage
11337: @cindex @code{class;} usage
11338: @cindex @code{method} usage
11339: @example
11340: object class graphical \ "object" is the parent class
11341:   method draw ( x y -- )
11342: class;
11343: @end example
11344: 
11345: This code defines a class @code{graphical} with an
11346: operation @code{draw}.  We can perform the operation
11347: @code{draw} on any @code{graphical} object, e.g.:
11348: 
11349: @example
11350: 100 100 t-rex draw
11351: @end example
11352: 
11353: @noindent
11354: where @code{t-rex} is an object or object pointer, created with e.g.
11355: @code{graphical : t-rex}.
11356: 
11357: @cindex abstract class
11358: How do we create a graphical object? With the present definitions,
11359: we cannot create a useful graphical object. The class
11360: @code{graphical} describes graphical objects in general, but not
11361: any concrete graphical object type (C++ users would call it an
11362: @emph{abstract class}); e.g., there is no method for the selector
11363: @code{draw} in the class @code{graphical}.
11364: 
11365: For concrete graphical objects, we define child classes of the
11366: class @code{graphical}, e.g.:
11367: 
11368: @example
11369: graphical class circle \ "graphical" is the parent class
11370:   cell var circle-radius
11371: how:
11372:   : draw ( x y -- )
11373:     circle-radius @@ draw-circle ;
11374: 
11375:   : init ( n-radius -- )
11376:     circle-radius ! ;
11377: class;
11378: @end example
11379: 
11380: Here we define a class @code{circle} as a child of @code{graphical},
11381: with a field @code{circle-radius}; it defines new methods for the
11382: selectors @code{draw} and @code{init} (@code{init} is defined in
11383: @code{object}, the parent class of @code{graphical}).
11384: 
11385: Now we can create a circle in the dictionary with:
11386: 
11387: @example
11388: 50 circle : my-circle
11389: @end example
11390: 
11391: @noindent
11392: @code{:} invokes @code{init}, thus initializing the field
11393: @code{circle-radius} with 50. We can draw this new circle at (100,100)
11394: with:
11395: 
11396: @example
11397: 100 100 my-circle draw
11398: @end example
11399: 
11400: @cindex selector invocation, restrictions
11401: @cindex class definition, restrictions
11402: Note: You can only invoke a selector if the receiving object belongs to
11403: the class where the selector was defined or one of its descendents;
11404: e.g., you can invoke @code{draw} only for objects belonging to
11405: @code{graphical} or its descendents (e.g., @code{circle}). The scoping
11406: mechanism will check if you try to invoke a selector that is not
11407: defined in this class hierarchy, so you'll get an error at compilation
11408: time.
11409: 
11410: 
11411: @node The OOF base class, Class Declaration, Basic OOF Usage, OOF
11412: @subsubsection The @file{oof.fs} base class
11413: @cindex @file{oof.fs} base class
11414: 
11415: When you define a class, you have to specify a parent class.  So how do
11416: you start defining classes? There is one class available from the start:
11417: @code{object}. You have to use it as ancestor for all classes. It is the
11418: only class that has no parent. Classes are also objects, except that
11419: they don't have instance variables; class manipulation such as
11420: inheritance or changing definitions of a class is handled through
11421: selectors of the class @code{object}.
11422: 
11423: @code{object} provides a number of selectors:
11424: 
11425: @itemize @bullet
11426: @item
11427: @code{class} for subclassing, @code{definitions} to add definitions
11428: later on, and @code{class?} to get type informations (is the class a
11429: subclass of the class passed on the stack?).
11430: 
11431: doc---object-class
11432: doc---object-definitions
11433: doc---object-class?
11434: 
11435: 
11436: @item
11437: @code{init} and @code{dispose} as constructor and destructor of the
11438: object. @code{init} is invocated after the object's memory is allocated,
11439: while @code{dispose} also handles deallocation. Thus if you redefine
11440: @code{dispose}, you have to call the parent's dispose with @code{super
11441: dispose}, too.
11442: 
11443: doc---object-init
11444: doc---object-dispose
11445: 
11446: 
11447: @item
11448: @code{new}, @code{new[]}, @code{:}, @code{ptr}, @code{asptr}, and
11449: @code{[]} to create named and unnamed objects and object arrays or
11450: object pointers.
11451: 
11452: doc---object-new
11453: doc---object-new[]
11454: doc---object-:
11455: doc---object-ptr
11456: doc---object-asptr
11457: doc---object-[]
11458: 
11459: 
11460: @item
11461: @code{::} and @code{super} for explicit scoping. You should use explicit
11462: scoping only for super classes or classes with the same set of instance
11463: variables. Explicitly-scoped selectors use early binding.
11464: 
11465: doc---object-::
11466: doc---object-super
11467: 
11468: 
11469: @item
11470: @code{self} to get the address of the object
11471: 
11472: doc---object-self
11473: 
11474: 
11475: @item
11476: @code{bind}, @code{bound}, @code{link}, and @code{is} to assign object
11477: pointers and instance defers.
11478: 
11479: doc---object-bind
11480: doc---object-bound
11481: doc---object-link
11482: doc---object-is
11483: 
11484: 
11485: @item
11486: @code{'} to obtain selector tokens, @code{send} to invocate selectors
11487: form the stack, and @code{postpone} to generate selector invocation code.
11488: 
11489: doc---object-'
11490: doc---object-postpone
11491: 
11492: 
11493: @item
11494: @code{with} and @code{endwith} to select the active object from the
11495: stack, and enable its scope. Using @code{with} and @code{endwith}
11496: also allows you to create code using selector @code{postpone} without being
11497: trapped by the state-smart objects.
11498: 
11499: doc---object-with
11500: doc---object-endwith
11501: 
11502: 
11503: @end itemize
11504: 
11505: @node Class Declaration, Class Implementation, The OOF base class, OOF
11506: @subsubsection Class Declaration
11507: @cindex class declaration
11508: 
11509: @itemize @bullet
11510: @item
11511: Instance variables
11512: 
11513: doc---oof-var
11514: 
11515: 
11516: @item
11517: Object pointers
11518: 
11519: doc---oof-ptr
11520: doc---oof-asptr
11521: 
11522: 
11523: @item
11524: Instance defers
11525: 
11526: doc---oof-defer
11527: 
11528: 
11529: @item
11530: Method selectors
11531: 
11532: doc---oof-early
11533: doc---oof-method
11534: 
11535: 
11536: @item
11537: Class-wide variables
11538: 
11539: doc---oof-static
11540: 
11541: 
11542: @item
11543: End declaration
11544: 
11545: doc---oof-how:
11546: doc---oof-class;
11547: 
11548: 
11549: @end itemize
11550: 
11551: @c -------------------------------------------------------------
11552: @node Class Implementation,  , Class Declaration, OOF
11553: @subsubsection Class Implementation
11554: @cindex class implementation
11555: 
11556: @c -------------------------------------------------------------
11557: @node Mini-OOF, Comparison with other object models, OOF, Object-oriented Forth
11558: @subsection The @file{mini-oof.fs} model
11559: @cindex mini-oof
11560: 
11561: Gforth's third object oriented Forth package is a 12-liner. It uses a
11562: mixture of the @file{objects.fs} and the @file{oof.fs} syntax,
11563: and reduces to the bare minimum of features. This is based on a posting
11564: of Bernd Paysan in comp.lang.forth.
11565: 
11566: @menu
11567: * Basic Mini-OOF Usage::        
11568: * Mini-OOF Example::            
11569: * Mini-OOF Implementation::     
11570: @end menu
11571: 
11572: @c -------------------------------------------------------------
11573: @node Basic Mini-OOF Usage, Mini-OOF Example, Mini-OOF, Mini-OOF
11574: @subsubsection Basic @file{mini-oof.fs} Usage
11575: @cindex mini-oof usage
11576: 
11577: There is a base class (@code{class}, which allocates one cell for the
11578: object pointer) plus seven other words: to define a method, a variable,
11579: a class; to end a class, to resolve binding, to allocate an object and
11580: to compile a class method.
11581: @comment TODO better description of the last one
11582: 
11583: 
11584: doc-object
11585: doc-method
11586: doc-var
11587: doc-class
11588: doc-end-class
11589: doc-defines
11590: doc-new
11591: doc-::
11592: 
11593: 
11594: 
11595: @c -------------------------------------------------------------
11596: @node Mini-OOF Example, Mini-OOF Implementation, Basic Mini-OOF Usage, Mini-OOF
11597: @subsubsection Mini-OOF Example
11598: @cindex mini-oof example
11599: 
11600: A short example shows how to use this package. This example, in slightly
11601: extended form, is supplied as @file{moof-exm.fs}
11602: @comment TODO could flesh this out with some comments from the Forthwrite article
11603: 
11604: @example
11605: object class
11606:   method init
11607:   method draw
11608: end-class graphical
11609: @end example
11610: 
11611: This code defines a class @code{graphical} with an
11612: operation @code{draw}.  We can perform the operation
11613: @code{draw} on any @code{graphical} object, e.g.:
11614: 
11615: @example
11616: 100 100 t-rex draw
11617: @end example
11618: 
11619: where @code{t-rex} is an object or object pointer, created with e.g.
11620: @code{graphical new Constant t-rex}.
11621: 
11622: For concrete graphical objects, we define child classes of the
11623: class @code{graphical}, e.g.:
11624: 
11625: @example
11626: graphical class
11627:   cell var circle-radius
11628: end-class circle \ "graphical" is the parent class
11629: 
11630: :noname ( x y -- )
11631:   circle-radius @@ draw-circle ; circle defines draw
11632: :noname ( r -- )
11633:   circle-radius ! ; circle defines init
11634: @end example
11635: 
11636: There is no implicit init method, so we have to define one. The creation
11637: code of the object now has to call init explicitely.
11638: 
11639: @example
11640: circle new Constant my-circle
11641: 50 my-circle init
11642: @end example
11643: 
11644: It is also possible to add a function to create named objects with
11645: automatic call of @code{init}, given that all objects have @code{init}
11646: on the same place:
11647: 
11648: @example
11649: : new: ( .. o "name" -- )
11650:     new dup Constant init ;
11651: 80 circle new: large-circle
11652: @end example
11653: 
11654: We can draw this new circle at (100,100) with:
11655: 
11656: @example
11657: 100 100 my-circle draw
11658: @end example
11659: 
11660: @node Mini-OOF Implementation,  , Mini-OOF Example, Mini-OOF
11661: @subsubsection @file{mini-oof.fs} Implementation
11662: 
11663: Object-oriented systems with late binding typically use a
11664: ``vtable''-approach: the first variable in each object is a pointer to a
11665: table, which contains the methods as function pointers. The vtable
11666: may also contain other information.
11667: 
11668: So first, let's declare selectors:
11669: 
11670: @example
11671: : method ( m v "name" -- m' v ) Create  over , swap cell+ swap
11672:   DOES> ( ... o -- ... ) @@ over @@ + @@ execute ;
11673: @end example
11674: 
11675: During selector declaration, the number of selectors and instance
11676: variables is on the stack (in address units). @code{method} creates one
11677: selector and increments the selector number. To execute a selector, it
11678: takes the object, fetches the vtable pointer, adds the offset, and
11679: executes the method @i{xt} stored there. Each selector takes the object
11680: it is invoked with as top of stack parameter; it passes the parameters
11681: (including the object) unchanged to the appropriate method which should
11682: consume that object.
11683: 
11684: Now, we also have to declare instance variables
11685: 
11686: @example
11687: : var ( m v size "name" -- m v' ) Create  over , +
11688:   DOES> ( o -- addr ) @@ + ;
11689: @end example
11690: 
11691: As before, a word is created with the current offset. Instance
11692: variables can have different sizes (cells, floats, doubles, chars), so
11693: all we do is take the size and add it to the offset. If your machine
11694: has alignment restrictions, put the proper @code{aligned} or
11695: @code{faligned} before the variable, to adjust the variable
11696: offset. That's why it is on the top of stack.
11697: 
11698: We need a starting point (the base object) and some syntactic sugar:
11699: 
11700: @example
11701: Create object  1 cells , 2 cells ,
11702: : class ( class -- class selectors vars ) dup 2@@ ;
11703: @end example
11704: 
11705: For inheritance, the vtable of the parent object has to be
11706: copied when a new, derived class is declared. This gives all the
11707: methods of the parent class, which can be overridden, though.
11708: 
11709: @example
11710: : end-class  ( class selectors vars "name" -- )
11711:   Create  here >r , dup , 2 cells ?DO ['] noop , 1 cells +LOOP
11712:   cell+ dup cell+ r> rot @@ 2 cells /string move ;
11713: @end example
11714: 
11715: The first line creates the vtable, initialized with
11716: @code{noop}s. The second line is the inheritance mechanism, it
11717: copies the xts from the parent vtable.
11718: 
11719: We still have no way to define new methods, let's do that now:
11720: 
11721: @example
11722: : defines ( xt class "name" -- ) ' >body @@ + ! ;
11723: @end example
11724: 
11725: To allocate a new object, we need a word, too:
11726: 
11727: @example
11728: : new ( class -- o )  here over @@ allot swap over ! ;
11729: @end example
11730: 
11731: Sometimes derived classes want to access the method of the
11732: parent object. There are two ways to achieve this with Mini-OOF:
11733: first, you could use named words, and second, you could look up the
11734: vtable of the parent object.
11735: 
11736: @example
11737: : :: ( class "name" -- ) ' >body @@ + @@ compile, ;
11738: @end example
11739: 
11740: 
11741: Nothing can be more confusing than a good example, so here is
11742: one. First let's declare a text object (called
11743: @code{button}), that stores text and position:
11744: 
11745: @example
11746: object class
11747:   cell var text
11748:   cell var len
11749:   cell var x
11750:   cell var y
11751:   method init
11752:   method draw
11753: end-class button
11754: @end example
11755: 
11756: @noindent
11757: Now, implement the two methods, @code{draw} and @code{init}:
11758: 
11759: @example
11760: :noname ( o -- )
11761:  >r r@@ x @@ r@@ y @@ at-xy  r@@ text @@ r> len @@ type ;
11762:  button defines draw
11763: :noname ( addr u o -- )
11764:  >r 0 r@@ x ! 0 r@@ y ! r@@ len ! r> text ! ;
11765:  button defines init
11766: @end example
11767: 
11768: @noindent
11769: To demonstrate inheritance, we define a class @code{bold-button}, with no
11770: new data and no new selectors:
11771: 
11772: @example
11773: button class
11774: end-class bold-button
11775: 
11776: : bold   27 emit ." [1m" ;
11777: : normal 27 emit ." [0m" ;
11778: @end example
11779: 
11780: @noindent
11781: The class @code{bold-button} has a different draw method to
11782: @code{button}, but the new method is defined in terms of the draw method
11783: for @code{button}:
11784: 
11785: @example
11786: :noname bold [ button :: draw ] normal ; bold-button defines draw
11787: @end example
11788: 
11789: @noindent
11790: Finally, create two objects and apply selectors:
11791: 
11792: @example
11793: button new Constant foo
11794: s" thin foo" foo init
11795: page
11796: foo draw
11797: bold-button new Constant bar
11798: s" fat bar" bar init
11799: 1 bar y !
11800: bar draw
11801: @end example
11802: 
11803: 
11804: @node Comparison with other object models,  , Mini-OOF, Object-oriented Forth
11805: @subsection Comparison with other object models
11806: @cindex comparison of object models
11807: @cindex object models, comparison
11808: 
11809: Many object-oriented Forth extensions have been proposed (@cite{A survey
11810: of object-oriented Forths} (SIGPLAN Notices, April 1996) by Bradford
11811: J. Rodriguez and W. F. S. Poehlman lists 17). This section discusses the
11812: relation of the object models described here to two well-known and two
11813: closely-related (by the use of method maps) models.  Andras Zsoter
11814: helped us with this section.
11815: 
11816: @cindex Neon model
11817: The most popular model currently seems to be the Neon model (see
11818: @cite{Object-oriented programming in ANS Forth} (Forth Dimensions, March
11819: 1997) by Andrew McKewan) but this model has a number of limitations
11820: @footnote{A longer version of this critique can be
11821: found in @cite{On Standardizing Object-Oriented Forth Extensions} (Forth
11822: Dimensions, May 1997) by Anton Ertl.}:
11823: 
11824: @itemize @bullet
11825: @item
11826: It uses a @code{@emph{selector object}} syntax, which makes it unnatural
11827: to pass objects on the stack.
11828: 
11829: @item
11830: It requires that the selector parses the input stream (at
11831: compile time); this leads to reduced extensibility and to bugs that are
11832: hard to find.
11833: 
11834: @item
11835: It allows using every selector on every object; this eliminates the
11836: need for interfaces, but makes it harder to create efficient
11837: implementations.
11838: @end itemize
11839: 
11840: @cindex Pountain's object-oriented model
11841: Another well-known publication is @cite{Object-Oriented Forth} (Academic
11842: Press, London, 1987) by Dick Pountain. However, it is not really about
11843: object-oriented programming, because it hardly deals with late
11844: binding. Instead, it focuses on features like information hiding and
11845: overloading that are characteristic of modular languages like Ada (83).
11846: 
11847: @cindex Zsoter's object-oriented model
11848: In @uref{http://www.forth.org/oopf.html, Does late binding have to be
11849: slow?} (Forth Dimensions 18(1) 1996, pages 31-35) Andras Zsoter
11850: describes a model that makes heavy use of an active object (like
11851: @code{this} in @file{objects.fs}): The active object is not only used
11852: for accessing all fields, but also specifies the receiving object of
11853: every selector invocation; you have to change the active object
11854: explicitly with @code{@{ ... @}}, whereas in @file{objects.fs} it
11855: changes more or less implicitly at @code{m: ... ;m}. Such a change at
11856: the method entry point is unnecessary with Zsoter's model, because the
11857: receiving object is the active object already. On the other hand, the
11858: explicit change is absolutely necessary in that model, because otherwise
11859: no one could ever change the active object. An ANS Forth implementation
11860: of this model is available through
11861: @uref{http://www.forth.org/oopf.html}.
11862: 
11863: @cindex @file{oof.fs}, differences to other models
11864: The @file{oof.fs} model combines information hiding and overloading
11865: resolution (by keeping names in various word lists) with object-oriented
11866: programming. It sets the active object implicitly on method entry, but
11867: also allows explicit changing (with @code{>o...o>} or with
11868: @code{with...endwith}). It uses parsing and state-smart objects and
11869: classes for resolving overloading and for early binding: the object or
11870: class parses the selector and determines the method from this. If the
11871: selector is not parsed by an object or class, it performs a call to the
11872: selector for the active object (late binding), like Zsoter's model.
11873: Fields are always accessed through the active object. The big
11874: disadvantage of this model is the parsing and the state-smartness, which
11875: reduces extensibility and increases the opportunities for subtle bugs;
11876: essentially, you are only safe if you never tick or @code{postpone} an
11877: object or class (Bernd disagrees, but I (Anton) am not convinced).
11878: 
11879: @cindex @file{mini-oof.fs}, differences to other models
11880: The @file{mini-oof.fs} model is quite similar to a very stripped-down
11881: version of the @file{objects.fs} model, but syntactically it is a
11882: mixture of the @file{objects.fs} and @file{oof.fs} models.
11883: 
11884: 
11885: @c -------------------------------------------------------------
11886: @node Programming Tools, C Interface, Object-oriented Forth, Words
11887: @section Programming Tools
11888: @cindex programming tools
11889: 
11890: @c !! move this and assembler down below OO stuff.
11891: 
11892: @menu
11893: * Examining::                   Data and Code.
11894: * Forgetting words::            Usually before reloading.
11895: * Debugging::                   Simple and quick.
11896: * Assertions::                  Making your programs self-checking.
11897: * Singlestep Debugger::         Executing your program word by word.
11898: @end menu
11899: 
11900: @node Examining, Forgetting words, Programming Tools, Programming Tools
11901: @subsection Examining data and code
11902: @cindex examining data and code
11903: @cindex data examination
11904: @cindex code examination
11905: 
11906: The following words inspect the stack non-destructively:
11907: 
11908: doc-.s
11909: doc-f.s
11910: doc-maxdepth-.s
11911: 
11912: There is a word @code{.r} but it does @i{not} display the return stack!
11913: It is used for formatted numeric output (@pxref{Simple numeric output}).
11914: 
11915: doc-depth
11916: doc-fdepth
11917: doc-clearstack
11918: doc-clearstacks
11919: 
11920: The following words inspect memory.
11921: 
11922: doc-?
11923: doc-dump
11924: 
11925: And finally, @code{see} allows to inspect code:
11926: 
11927: doc-see
11928: doc-xt-see
11929: doc-simple-see
11930: doc-simple-see-range
11931: doc-see-code
11932: doc-see-code-range
11933: 
11934: @node Forgetting words, Debugging, Examining, Programming Tools
11935: @subsection Forgetting words
11936: @cindex words, forgetting
11937: @cindex forgeting words
11938: 
11939: @c  anton: other, maybe better places for this subsection: Defining Words;
11940: @c  Dictionary allocation.  At least a reference should be there.
11941: 
11942: Forth allows you to forget words (and everything that was alloted in the
11943: dictonary after them) in a LIFO manner.
11944: 
11945: doc-marker
11946: 
11947: The most common use of this feature is during progam development: when
11948: you change a source file, forget all the words it defined and load it
11949: again (since you also forget everything defined after the source file
11950: was loaded, you have to reload that, too).  Note that effects like
11951: storing to variables and destroyed system words are not undone when you
11952: forget words.  With a system like Gforth, that is fast enough at
11953: starting up and compiling, I find it more convenient to exit and restart
11954: Gforth, as this gives me a clean slate.
11955: 
11956: Here's an example of using @code{marker} at the start of a source file
11957: that you are debugging; it ensures that you only ever have one copy of
11958: the file's definitions compiled at any time:
11959: 
11960: @example
11961: [IFDEF] my-code
11962:     my-code
11963: [ENDIF]
11964: 
11965: marker my-code
11966: init-included-files
11967: 
11968: \ .. definitions start here
11969: \ .
11970: \ .
11971: \ end
11972: @end example
11973: 
11974: 
11975: @node Debugging, Assertions, Forgetting words, Programming Tools
11976: @subsection Debugging
11977: @cindex debugging
11978: 
11979: Languages with a slow edit/compile/link/test development loop tend to
11980: require sophisticated tracing/stepping debuggers to facilate debugging.
11981: 
11982: A much better (faster) way in fast-compiling languages is to add
11983: printing code at well-selected places, let the program run, look at
11984: the output, see where things went wrong, add more printing code, etc.,
11985: until the bug is found.
11986: 
11987: The simple debugging aids provided in @file{debugs.fs}
11988: are meant to support this style of debugging.
11989: 
11990: The word @code{~~} prints debugging information (by default the source
11991: location and the stack contents). It is easy to insert. If you use Emacs
11992: it is also easy to remove (@kbd{C-x ~} in the Emacs Forth mode to
11993: query-replace them with nothing). The deferred words
11994: @code{printdebugdata} and @code{.debugline} control the output of
11995: @code{~~}. The default source location output format works well with
11996: Emacs' compilation mode, so you can step through the program at the
11997: source level using @kbd{C-x `} (the advantage over a stepping debugger
11998: is that you can step in any direction and you know where the crash has
11999: happened or where the strange data has occurred).
12000: 
12001: doc-~~
12002: doc-printdebugdata
12003: doc-.debugline
12004: doc-debug-fid
12005: 
12006: @cindex filenames in @code{~~} output
12007: @code{~~} (and assertions) will usually print the wrong file name if a
12008: marker is executed in the same file after their occurance.  They will
12009: print @samp{*somewhere*} as file name if a marker is executed in the
12010: same file before their occurance.
12011: 
12012: 
12013: @node Assertions, Singlestep Debugger, Debugging, Programming Tools
12014: @subsection Assertions
12015: @cindex assertions
12016: 
12017: It is a good idea to make your programs self-checking, especially if you
12018: make an assumption that may become invalid during maintenance (for
12019: example, that a certain field of a data structure is never zero). Gforth
12020: supports @dfn{assertions} for this purpose. They are used like this:
12021: 
12022: @example
12023: assert( @i{flag} )
12024: @end example
12025: 
12026: The code between @code{assert(} and @code{)} should compute a flag, that
12027: should be true if everything is alright and false otherwise. It should
12028: not change anything else on the stack. The overall stack effect of the
12029: assertion is @code{( -- )}. E.g.
12030: 
12031: @example
12032: assert( 1 1 + 2 = ) \ what we learn in school
12033: assert( dup 0<> ) \ assert that the top of stack is not zero
12034: assert( false ) \ this code should not be reached
12035: @end example
12036: 
12037: The need for assertions is different at different times. During
12038: debugging, we want more checking, in production we sometimes care more
12039: for speed. Therefore, assertions can be turned off, i.e., the assertion
12040: becomes a comment. Depending on the importance of an assertion and the
12041: time it takes to check it, you may want to turn off some assertions and
12042: keep others turned on. Gforth provides several levels of assertions for
12043: this purpose:
12044: 
12045: 
12046: doc-assert0(
12047: doc-assert1(
12048: doc-assert2(
12049: doc-assert3(
12050: doc-assert(
12051: doc-)
12052: 
12053: 
12054: The variable @code{assert-level} specifies the highest assertions that
12055: are turned on. I.e., at the default @code{assert-level} of one,
12056: @code{assert0(} and @code{assert1(} assertions perform checking, while
12057: @code{assert2(} and @code{assert3(} assertions are treated as comments.
12058: 
12059: The value of @code{assert-level} is evaluated at compile-time, not at
12060: run-time. Therefore you cannot turn assertions on or off at run-time;
12061: you have to set the @code{assert-level} appropriately before compiling a
12062: piece of code. You can compile different pieces of code at different
12063: @code{assert-level}s (e.g., a trusted library at level 1 and
12064: newly-written code at level 3).
12065: 
12066: 
12067: doc-assert-level
12068: 
12069: 
12070: If an assertion fails, a message compatible with Emacs' compilation mode
12071: is produced and the execution is aborted (currently with @code{ABORT"}.
12072: If there is interest, we will introduce a special throw code. But if you
12073: intend to @code{catch} a specific condition, using @code{throw} is
12074: probably more appropriate than an assertion).
12075: 
12076: @cindex filenames in assertion output
12077: Assertions (and @code{~~}) will usually print the wrong file name if a
12078: marker is executed in the same file after their occurance.  They will
12079: print @samp{*somewhere*} as file name if a marker is executed in the
12080: same file before their occurance.
12081: 
12082: Definitions in ANS Forth for these assertion words are provided
12083: in @file{compat/assert.fs}.
12084: 
12085: 
12086: @node Singlestep Debugger,  , Assertions, Programming Tools
12087: @subsection Singlestep Debugger
12088: @cindex singlestep Debugger
12089: @cindex debugging Singlestep
12090: 
12091: The singlestep debugger works only with the engine @code{gforth-itc}.
12092: 
12093: When you create a new word there's often the need to check whether it
12094: behaves correctly or not. You can do this by typing @code{dbg
12095: badword}. A debug session might look like this:
12096: 
12097: @example
12098: : badword 0 DO i . LOOP ;  ok
12099: 2 dbg badword 
12100: : badword  
12101: Scanning code...
12102: 
12103: Nesting debugger ready!
12104: 
12105: 400D4738  8049BC4 0              -> [ 2 ] 00002 00000 
12106: 400D4740  8049F68 DO             -> [ 0 ] 
12107: 400D4744  804A0C8 i              -> [ 1 ] 00000 
12108: 400D4748 400C5E60 .              -> 0 [ 0 ] 
12109: 400D474C  8049D0C LOOP           -> [ 0 ] 
12110: 400D4744  804A0C8 i              -> [ 1 ] 00001 
12111: 400D4748 400C5E60 .              -> 1 [ 0 ] 
12112: 400D474C  8049D0C LOOP           -> [ 0 ] 
12113: 400D4758  804B384 ;              ->  ok
12114: @end example
12115: 
12116: Each line displayed is one step. You always have to hit return to
12117: execute the next word that is displayed. If you don't want to execute
12118: the next word in a whole, you have to type @kbd{n} for @code{nest}. Here is
12119: an overview what keys are available:
12120: 
12121: @table @i
12122: 
12123: @item @key{RET}
12124: Next; Execute the next word.
12125: 
12126: @item n
12127: Nest; Single step through next word.
12128: 
12129: @item u
12130: Unnest; Stop debugging and execute rest of word. If we got to this word
12131: with nest, continue debugging with the calling word.
12132: 
12133: @item d
12134: Done; Stop debugging and execute rest.
12135: 
12136: @item s
12137: Stop; Abort immediately.
12138: 
12139: @end table
12140: 
12141: Debugging large application with this mechanism is very difficult, because
12142: you have to nest very deeply into the program before the interesting part
12143: begins. This takes a lot of time. 
12144: 
12145: To do it more directly put a @code{BREAK:} command into your source code.
12146: When program execution reaches @code{BREAK:} the single step debugger is
12147: invoked and you have all the features described above.
12148: 
12149: If you have more than one part to debug it is useful to know where the
12150: program has stopped at the moment. You can do this by the 
12151: @code{BREAK" string"} command. This behaves like @code{BREAK:} except that
12152: string is typed out when the ``breakpoint'' is reached.
12153: 
12154: 
12155: doc-dbg
12156: doc-break:
12157: doc-break"
12158: 
12159: @c ------------------------------------------------------------
12160: @node C Interface, Assembler and Code Words, Programming Tools, Words
12161: @section C Interface
12162: @cindex C interface
12163: @cindex foreign language interface
12164: @cindex interface to C functions
12165: 
12166: Note that the C interface is not yet complete; callbacks are missing,
12167: as well as a way of declaring structs, unions, and their fields.
12168: 
12169: @menu
12170: * Calling C Functions::         
12171: * Declaring C Functions::       
12172: * Calling C function pointers::  
12173: * Defining library interfaces::  
12174: * Declaring OS-level libraries::  
12175: * Callbacks::                   
12176: * C interface internals::       
12177: * Low-Level C Interface Words::  
12178: @end menu
12179: 
12180: @node Calling C Functions, Declaring C Functions, C Interface, C Interface
12181: @subsection Calling C functions
12182: @cindex C functions, calls to
12183: @cindex calling C functions
12184: 
12185: Once a C function is declared (see @pxref{Declaring C Functions}), you
12186: can call it as follows: You push the arguments on the stack(s), and
12187: then call the word for the C function.  The arguments have to be
12188: pushed in the same order as the arguments appear in the C
12189: documentation (i.e., the first argument is deepest on the stack).
12190: Integer and pointer arguments have to be pushed on the data stack,
12191: floating-point arguments on the FP stack; these arguments are consumed
12192: by the called C function.
12193: 
12194: On returning from the C function, the return value, if any, resides on
12195: the appropriate stack: an integer return value is pushed on the data
12196: stack, an FP return value on the FP stack, and a void return value
12197: results in not pushing anything.  Note that most C functions have a
12198: return value, even if that is often not used in C; in Forth, you have
12199: to @code{drop} this return value explicitly if you do not use it.
12200: 
12201: The C interface automatically converts between the C type and the
12202: Forth type as necessary, on a best-effort basis (in some cases, there
12203: may be some loss).
12204: 
12205: As an example, consider the POSIX function @code{lseek()}:
12206: 
12207: @example
12208: off_t lseek(int fd, off_t offset, int whence);
12209: @end example
12210: 
12211: This function takes three integer arguments, and returns an integer
12212: argument, so a Forth call for setting the current file offset to the
12213: start of the file could look like this:
12214: 
12215: @example
12216: fd @@ 0 SEEK_SET lseek -1 = if
12217:   ... \ error handling
12218: then
12219: @end example
12220: 
12221: You might be worried that an @code{off_t} does not fit into a cell, so
12222: you could not pass larger offsets to lseek, and might get only a part
12223: of the return values.  In that case, in your declaration of the
12224: function (@pxref{Declaring C Functions}) you should declare it to use
12225: double-cells for the off_t argument and return value, and maybe give
12226: the resulting Forth word a different name, like @code{dlseek}; the
12227: result could be called like this:
12228: 
12229: @example
12230: fd @@ 0. SEEK_SET dlseek -1. d= if
12231:   ... \ error handling
12232: then
12233: @end example
12234: 
12235: Passing and returning structs or unions is currently not supported by
12236: our interface@footnote{If you know the calling convention of your C
12237: compiler, you usually can call such functions in some way, but that
12238: way is usually not portable between platforms, and sometimes not even
12239: between C compilers.}.
12240: 
12241: Calling functions with a variable number of arguments (@emph{variadic}
12242: functions, e.g., @code{printf()}) is only supported by having you
12243: declare one function-calling word for each argument pattern, and
12244: calling the appropriate word for the desired pattern.
12245: 
12246: 
12247: 
12248: @node Declaring C Functions, Calling C function pointers, Calling C Functions, C Interface
12249: @subsection Declaring C Functions
12250: @cindex C functions, declarations
12251: @cindex declaring C functions
12252: 
12253: Before you can call @code{lseek} or @code{dlseek}, you have to declare
12254: it.  The declaration consists of two parts: 
12255: 
12256: @table @b
12257: 
12258: @item The C part
12259: is the C declaration of the function, or more typically and portably,
12260: a C-style @code{#include} of a file that contains the declaration of
12261: the C function.
12262: 
12263: @item The Forth part
12264: declares the Forth types of the parameters and the Forth word name
12265: corresponding to the C function.
12266: 
12267: @end table
12268: 
12269: For the words @code{lseek} and @code{dlseek} mentioned earlier, the
12270: declarations are:
12271: 
12272: @example
12273: \c #define _FILE_OFFSET_BITS 64
12274: \c #include <sys/types.h>
12275: \c #include <unistd.h>
12276: c-function lseek lseek n n n -- n
12277: c-function dlseek lseek n d n -- d
12278: @end example
12279: 
12280: The C part of the declarations is prefixed by @code{\c}, and the rest
12281: of the line is ordinary C code.  You can use as many lines of C
12282: declarations as you like, and they are visible for all further
12283: function declarations.
12284: 
12285: The Forth part declares each interface word with @code{c-function},
12286: followed by the Forth name of the word, the C name of the called
12287: function, and the stack effect of the word.  The stack effect contains
12288: an arbitrary number of types of parameters, then @code{--}, and then
12289: exactly one type for the return value.  The possible types are:
12290: 
12291: @table @code
12292: 
12293: @item n
12294: single-cell integer
12295: 
12296: @item a
12297: address (single-cell)
12298: 
12299: @item d
12300: double-cell integer
12301: 
12302: @item r
12303: floating-point value
12304: 
12305: @item func
12306: C function pointer
12307: 
12308: @item void
12309: no value (used as return type for void functions)
12310: 
12311: @end table
12312: 
12313: @cindex variadic C functions
12314: 
12315: To deal with variadic C functions, you can declare one Forth word for
12316: every pattern you want to use, e.g.:
12317: 
12318: @example
12319: \c #include <stdio.h>
12320: c-function printf-nr printf a n r -- n
12321: c-function printf-rn printf a r n -- n
12322: @end example
12323: 
12324: Note that with C functions declared as variadic (or if you don't
12325: provide a prototype), the C interface has no C type to convert to, so
12326: no automatic conversion happens, which may lead to portability
12327: problems in some cases.  In such cases you can perform the conversion
12328: explicitly on the C level, e.g., as follows:
12329: 
12330: @example
12331: \c #define printfll(s,ll) printf(s,(long long)ll)
12332: c-function printfll printfll a n -- n
12333: @end example
12334: 
12335: Here, instead of calling @code{printf()} directly, we define a macro
12336: that casts (converts) the Forth single-cell integer into a
12337: C @code{long long} before calling @code{printf()}.
12338: 
12339: doc-\c
12340: doc-c-function
12341: doc-c-value
12342: doc-c-variable
12343: 
12344: In order to work, this C interface invokes GCC at run-time and uses
12345: dynamic linking.  If these features are not available, there are
12346: other, less convenient and less portable C interfaces in @file{lib.fs}
12347: and @file{oldlib.fs}.  These interfaces are mostly undocumented and
12348: mostly incompatible with each other and with the documented C
12349: interface; you can find some examples for the @file{lib.fs} interface
12350: in @file{lib.fs}.
12351: 
12352: 
12353: @node Calling C function pointers, Defining library interfaces, Declaring C Functions, C Interface
12354: @subsection Calling C function pointers from Forth
12355: @cindex C function pointers, calling from Forth
12356: 
12357: If you come across a C function pointer (e.g., in some C-constructed
12358: structure) and want to call it from your Forth program, you can also
12359: use the features explained until now to achieve that, as follows:
12360: 
12361: Let us assume that there is a C function pointer type @code{func1}
12362: defined in some header file @file{func1.h}, and you know that these
12363: functions take one integer argument and return an integer result; and
12364: you want to call functions through such pointers.  Just define
12365: 
12366: @example
12367: \c #include <func1.h>
12368: \c #define call_func1(par1,fptr) ((func1)fptr)(par1)
12369: c-function call-func1 call_func1 n func -- n
12370: @end example
12371: 
12372: and then you can call a function pointed to by, say @code{func1a} as
12373: follows:
12374: 
12375: @example
12376: -5 func1a call-func1 .
12377: @end example
12378: 
12379: In the C part, @code{call_func} is defined as a macro to avoid having
12380: to declare the exact parameter and return types, so the C compiler
12381: knows them from the declaration of @code{func1}.
12382: 
12383: The Forth word @code{call-func1} is similar to @code{execute}, except
12384: that it takes a C @code{func1} pointer instead of a Forth execution
12385: token, and it is specific to @code{func1} pointers.  For each type of
12386: function pointer you want to call from Forth, you have to define
12387: a separate calling word.
12388: 
12389: 
12390: @node Defining library interfaces, Declaring OS-level libraries, Calling C function pointers, C Interface
12391: @subsection Defining library interfaces
12392: @cindex giving a name to a library interface
12393: @cindex library interface names
12394: 
12395: You can give a name to a bunch of C function declarations (a library
12396: interface), as follows:
12397: 
12398: @example
12399: c-library lseek-lib
12400: \c #define _FILE_OFFSET_BITS 64
12401: ...
12402: end-c-library
12403: @end example
12404: 
12405: The effect of giving such a name to the interface is that the names of
12406: the generated files will contain that name, and when you use the
12407: interface a second time, it will use the existing files instead of
12408: generating and compiling them again, saving you time.  Note that even
12409: if you change the declarations, the old (stale) files will be used,
12410: probably leading to errors.  So, during development of the
12411: declarations we recommend not using @code{c-library}.  Normally these
12412: files are cached in @file{$HOME/.gforth/libcc-named}, so by deleting
12413: that directory you can get rid of stale files.
12414: 
12415: Note that you should use @code{c-library} before everything else
12416: having anything to do with that library, as it resets some setup
12417: stuff.  The idea is that the typical use is to put each
12418: @code{c-library}...@code{end-library} unit in its own file, and to be
12419: able to include these files in any order.
12420: 
12421: Note that the library name is not allocated in the dictionary and
12422: therefore does not shadow dictionary names.  It is used in the file
12423: system, so you have to use naming conventions appropriate for file
12424: systems.  Also, you must not call a function you declare after
12425: @code{c-library} before you perform @code{end-c-library}.
12426: 
12427: A major benefit of these named library interfaces is that, once they
12428: are generated, the tools used to generated them (in particular, the C
12429: compiler and libtool) are no longer needed, so the interface can be
12430: used even on machines that do not have the tools installed.
12431: 
12432: doc-c-library-name
12433: doc-c-library
12434: doc-end-c-library
12435: 
12436: 
12437: @node Declaring OS-level libraries, Callbacks, Defining library interfaces, C Interface
12438: @subsection Declaring OS-level libraries
12439: @cindex Shared libraries in C interface
12440: @cindex Dynamically linked libraries in C interface
12441: @cindex Libraries in C interface
12442: 
12443: For calling some C functions, you need to link with a specific
12444: OS-level library that contains that function.  E.g., the @code{sin}
12445: function requires linking a special library by using the command line
12446: switch @code{-lm}.  In our C iterface you do the equivalent thing by
12447: calling @code{add-lib} as follows:
12448: 
12449: @example
12450: clear-libs
12451: s" m" add-lib
12452: \c #include <math.h>
12453: c-function sin sin r -- r
12454: @end example
12455: 
12456: First, you clear any libraries that may have been declared earlier
12457: (you don't need them for @code{sin}); then you add the @code{m}
12458: library (actually @code{libm.so} or somesuch) to the currently
12459: declared libraries; you can add as many as you need.  Finally you
12460: declare the function as shown above.  Typically you will use the same
12461: set of library declarations for many function declarations; you need
12462: to write only one set for that, right at the beginning.
12463: 
12464: Note that you must not call @code{clear-libs} inside
12465: @code{c-library...end-c-library}; however, @code{c-library} performs
12466: the function of @code{clear-libs}, so @code{clear-libs} is not
12467: necessary, and you usually want to put @code{add-lib} calls inside
12468: @code{c-library...end-c-library}.
12469: 
12470: doc-clear-libs
12471: doc-add-lib
12472: 
12473: 
12474: @node Callbacks, C interface internals, Declaring OS-level libraries, C Interface
12475: @subsection Callbacks
12476: @cindex Callback functions written in Forth
12477: @cindex C function pointers to Forth words
12478: 
12479: Callbacks are not yet supported by the documented C interface.  You
12480: can use the undocumented @file{lib.fs} interface for callbacks.
12481: 
12482: In some cases you have to pass a function pointer to a C function,
12483: i.e., the library wants to call back to your application (and the
12484: pointed-to function is called a callback function).  You can pass the
12485: address of an existing C function (that you get with @code{lib-sym},
12486: @pxref{Low-Level C Interface Words}), but if there is no appropriate C
12487: function, you probably want to define the function as a Forth word.
12488: 
12489: @c I don't understand the existing callback interface from the example - anton
12490: 
12491: 
12492: @c > > Und dann gibt's noch die fptr-Deklaration, die einem
12493: @c > > C-Funktionspointer entspricht (Deklaration gleich wie bei
12494: @c > > Library-Funktionen, nur ohne den C-Namen, Aufruf mit der
12495: @c > > C-Funktionsadresse auf dem TOS).
12496: @c >
12497: @c > Ja, da bin ich dann ausgestiegen, weil ich aus dem Beispiel nicht
12498: @c > gesehen habe, wozu das gut ist.
12499: @c 
12500: @c Irgendwie muss ich den Callback ja testen. Und es soll ja auch 
12501: @c vorkommen, dass man von irgendwelchen kranken Interfaces einen 
12502: @c Funktionspointer übergeben bekommt, den man dann bei Gelegenheit 
12503: @c aufrufen muss. Also kann man den deklarieren, und das damit deklarierte 
12504: @c Wort verhält sich dann wie ein EXECUTE für alle C-Funktionen mit 
12505: @c demselben Prototyp.
12506: 
12507: 
12508: @node C interface internals, Low-Level C Interface Words, Callbacks, C Interface
12509: @subsection How the C interface works
12510: 
12511: The documented C interface works by generating a C code out of the
12512: declarations.
12513: 
12514: In particular, for every Forth word declared with @code{c-function},
12515: it generates a wrapper function in C that takes the Forth data from
12516: the Forth stacks, and calls the target C function with these data as
12517: arguments.  The C compiler then performs an implicit conversion
12518: between the Forth type from the stack, and the C type for the
12519: parameter, which is given by the C function prototype.  After the C
12520: function returns, the return value is likewise implicitly converted to
12521: a Forth type and written back on the stack.
12522: 
12523: The @code{\c} lines are literally included in the C code (but without
12524: the @code{\c}), and provide the necessary declarations so that the C
12525: compiler knows the C types and has enough information to perform the
12526: conversion.
12527: 
12528: These wrapper functions are eventually compiled and dynamically linked
12529: into Gforth, and then they can be called.
12530: 
12531: The libraries added with @code{add-lib} are used in the compile
12532: command line to specify dependent libraries with @code{-l@var{lib}},
12533: causing these libraries to be dynamically linked when the wrapper
12534: function is linked.
12535: 
12536: 
12537: @node Low-Level C Interface Words,  , C interface internals, C Interface
12538: @subsection Low-Level C Interface Words
12539: 
12540: doc-open-lib
12541: doc-lib-sym
12542: doc-lib-error
12543: doc-call-c
12544: 
12545: @c -------------------------------------------------------------
12546: @node Assembler and Code Words, Threading Words, C Interface, Words
12547: @section Assembler and Code Words
12548: @cindex assembler
12549: @cindex code words
12550: 
12551: @menu
12552: * Code and ;code::              
12553: * Common Assembler::            Assembler Syntax
12554: * Common Disassembler::         
12555: * 386 Assembler::               Deviations and special cases
12556: * Alpha Assembler::             Deviations and special cases
12557: * MIPS assembler::              Deviations and special cases
12558: * PowerPC assembler::           Deviations and special cases
12559: * ARM Assembler::               Deviations and special cases
12560: * Other assemblers::            How to write them
12561: @end menu
12562: 
12563: @node Code and ;code, Common Assembler, Assembler and Code Words, Assembler and Code Words
12564: @subsection @code{Code} and @code{;code}
12565: 
12566: Gforth provides some words for defining primitives (words written in
12567: machine code), and for defining the machine-code equivalent of
12568: @code{DOES>}-based defining words. However, the machine-independent
12569: nature of Gforth poses a few problems: First of all, Gforth runs on
12570: several architectures, so it can provide no standard assembler. What's
12571: worse is that the register allocation not only depends on the processor,
12572: but also on the @code{gcc} version and options used.
12573: 
12574: The words that Gforth offers encapsulate some system dependences (e.g.,
12575: the header structure), so a system-independent assembler may be used in
12576: Gforth. If you do not have an assembler, you can compile machine code
12577: directly with @code{,} and @code{c,}@footnote{This isn't portable,
12578: because these words emit stuff in @i{data} space; it works because
12579: Gforth has unified code/data spaces. Assembler isn't likely to be
12580: portable anyway.}.
12581: 
12582: 
12583: doc-assembler
12584: doc-init-asm
12585: doc-code
12586: doc-end-code
12587: doc-;code
12588: doc-flush-icache
12589: 
12590: 
12591: If @code{flush-icache} does not work correctly, @code{code} words
12592: etc. will not work (reliably), either.
12593: 
12594: The typical usage of these @code{code} words can be shown most easily by
12595: analogy to the equivalent high-level defining words:
12596: 
12597: @example
12598: : foo                              code foo
12599:    <high-level Forth words>              <assembler>
12600: ;                                  end-code
12601:                                 
12602: : bar                              : bar
12603:    <high-level Forth words>           <high-level Forth words>
12604:    CREATE                             CREATE
12605:       <high-level Forth words>           <high-level Forth words>
12606:    DOES>                              ;code
12607:       <high-level Forth words>           <assembler>
12608: ;                                  end-code
12609: @end example
12610: 
12611: @c anton: the following stuff is also in "Common Assembler", in less detail.
12612: 
12613: @cindex registers of the inner interpreter
12614: In the assembly code you will want to refer to the inner interpreter's
12615: registers (e.g., the data stack pointer) and you may want to use other
12616: registers for temporary storage. Unfortunately, the register allocation
12617: is installation-dependent.
12618: 
12619: In particular, @code{ip} (Forth instruction pointer) and @code{rp}
12620: (return stack pointer) may be in different places in @code{gforth} and
12621: @code{gforth-fast}, or different installations.  This means that you
12622: cannot write a @code{NEXT} routine that works reliably on both versions
12623: or different installations; so for doing @code{NEXT}, I recommend
12624: jumping to @code{' noop >code-address}, which contains nothing but a
12625: @code{NEXT}.
12626: 
12627: For general accesses to the inner interpreter's registers, the easiest
12628: solution is to use explicit register declarations (@pxref{Explicit Reg
12629: Vars, , Variables in Specified Registers, gcc.info, GNU C Manual}) for
12630: all of the inner interpreter's registers: You have to compile Gforth
12631: with @code{-DFORCE_REG} (configure option @code{--enable-force-reg}) and
12632: the appropriate declarations must be present in the @code{machine.h}
12633: file (see @code{mips.h} for an example; you can find a full list of all
12634: declarable register symbols with @code{grep register engine.c}). If you
12635: give explicit registers to all variables that are declared at the
12636: beginning of @code{engine()}, you should be able to use the other
12637: caller-saved registers for temporary storage. Alternatively, you can use
12638: the @code{gcc} option @code{-ffixed-REG} (@pxref{Code Gen Options, ,
12639: Options for Code Generation Conventions, gcc.info, GNU C Manual}) to
12640: reserve a register (however, this restriction on register allocation may
12641: slow Gforth significantly).
12642: 
12643: If this solution is not viable (e.g., because @code{gcc} does not allow
12644: you to explicitly declare all the registers you need), you have to find
12645: out by looking at the code where the inner interpreter's registers
12646: reside and which registers can be used for temporary storage. You can
12647: get an assembly listing of the engine's code with @code{make engine.s}.
12648: 
12649: In any case, it is good practice to abstract your assembly code from the
12650: actual register allocation. E.g., if the data stack pointer resides in
12651: register @code{$17}, create an alias for this register called @code{sp},
12652: and use that in your assembly code.
12653: 
12654: @cindex code words, portable
12655: Another option for implementing normal and defining words efficiently
12656: is to add the desired functionality to the source of Gforth. For normal
12657: words you just have to edit @file{primitives} (@pxref{Automatic
12658: Generation}). Defining words (equivalent to @code{;CODE} words, for fast
12659: defined words) may require changes in @file{engine.c}, @file{kernel.fs},
12660: @file{prims2x.fs}, and possibly @file{cross.fs}.
12661: 
12662: @node Common Assembler, Common Disassembler, Code and ;code, Assembler and Code Words
12663: @subsection Common Assembler
12664: 
12665: The assemblers in Gforth generally use a postfix syntax, i.e., the
12666: instruction name follows the operands.
12667: 
12668: The operands are passed in the usual order (the same that is used in the
12669: manual of the architecture).  Since they all are Forth words, they have
12670: to be separated by spaces; you can also use Forth words to compute the
12671: operands.
12672: 
12673: The instruction names usually end with a @code{,}.  This makes it easier
12674: to visually separate instructions if you put several of them on one
12675: line; it also avoids shadowing other Forth words (e.g., @code{and}).
12676: 
12677: Registers are usually specified by number; e.g., (decimal) @code{11}
12678: specifies registers R11 and F11 on the Alpha architecture (which one,
12679: depends on the instruction).  The usual names are also available, e.g.,
12680: @code{s2} for R11 on Alpha.
12681: 
12682: Control flow is specified similar to normal Forth code (@pxref{Arbitrary
12683: control structures}), with @code{if,}, @code{ahead,}, @code{then,},
12684: @code{begin,}, @code{until,}, @code{again,}, @code{cs-roll},
12685: @code{cs-pick}, @code{else,}, @code{while,}, and @code{repeat,}.  The
12686: conditions are specified in a way specific to each assembler.
12687: 
12688: Note that the register assignments of the Gforth engine can change
12689: between Gforth versions, or even between different compilations of the
12690: same Gforth version (e.g., if you use a different GCC version).  So if
12691: you want to refer to Gforth's registers (e.g., the stack pointer or
12692: TOS), I recommend defining your own words for refering to these
12693: registers, and using them later on; then you can easily adapt to a
12694: changed register assignment.  The stability of the register assignment
12695: is usually better if you build Gforth with @code{--enable-force-reg}.
12696: 
12697: The most common use of these registers is to dispatch to the next word
12698: (the @code{next} routine).  A portable way to do this is to jump to
12699: @code{' noop >code-address} (of course, this is less efficient than
12700: integrating the @code{next} code and scheduling it well).
12701: 
12702: Another difference between Gforth version is that the top of stack is
12703: kept in memory in @code{gforth} and, on most platforms, in a register in
12704: @code{gforth-fast}.
12705: 
12706: @node  Common Disassembler, 386 Assembler, Common Assembler, Assembler and Code Words
12707: @subsection Common Disassembler
12708: @cindex disassembler, general
12709: @cindex gdb disassembler
12710: 
12711: You can disassemble a @code{code} word with @code{see}
12712: (@pxref{Debugging}).  You can disassemble a section of memory with
12713: 
12714: doc-discode
12715: 
12716: There are two kinds of disassembler for Gforth: The Forth disassembler
12717: (available on some CPUs) and the gdb disassembler (available on
12718: platforms with @command{gdb} and @command{mktemp}).  If both are
12719: available, the Forth disassembler is used by default.  If you prefer
12720: the gdb disassembler, say
12721: 
12722: @example
12723: ' disasm-gdb is discode
12724: @end example
12725: 
12726: If neither is available, @code{discode} performs @code{dump}.
12727: 
12728: The Forth disassembler generally produces output that can be fed into the
12729: assembler (i.e., same syntax, etc.).  It also includes additional
12730: information in comments.  In particular, the address of the instruction
12731: is given in a comment before the instruction.
12732: 
12733: The gdb disassembler produces output in the same format as the gdb
12734: @code{disassemble} command (@pxref{Machine Code,,Source and machine
12735: code,gdb,Debugging with GDB}), in the default flavour (AT&T syntax for
12736: the 386 and AMD64 architectures).
12737: 
12738: @code{See} may display more or less than the actual code of the word,
12739: because the recognition of the end of the code is unreliable.  You can
12740: use @code{discode} if it did not display enough.  It may display more, if
12741: the code word is not immediately followed by a named word.  If you have
12742: something else there, you can follow the word with @code{align latest ,}
12743: to ensure that the end is recognized.
12744: 
12745: @node 386 Assembler, Alpha Assembler, Common Disassembler, Assembler and Code Words
12746: @subsection 386 Assembler
12747: 
12748: The 386 assembler included in Gforth was written by Bernd Paysan, it's
12749: available under GPL, and originally part of bigFORTH.
12750: 
12751: The 386 disassembler included in Gforth was written by Andrew McKewan
12752: and is in the public domain.
12753: 
12754: The disassembler displays code in an Intel-like prefix syntax.
12755: 
12756: The assembler uses a postfix syntax with reversed parameters.
12757: 
12758: The assembler includes all instruction of the Athlon, i.e. 486 core
12759: instructions, Pentium and PPro extensions, floating point, MMX, 3Dnow!,
12760: but not ISSE. It's an integrated 16- and 32-bit assembler. Default is 32
12761: bit, you can switch to 16 bit with .86 and back to 32 bit with .386.
12762: 
12763: There are several prefixes to switch between different operation sizes,
12764: @code{.b} for byte accesses, @code{.w} for word accesses, @code{.d} for
12765: double-word accesses. Addressing modes can be switched with @code{.wa}
12766: for 16 bit addresses, and @code{.da} for 32 bit addresses. You don't
12767: need a prefix for byte register names (@code{AL} et al).
12768: 
12769: For floating point operations, the prefixes are @code{.fs} (IEEE
12770: single), @code{.fl} (IEEE double), @code{.fx} (extended), @code{.fw}
12771: (word), @code{.fd} (double-word), and @code{.fq} (quad-word).
12772: 
12773: The MMX opcodes don't have size prefixes, they are spelled out like in
12774: the Intel assembler. Instead of move from and to memory, there are
12775: PLDQ/PLDD and PSTQ/PSTD.
12776: 
12777: The registers lack the 'e' prefix; even in 32 bit mode, eax is called
12778: ax.  Immediate values are indicated by postfixing them with @code{#},
12779: e.g., @code{3 #}.  Here are some examples of addressing modes in various
12780: syntaxes:
12781: 
12782: @example
12783: Gforth          Intel (NASM)   AT&T (gas)      Name
12784: .w ax           ax             %ax             register (16 bit)
12785: ax              eax            %eax            register (32 bit)
12786: 3 #             offset 3       $3              immediate
12787: 1000 #)         byte ptr 1000  1000            displacement
12788: bx )            [ebx]          (%ebx)          base
12789: 100 di d)       100[edi]       100(%edi)       base+displacement
12790: 20 ax *4 i#)    20[eax*4]      20(,%eax,4)     (index*scale)+displacement
12791: di ax *4 i)     [edi][eax*4]   (%edi,%eax,4)   base+(index*scale)
12792: 4 bx cx di)     4[ebx][ecx]    4(%ebx,%ecx)    base+index+displacement
12793: 12 sp ax *2 di) 12[esp][eax*2] 12(%esp,%eax,2) base+(index*scale)+displacement
12794: @end example
12795: 
12796: You can use @code{L)} and @code{LI)} instead of @code{D)} and
12797: @code{DI)} to enforce 32-bit displacement fields (useful for
12798: later patching).
12799: 
12800: Some example of instructions are:
12801: 
12802: @example
12803: ax bx mov             \ move ebx,eax
12804: 3 # ax mov            \ mov eax,3
12805: 100 di d) ax mov      \ mov eax,100[edi]
12806: 4 bx cx di) ax mov    \ mov eax,4[ebx][ecx]
12807: .w ax bx mov          \ mov bx,ax
12808: @end example
12809: 
12810: The following forms are supported for binary instructions:
12811: 
12812: @example
12813: <reg> <reg> <inst>
12814: <n> # <reg> <inst>
12815: <mem> <reg> <inst>
12816: <reg> <mem> <inst>
12817: <n> # <mem> <inst>
12818: @end example
12819: 
12820: The shift/rotate syntax is:
12821: 
12822: @example
12823: <reg/mem> 1 # shl \ shortens to shift without immediate
12824: <reg/mem> 4 # shl
12825: <reg/mem> cl shl
12826: @end example
12827: 
12828: Precede string instructions (@code{movs} etc.) with @code{.b} to get
12829: the byte version.
12830: 
12831: The control structure words @code{IF} @code{UNTIL} etc. must be preceded
12832: by one of these conditions: @code{vs vc u< u>= 0= 0<> u<= u> 0< 0>= ps
12833: pc < >= <= >}. (Note that most of these words shadow some Forth words
12834: when @code{assembler} is in front of @code{forth} in the search path,
12835: e.g., in @code{code} words).  Currently the control structure words use
12836: one stack item, so you have to use @code{roll} instead of @code{cs-roll}
12837: to shuffle them (you can also use @code{swap} etc.).
12838: 
12839: Here is an example of a @code{code} word (assumes that the stack pointer
12840: is in esi and the TOS is in ebx):
12841: 
12842: @example
12843: code my+ ( n1 n2 -- n )
12844:     4 si D) bx add
12845:     4 # si add
12846:     Next
12847: end-code
12848: @end example
12849: 
12850: 
12851: @node Alpha Assembler, MIPS assembler, 386 Assembler, Assembler and Code Words
12852: @subsection Alpha Assembler
12853: 
12854: The Alpha assembler and disassembler were originally written by Bernd
12855: Thallner.
12856: 
12857: The register names @code{a0}--@code{a5} are not available to avoid
12858: shadowing hex numbers.
12859: 
12860: Immediate forms of arithmetic instructions are distinguished by a
12861: @code{#} just before the @code{,}, e.g., @code{and#,} (note: @code{lda,}
12862: does not count as arithmetic instruction).
12863: 
12864: You have to specify all operands to an instruction, even those that
12865: other assemblers consider optional, e.g., the destination register for
12866: @code{br,}, or the destination register and hint for @code{jmp,}.
12867: 
12868: You can specify conditions for @code{if,} by removing the first @code{b}
12869: and the trailing @code{,} from a branch with a corresponding name; e.g.,
12870: 
12871: @example
12872: 11 fgt if, \ if F11>0e
12873:   ...
12874: endif,
12875: @end example
12876: 
12877: @code{fbgt,} gives @code{fgt}.  
12878: 
12879: @node MIPS assembler, PowerPC assembler, Alpha Assembler, Assembler and Code Words
12880: @subsection MIPS assembler
12881: 
12882: The MIPS assembler was originally written by Christian Pirker.
12883: 
12884: Currently the assembler and disassembler only cover the MIPS-I
12885: architecture (R3000), and don't support FP instructions.
12886: 
12887: The register names @code{$a0}--@code{$a3} are not available to avoid
12888: shadowing hex numbers.
12889: 
12890: Because there is no way to distinguish registers from immediate values,
12891: you have to explicitly use the immediate forms of instructions, i.e.,
12892: @code{addiu,}, not just @code{addu,} (@command{as} does this
12893: implicitly).
12894: 
12895: If the architecture manual specifies several formats for the instruction
12896: (e.g., for @code{jalr,}), you usually have to use the one with more
12897: arguments (i.e., two for @code{jalr,}).  When in doubt, see
12898: @code{arch/mips/testasm.fs} for an example of correct use.
12899: 
12900: Branches and jumps in the MIPS architecture have a delay slot.  You have
12901: to fill it yourself (the simplest way is to use @code{nop,}), the
12902: assembler does not do it for you (unlike @command{as}).  Even
12903: @code{if,}, @code{ahead,}, @code{until,}, @code{again,}, @code{while,},
12904: @code{else,} and @code{repeat,} need a delay slot.  Since @code{begin,}
12905: and @code{then,} just specify branch targets, they are not affected.
12906: 
12907: Note that you must not put branches, jumps, or @code{li,} into the delay
12908: slot: @code{li,} may expand to several instructions, and control flow
12909: instructions may not be put into the branch delay slot in any case.
12910: 
12911: For branches the argument specifying the target is a relative address;
12912: You have to add the address of the delay slot to get the absolute
12913: address.
12914: 
12915: The MIPS architecture also has load delay slots and restrictions on
12916: using @code{mfhi,} and @code{mflo,}; you have to order the instructions
12917: yourself to satisfy these restrictions, the assembler does not do it for
12918: you.
12919: 
12920: You can specify the conditions for @code{if,} etc. by taking a
12921: conditional branch and leaving away the @code{b} at the start and the
12922: @code{,} at the end.  E.g.,
12923: 
12924: @example
12925: 4 5 eq if,
12926:   ... \ do something if $4 equals $5
12927: then,
12928: @end example
12929: 
12930: 
12931: @node PowerPC assembler, ARM Assembler, MIPS assembler, Assembler and Code Words
12932: @subsection PowerPC assembler
12933: 
12934: The PowerPC assembler and disassembler were contributed by Michal
12935: Revucky.
12936: 
12937: This assembler does not follow the convention of ending mnemonic names
12938: with a ``,'', so some mnemonic names shadow regular Forth words (in
12939: particular: @code{and or xor fabs}); so if you want to use the Forth
12940: words, you have to make them visible first, e.g., with @code{also
12941: forth}.
12942: 
12943: Registers are referred to by their number, e.g., @code{9} means the
12944: integer register 9 or the FP register 9 (depending on the
12945: instruction).
12946: 
12947: Because there is no way to distinguish registers from immediate values,
12948: you have to explicitly use the immediate forms of instructions, i.e.,
12949: @code{addi,}, not just @code{add,}.
12950: 
12951: The assembler and disassembler usually support the most general form
12952: of an instruction, but usually not the shorter forms (especially for
12953: branches).
12954: 
12955: 
12956: @node ARM Assembler, Other assemblers, PowerPC assembler, Assembler and Code Words
12957: @subsection ARM Assembler
12958: 
12959: The ARM assembler included in Gforth was written from scratch by David
12960: Kuehling.
12961: 
12962: The assembler includes all instruction of ARM architecture version 4,
12963: but does not (yet) have support for Thumb instructions.  It also lacks
12964: support for any co-processors.
12965: 
12966: The assembler uses a postfix syntax with the target operand specified
12967: last.  For load/store instructions the last operand will be the
12968: register(s) to be loaded from/stored to.
12969: 
12970: Registers are specified by their names @code{r0} through @code{r15},
12971: with the aliases @code{pc}, @code{lr}, @code{sp}, @code{ip} and
12972: @code{fp} provided for convenience.  Note that @code{ip} means intra
12973: procedure call scratch register (@code{r12}) and does not refer to the
12974: instruction pointer.
12975: 
12976: Condition codes can be specified anywhere in the instruction, but will
12977: be most readable if specified just in front of the mnemonic.  The 'S'
12978: flag is not a separate word, but encoded into instruction mnemonics,
12979: ie. just use @code{adds,} instead of @code{add,} if you want the
12980: status register to be updated.
12981: 
12982: The following table lists the syntax of operands for general
12983: instructions:
12984: 
12985: @example
12986: Gforth          normal assembler      description
12987: 123 #           #123                  immediate
12988: r12             r12                   register
12989: r12 4 #LSL      r12, LSL #4           shift left by immediate
12990: r12 r1 #LSL     r12, LSL r1           shift left by register
12991: r12 4 #LSR      r12, LSR #4           shift right by immediate
12992: r12 r1 #LSR     r12, LSR r1           shift right by register
12993: r12 4 #ASR      r12, ASR #4           arithmetic shift right
12994: r12 r1 #ASR     r12, ASR r1           ... by register
12995: r12 4 #ROR      r12, ROR #4           rotate right by immediate
12996: r12 r1 #ROR     r12, ROR r1           ... by register
12997: r12 RRX         r12, RRX              rotate right with extend by 1
12998: @end example
12999: 
13000: Memory operand syntax is listed in this table:
13001: 
13002: @example
13003: Gforth            normal assembler      description
13004: r4 ]              [r4]                  register
13005: r4 4 #]           [r4, #+4]             register with immediate offset
13006: r4 -4 #]          [r4, #-4]             with negative offset
13007: r4 r1 +]          [r4, +r1]             register with register offset
13008: r4 r1 -]          [r4, -r1]             with negated register offset
13009: r4 r1 2 #LSL -]   [r4, -r1, LSL #2]     with negated and shifted offset
13010: r4 4 #]!          [r4, #+4]!            immediate preincrement
13011: r4 r1 +]!         [r4, +r1]!            register preincrement
13012: r4 r1 -]!         [r4, +r1]!            register predecrement
13013: r4 r1 2 #LSL +]!  [r4, +r1, LSL #2]!    shifted preincrement
13014: r4 -4 ]#          [r4], #-4             immediate postdecrement
13015: r4 r1 ]+          [r4], r1              register postincrement
13016: r4 r1 ]-          [r4], -r1             register postdecrement
13017: r4 r1 2 #LSL ]-   [r4], -r1, LSL #2     shifted postdecrement
13018: ' xyz >body [#]   xyz                   PC-relative addressing
13019: @end example
13020: 
13021: Register lists for load/store multiple instructions are started and
13022: terminated by using the words @code{@{} and @code{@}}
13023: respectivly.  Between braces, register names can be listed one by one,
13024: or register ranges can be formed by using the postfix operator
13025: @code{r-r}.  The @code{^} flag is not encoded in the register list
13026: operand, but instead directly encoded into the instruction mnemonic,
13027: ie. use @code{^ldm,} and @code{^stm,}.
13028: 
13029: Addressing modes for load/store multiple are not encoded as
13030: instruction suffixes, but instead specified after the register that
13031: supplies the address.  Use one of @code{DA}, @code{IA}, @code{DB},
13032: @code{IB}, @code{DA!}, @code{IA!}, @code{DB!} or @code{IB!}.
13033: 
13034: The following table gives some examples:
13035: 
13036: @example
13037: Gforth                           normal assembler
13038: @{ r0 r7 r8 @}  r4 ia  stm,        stmia    @{r0,r7,r8@}, r4
13039: @{ r0 r7 r8 @}  r4 db!  ldm,       ldmdb    @{r0,r7,r8@}, r4!
13040: @{ r0 r15 r-r @}  sp ia!  ^ldm,    ldmfd    @{r0-r15@}^, sp!
13041: @end example
13042: 
13043: Conditions for control structure words are specified in front of a
13044: word:
13045: 
13046: @example
13047: r1 r2 cmp,    \ compare r1 and r2
13048: eq if,        \ equal?
13049:    ...          \ code executed if r1 == r2
13050: then,
13051: @end example
13052: 
13053: Here is an example of a @code{code} word (assumes that the stack
13054: pointer is in @code{r9}, and that @code{r2} and @code{r3} can be
13055: clobbered):
13056: 
13057: @example
13058: code my+ ( n1 n2 --  n3 )
13059:    r9 IA!       @{ r2 r3 @} ldm,  \ pop r2 = n2, r3 = n1
13060:    r2   r3      r3        add,  \ r3 = n2+n1
13061:    r9 -4 #]!    r3        str,  \ push r3
13062:    next,
13063: end-code
13064: @end example
13065: 
13066: Look at @file{arch/arm/asm-example.fs} for more examples.
13067: 
13068: @node Other assemblers,  , ARM Assembler, Assembler and Code Words
13069: @subsection Other assemblers
13070: 
13071: If you want to contribute another assembler/disassembler, please contact
13072: us (@email{anton@@mips.complang.tuwien.ac.at}) to check if we have such
13073: an assembler already.  If you are writing them from scratch, please use
13074: a similar syntax style as the one we use (i.e., postfix, commas at the
13075: end of the instruction names, @pxref{Common Assembler}); make the output
13076: of the disassembler be valid input for the assembler, and keep the style
13077: similar to the style we used.
13078: 
13079: Hints on implementation: The most important part is to have a good test
13080: suite that contains all instructions.  Once you have that, the rest is
13081: easy.  For actual coding you can take a look at
13082: @file{arch/mips/disasm.fs} to get some ideas on how to use data for both
13083: the assembler and disassembler, avoiding redundancy and some potential
13084: bugs.  You can also look at that file (and @pxref{Advanced does> usage
13085: example}) to get ideas how to factor a disassembler.
13086: 
13087: Start with the disassembler, because it's easier to reuse data from the
13088: disassembler for the assembler than the other way round.
13089: 
13090: For the assembler, take a look at @file{arch/alpha/asm.fs}, which shows
13091: how simple it can be.
13092: 
13093: 
13094: 
13095: 
13096: @c -------------------------------------------------------------
13097: @node Threading Words, Passing Commands to the OS, Assembler and Code Words, Words
13098: @section Threading Words
13099: @cindex threading words
13100: 
13101: @cindex code address
13102: These words provide access to code addresses and other threading stuff
13103: in Gforth (and, possibly, other interpretive Forths). It more or less
13104: abstracts away the differences between direct and indirect threading
13105: (and, for direct threading, the machine dependences). However, at
13106: present this wordset is still incomplete. It is also pretty low-level;
13107: some day it will hopefully be made unnecessary by an internals wordset
13108: that abstracts implementation details away completely.
13109: 
13110: The terminology used here stems from indirect threaded Forth systems; in
13111: such a system, the XT of a word is represented by the CFA (code field
13112: address) of a word; the CFA points to a cell that contains the code
13113: address.  The code address is the address of some machine code that
13114: performs the run-time action of invoking the word (e.g., the
13115: @code{dovar:} routine pushes the address of the body of the word (a
13116: variable) on the stack
13117: ).
13118: 
13119: @cindex code address
13120: @cindex code field address
13121: In an indirect threaded Forth, you can get the code address of @i{name}
13122: with @code{' @i{name} @@}; in Gforth you can get it with @code{' @i{name}
13123: >code-address}, independent of the threading method.
13124: 
13125: doc-threading-method
13126: doc->code-address
13127: doc-code-address!
13128: 
13129: @cindex @code{does>}-handler
13130: @cindex @code{does>}-code
13131: For a word defined with @code{DOES>}, the code address usually points to
13132: a jump instruction (the @dfn{does-handler}) that jumps to the dodoes
13133: routine (in Gforth on some platforms, it can also point to the dodoes
13134: routine itself).  What you are typically interested in, though, is
13135: whether a word is a @code{DOES>}-defined word, and what Forth code it
13136: executes; @code{>does-code} tells you that.
13137: 
13138: doc->does-code
13139: 
13140: To create a @code{DOES>}-defined word with the following basic words,
13141: you have to set up a @code{DOES>}-handler with @code{does-handler!};
13142: @code{/does-handler} aus behind you have to place your executable Forth
13143: code.  Finally you have to create a word and modify its behaviour with
13144: @code{does-handler!}.
13145: 
13146: doc-does-code!
13147: doc-does-handler!
13148: doc-/does-handler
13149: 
13150: The code addresses produced by various defining words are produced by
13151: the following words:
13152: 
13153: doc-docol:
13154: doc-docon:
13155: doc-dovar:
13156: doc-douser:
13157: doc-dodefer:
13158: doc-dofield:
13159: 
13160: @cindex definer
13161: The following two words generalize @code{>code-address},
13162: @code{>does-code}, @code{code-address!}, and @code{does-code!}:
13163: 
13164: doc->definer
13165: doc-definer!
13166: 
13167: @c -------------------------------------------------------------
13168: @node Passing Commands to the OS, Keeping track of Time, Threading Words, Words
13169: @section Passing Commands to the Operating System
13170: @cindex operating system - passing commands
13171: @cindex shell commands
13172: 
13173: Gforth allows you to pass an arbitrary string to the host operating
13174: system shell (if such a thing exists) for execution.
13175: 
13176: doc-sh
13177: doc-system
13178: doc-$?
13179: doc-getenv
13180: 
13181: @c -------------------------------------------------------------
13182: @node Keeping track of Time, Miscellaneous Words, Passing Commands to the OS, Words
13183: @section Keeping track of Time
13184: @cindex time-related words
13185: 
13186: doc-ms
13187: doc-time&date
13188: doc-utime
13189: doc-cputime
13190: 
13191: 
13192: @c -------------------------------------------------------------
13193: @node Miscellaneous Words,  , Keeping track of Time, Words
13194: @section Miscellaneous Words
13195: @cindex miscellaneous words
13196: 
13197: @comment TODO find homes for these
13198: 
13199: These section lists the ANS Forth words that are not documented
13200: elsewhere in this manual. Ultimately, they all need proper homes.
13201: 
13202: doc-quit
13203: 
13204: The following ANS Forth words are not currently supported by Gforth 
13205: (@pxref{ANS conformance}):
13206: 
13207: @code{EDITOR} 
13208: @code{EMIT?} 
13209: @code{FORGET} 
13210: 
13211: @c ******************************************************************
13212: @node Error messages, Tools, Words, Top
13213: @chapter Error messages
13214: @cindex error messages
13215: @cindex backtrace
13216: 
13217: A typical Gforth error message looks like this:
13218: 
13219: @example
13220: in file included from \evaluated string/:-1
13221: in file included from ./yyy.fs:1
13222: ./xxx.fs:4: Invalid memory address
13223: >>>bar<<<
13224: Backtrace:
13225: $400E664C @@
13226: $400E6664 foo
13227: @end example
13228: 
13229: The message identifying the error is @code{Invalid memory address}.  The
13230: error happened when text-interpreting line 4 of the file
13231: @file{./xxx.fs}. This line is given (it contains @code{bar}), and the
13232: word on the line where the error happened, is pointed out (with
13233: @code{>>>} and @code{<<<}).
13234: 
13235: The file containing the error was included in line 1 of @file{./yyy.fs},
13236: and @file{yyy.fs} was included from a non-file (in this case, by giving
13237: @file{yyy.fs} as command-line parameter to Gforth).
13238: 
13239: At the end of the error message you find a return stack dump that can be
13240: interpreted as a backtrace (possibly empty). On top you find the top of
13241: the return stack when the @code{throw} happened, and at the bottom you
13242: find the return stack entry just above the return stack of the topmost
13243: text interpreter.
13244: 
13245: To the right of most return stack entries you see a guess for the word
13246: that pushed that return stack entry as its return address. This gives a
13247: backtrace. In our case we see that @code{bar} called @code{foo}, and
13248: @code{foo} called @code{@@} (and @code{@@} had an @emph{Invalid memory
13249: address} exception).
13250: 
13251: Note that the backtrace is not perfect: We don't know which return stack
13252: entries are return addresses (so we may get false positives); and in
13253: some cases (e.g., for @code{abort"}) we cannot determine from the return
13254: address the word that pushed the return address, so for some return
13255: addresses you see no names in the return stack dump.
13256: 
13257: @cindex @code{catch} and backtraces
13258: The return stack dump represents the return stack at the time when a
13259: specific @code{throw} was executed.  In programs that make use of
13260: @code{catch}, it is not necessarily clear which @code{throw} should be
13261: used for the return stack dump (e.g., consider one @code{throw} that
13262: indicates an error, which is caught, and during recovery another error
13263: happens; which @code{throw} should be used for the stack dump?).
13264: Gforth presents the return stack dump for the first @code{throw} after
13265: the last executed (not returned-to) @code{catch} or @code{nothrow};
13266: this works well in the usual case. To get the right backtrace, you
13267: usually want to insert @code{nothrow} or @code{['] false catch drop}
13268: after a @code{catch} if the error is not rethrown.
13269: 
13270: @cindex @code{gforth-fast} and backtraces
13271: @cindex @code{gforth-fast}, difference from @code{gforth}
13272: @cindex backtraces with @code{gforth-fast}
13273: @cindex return stack dump with @code{gforth-fast}
13274: @code{Gforth} is able to do a return stack dump for throws generated
13275: from primitives (e.g., invalid memory address, stack empty etc.);
13276: @code{gforth-fast} is only able to do a return stack dump from a
13277: directly called @code{throw} (including @code{abort} etc.).  Given an
13278: exception caused by a primitive in @code{gforth-fast}, you will
13279: typically see no return stack dump at all; however, if the exception is
13280: caught by @code{catch} (e.g., for restoring some state), and then
13281: @code{throw}n again, the return stack dump will be for the first such
13282: @code{throw}.
13283: 
13284: @c ******************************************************************
13285: @node Tools, ANS conformance, Error messages, Top
13286: @chapter Tools
13287: 
13288: @menu
13289: * ANS Report::                  Report the words used, sorted by wordset.
13290: * Stack depth changes::         Where does this stack item come from?
13291: @end menu
13292: 
13293: See also @ref{Emacs and Gforth}.
13294: 
13295: @node ANS Report, Stack depth changes, Tools, Tools
13296: @section @file{ans-report.fs}: Report the words used, sorted by wordset
13297: @cindex @file{ans-report.fs}
13298: @cindex report the words used in your program
13299: @cindex words used in your program
13300: 
13301: If you want to label a Forth program as ANS Forth Program, you must
13302: document which wordsets the program uses; for extension wordsets, it is
13303: helpful to list the words the program requires from these wordsets
13304: (because Forth systems are allowed to provide only some words of them).
13305: 
13306: The @file{ans-report.fs} tool makes it easy for you to determine which
13307: words from which wordset and which non-ANS words your application
13308: uses. You simply have to include @file{ans-report.fs} before loading the
13309: program you want to check. After loading your program, you can get the
13310: report with @code{print-ans-report}. A typical use is to run this as
13311: batch job like this:
13312: @example
13313: gforth ans-report.fs myprog.fs -e "print-ans-report bye"
13314: @end example
13315: 
13316: The output looks like this (for @file{compat/control.fs}):
13317: @example
13318: The program uses the following words
13319: from CORE :
13320: : POSTPONE THEN ; immediate ?dup IF 0= 
13321: from BLOCK-EXT :
13322: \ 
13323: from FILE :
13324: ( 
13325: @end example
13326: 
13327: @subsection Caveats
13328: 
13329: Note that @file{ans-report.fs} just checks which words are used, not whether
13330: they are used in an ANS Forth conforming way!
13331: 
13332: Some words are defined in several wordsets in the
13333: standard. @file{ans-report.fs} reports them for only one of the
13334: wordsets, and not necessarily the one you expect. It depends on usage
13335: which wordset is the right one to specify. E.g., if you only use the
13336: compilation semantics of @code{S"}, it is a Core word; if you also use
13337: its interpretation semantics, it is a File word.
13338: 
13339: 
13340: @node Stack depth changes,  , ANS Report, Tools
13341: @section Stack depth changes during interpretation
13342: @cindex @file{depth-changes.fs}
13343: @cindex depth changes during interpretation
13344: @cindex stack depth changes during interpretation
13345: @cindex items on the stack after interpretation
13346: 
13347: Sometimes you notice that, after loading a file, there are items left
13348: on the stack.  The tool @file{depth-changes.fs} helps you find out
13349: quickly where in the file these stack items are coming from.
13350: 
13351: The simplest way of using @file{depth-changes.fs} is to include it
13352: before the file(s) you want to check, e.g.:
13353: 
13354: @example
13355: gforth depth-changes.fs my-file.fs
13356: @end example
13357: 
13358: This will compare the stack depths of the data and FP stack at every
13359: empty line (in interpretation state) against these depths at the last
13360: empty line (in interpretation state).  If the depths are not equal,
13361: the position in the file and the stack contents are printed with
13362: @code{~~} (@pxref{Debugging}).  This indicates that a stack depth
13363: change has occured in the paragraph of non-empty lines before the
13364: indicated line.  It is a good idea to leave an empty line at the end
13365: of the file, so the last paragraph is checked, too.
13366: 
13367: Checking only at empty lines usually works well, but sometimes you
13368: have big blocks of non-empty lines (e.g., when building a big table),
13369: and you want to know where in this block the stack depth changed.  You
13370: can check all interpreted lines with
13371: 
13372: @example
13373: gforth depth-changes.fs -e "' all-lines is depth-changes-filter" my-file.fs
13374: @end example
13375: 
13376: This checks the stack depth at every end-of-line.  So the depth change
13377: occured in the line reported by the @code{~~} (not in the line
13378: before).
13379: 
13380: Note that, while this offers better accuracy in indicating where the
13381: stack depth changes, it will often report many intentional stack depth
13382: changes (e.g., when an interpreted computation stretches across
13383: several lines).  You can suppress the checking of some lines by
13384: putting backslashes at the end of these lines (not followed by white
13385: space), and using
13386: 
13387: @example
13388: gforth depth-changes.fs -e "' most-lines is depth-changes-filter" my-file.fs
13389: @end example
13390: 
13391: @c ******************************************************************
13392: @node ANS conformance, Standard vs Extensions, Tools, Top
13393: @chapter ANS conformance
13394: @cindex ANS conformance of Gforth
13395: 
13396: To the best of our knowledge, Gforth is an
13397: 
13398: ANS Forth System
13399: @itemize @bullet
13400: @item providing the Core Extensions word set
13401: @item providing the Block word set
13402: @item providing the Block Extensions word set
13403: @item providing the Double-Number word set
13404: @item providing the Double-Number Extensions word set
13405: @item providing the Exception word set
13406: @item providing the Exception Extensions word set
13407: @item providing the Facility word set
13408: @item providing @code{EKEY}, @code{EKEY>CHAR}, @code{EKEY?}, @code{MS} and @code{TIME&DATE} from the Facility Extensions word set
13409: @item providing the File Access word set
13410: @item providing the File Access Extensions word set
13411: @item providing the Floating-Point word set
13412: @item providing the Floating-Point Extensions word set
13413: @item providing the Locals word set
13414: @item providing the Locals Extensions word set
13415: @item providing the Memory-Allocation word set
13416: @item providing the Memory-Allocation Extensions word set (that one's easy)
13417: @item providing the Programming-Tools word set
13418: @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
13419: @item providing the Search-Order word set
13420: @item providing the Search-Order Extensions word set
13421: @item providing the String word set
13422: @item providing the String Extensions word set (another easy one)
13423: @end itemize
13424: 
13425: Gforth has the following environmental restrictions:
13426: 
13427: @cindex environmental restrictions
13428: @itemize @bullet
13429: @item
13430: While processing the OS command line, if an exception is not caught,
13431: Gforth exits with a non-zero exit code instyead of performing QUIT.
13432: 
13433: @item
13434: When an @code{throw} is performed after a @code{query}, Gforth does not
13435: allways restore the input source specification in effect at the
13436: corresponding catch.
13437: 
13438: @end itemize
13439: 
13440: 
13441: @cindex system documentation
13442: In addition, ANS Forth systems are required to document certain
13443: implementation choices. This chapter tries to meet these
13444: requirements. In many cases it gives a way to ask the system for the
13445: information instead of providing the information directly, in
13446: particular, if the information depends on the processor, the operating
13447: system or the installation options chosen, or if they are likely to
13448: change during the maintenance of Gforth.
13449: 
13450: @comment The framework for the rest has been taken from pfe.
13451: 
13452: @menu
13453: * The Core Words::              
13454: * The optional Block word set::  
13455: * The optional Double Number word set::  
13456: * The optional Exception word set::  
13457: * The optional Facility word set::  
13458: * The optional File-Access word set::  
13459: * The optional Floating-Point word set::  
13460: * The optional Locals word set::  
13461: * The optional Memory-Allocation word set::  
13462: * The optional Programming-Tools word set::  
13463: * The optional Search-Order word set::  
13464: @end menu
13465: 
13466: 
13467: @c =====================================================================
13468: @node The Core Words, The optional Block word set, ANS conformance, ANS conformance
13469: @comment  node-name,  next,  previous,  up
13470: @section The Core Words
13471: @c =====================================================================
13472: @cindex core words, system documentation
13473: @cindex system documentation, core words
13474: 
13475: @menu
13476: * core-idef::                   Implementation Defined Options                   
13477: * core-ambcond::                Ambiguous Conditions                
13478: * core-other::                  Other System Documentation                  
13479: @end menu
13480: 
13481: @c ---------------------------------------------------------------------
13482: @node core-idef, core-ambcond, The Core Words, The Core Words
13483: @subsection Implementation Defined Options
13484: @c ---------------------------------------------------------------------
13485: @cindex core words, implementation-defined options
13486: @cindex implementation-defined options, core words
13487: 
13488: 
13489: @table @i
13490: @item (Cell) aligned addresses:
13491: @cindex cell-aligned addresses
13492: @cindex aligned addresses
13493: processor-dependent. Gforth's alignment words perform natural alignment
13494: (e.g., an address aligned for a datum of size 8 is divisible by
13495: 8). Unaligned accesses usually result in a @code{-23 THROW}.
13496: 
13497: @item @code{EMIT} and non-graphic characters:
13498: @cindex @code{EMIT} and non-graphic characters
13499: @cindex non-graphic characters and @code{EMIT}
13500: The character is output using the C library function (actually, macro)
13501: @code{putc}.
13502: 
13503: @item character editing of @code{ACCEPT} and @code{EXPECT}:
13504: @cindex character editing of @code{ACCEPT} and @code{EXPECT}
13505: @cindex editing in @code{ACCEPT} and @code{EXPECT}
13506: @cindex @code{ACCEPT}, editing
13507: @cindex @code{EXPECT}, editing
13508: This is modeled on the GNU readline library (@pxref{Readline
13509: Interaction, , Command Line Editing, readline, The GNU Readline
13510: Library}) with Emacs-like key bindings. @kbd{Tab} deviates a little by
13511: producing a full word completion every time you type it (instead of
13512: producing the common prefix of all completions). @xref{Command-line editing}.
13513: 
13514: @item character set:
13515: @cindex character set
13516: The character set of your computer and display device. Gforth is
13517: 8-bit-clean (but some other component in your system may make trouble).
13518: 
13519: @item Character-aligned address requirements:
13520: @cindex character-aligned address requirements
13521: installation-dependent. Currently a character is represented by a C
13522: @code{unsigned char}; in the future we might switch to @code{wchar_t}
13523: (Comments on that requested).
13524: 
13525: @item character-set extensions and matching of names:
13526: @cindex character-set extensions and matching of names
13527: @cindex case-sensitivity for name lookup
13528: @cindex name lookup, case-sensitivity
13529: @cindex locale and case-sensitivity
13530: Any character except the ASCII NUL character can be used in a
13531: name. Matching is case-insensitive (except in @code{TABLE}s). The
13532: matching is performed using the C library function @code{strncasecmp}, whose
13533: function is probably influenced by the locale. E.g., the @code{C} locale
13534: does not know about accents and umlauts, so they are matched
13535: case-sensitively in that locale. For portability reasons it is best to
13536: write programs such that they work in the @code{C} locale. Then one can
13537: use libraries written by a Polish programmer (who might use words
13538: containing ISO Latin-2 encoded characters) and by a French programmer
13539: (ISO Latin-1) in the same program (of course, @code{WORDS} will produce
13540: funny results for some of the words (which ones, depends on the font you
13541: are using)). Also, the locale you prefer may not be available in other
13542: operating systems. Hopefully, Unicode will solve these problems one day.
13543: 
13544: @item conditions under which control characters match a space delimiter:
13545: @cindex space delimiters
13546: @cindex control characters as delimiters
13547: If @code{word} is called with the space character as a delimiter, all
13548: white-space characters (as identified by the C macro @code{isspace()})
13549: are delimiters. @code{Parse}, on the other hand, treats space like other
13550: delimiters.  @code{Parse-name}, which is used by the outer
13551: interpreter (aka text interpreter) by default, treats all white-space
13552: characters as delimiters.
13553: 
13554: @item format of the control-flow stack:
13555: @cindex control-flow stack, format
13556: The data stack is used as control-flow stack. The size of a control-flow
13557: stack item in cells is given by the constant @code{cs-item-size}. At the
13558: time of this writing, an item consists of a (pointer to a) locals list
13559: (third), an address in the code (second), and a tag for identifying the
13560: item (TOS). The following tags are used: @code{defstart},
13561: @code{live-orig}, @code{dead-orig}, @code{dest}, @code{do-dest},
13562: @code{scopestart}.
13563: 
13564: @item conversion of digits > 35
13565: @cindex digits > 35
13566: The characters @code{[\]^_'} are the digits with the decimal value
13567: 36@minus{}41. There is no way to input many of the larger digits.
13568: 
13569: @item display after input terminates in @code{ACCEPT} and @code{EXPECT}:
13570: @cindex @code{EXPECT}, display after end of input
13571: @cindex @code{ACCEPT}, display after end of input
13572: The cursor is moved to the end of the entered string. If the input is
13573: terminated using the @kbd{Return} key, a space is typed.
13574: 
13575: @item exception abort sequence of @code{ABORT"}:
13576: @cindex exception abort sequence of @code{ABORT"}
13577: @cindex @code{ABORT"}, exception abort sequence
13578: The error string is stored into the variable @code{"error} and a
13579: @code{-2 throw} is performed.
13580: 
13581: @item input line terminator:
13582: @cindex input line terminator
13583: @cindex line terminator on input
13584: @cindex newline character on input
13585: For interactive input, @kbd{C-m} (CR) and @kbd{C-j} (LF) terminate
13586: lines. One of these characters is typically produced when you type the
13587: @kbd{Enter} or @kbd{Return} key.
13588: 
13589: @item maximum size of a counted string:
13590: @cindex maximum size of a counted string
13591: @cindex counted string, maximum size
13592: @code{s" /counted-string" environment? drop .}. Currently 255 characters
13593: on all platforms, but this may change.
13594: 
13595: @item maximum size of a parsed string:
13596: @cindex maximum size of a parsed string
13597: @cindex parsed string, maximum size
13598: Given by the constant @code{/line}. Currently 255 characters.
13599: 
13600: @item maximum size of a definition name, in characters:
13601: @cindex maximum size of a definition name, in characters
13602: @cindex name, maximum length
13603: MAXU/8
13604: 
13605: @item maximum string length for @code{ENVIRONMENT?}, in characters:
13606: @cindex maximum string length for @code{ENVIRONMENT?}, in characters
13607: @cindex @code{ENVIRONMENT?} string length, maximum
13608: MAXU/8
13609: 
13610: @item method of selecting the user input device:
13611: @cindex user input device, method of selecting
13612: The user input device is the standard input. There is currently no way to
13613: change it from within Gforth. However, the input can typically be
13614: redirected in the command line that starts Gforth.
13615: 
13616: @item method of selecting the user output device:
13617: @cindex user output device, method of selecting
13618: @code{EMIT} and @code{TYPE} output to the file-id stored in the value
13619: @code{outfile-id} (@code{stdout} by default). Gforth uses unbuffered
13620: output when the user output device is a terminal, otherwise the output
13621: is buffered.
13622: 
13623: @item methods of dictionary compilation:
13624: What are we expected to document here?
13625: 
13626: @item number of bits in one address unit:
13627: @cindex number of bits in one address unit
13628: @cindex address unit, size in bits
13629: @code{s" address-units-bits" environment? drop .}. 8 in all current
13630: platforms.
13631: 
13632: @item number representation and arithmetic:
13633: @cindex number representation and arithmetic
13634: Processor-dependent. Binary two's complement on all current platforms.
13635: 
13636: @item ranges for integer types:
13637: @cindex ranges for integer types
13638: @cindex integer types, ranges
13639: Installation-dependent. Make environmental queries for @code{MAX-N},
13640: @code{MAX-U}, @code{MAX-D} and @code{MAX-UD}. The lower bounds for
13641: unsigned (and positive) types is 0. The lower bound for signed types on
13642: two's complement and one's complement machines machines can be computed
13643: by adding 1 to the upper bound.
13644: 
13645: @item read-only data space regions:
13646: @cindex read-only data space regions
13647: @cindex data-space, read-only regions
13648: The whole Forth data space is writable.
13649: 
13650: @item size of buffer at @code{WORD}:
13651: @cindex size of buffer at @code{WORD}
13652: @cindex @code{WORD} buffer size
13653: @code{PAD HERE - .}. 104 characters on 32-bit machines. The buffer is
13654: shared with the pictured numeric output string. If overwriting
13655: @code{PAD} is acceptable, it is as large as the remaining dictionary
13656: space, although only as much can be sensibly used as fits in a counted
13657: string.
13658: 
13659: @item size of one cell in address units:
13660: @cindex cell size
13661: @code{1 cells .}.
13662: 
13663: @item size of one character in address units:
13664: @cindex char size
13665: @code{1 chars .}. 1 on all current platforms.
13666: 
13667: @item size of the keyboard terminal buffer:
13668: @cindex size of the keyboard terminal buffer
13669: @cindex terminal buffer, size
13670: Varies. You can determine the size at a specific time using @code{lp@@
13671: tib - .}. It is shared with the locals stack and TIBs of files that
13672: include the current file. You can change the amount of space for TIBs
13673: and locals stack at Gforth startup with the command line option
13674: @code{-l}.
13675: 
13676: @item size of the pictured numeric output buffer:
13677: @cindex size of the pictured numeric output buffer
13678: @cindex pictured numeric output buffer, size
13679: @code{PAD HERE - .}. 104 characters on 32-bit machines. The buffer is
13680: shared with @code{WORD}.
13681: 
13682: @item size of the scratch area returned by @code{PAD}:
13683: @cindex size of the scratch area returned by @code{PAD}
13684: @cindex @code{PAD} size
13685: The remainder of dictionary space. @code{unused pad here - - .}.
13686: 
13687: @item system case-sensitivity characteristics:
13688: @cindex case-sensitivity characteristics
13689: Dictionary searches are case-insensitive (except in
13690: @code{TABLE}s). However, as explained above under @i{character-set
13691: extensions}, the matching for non-ASCII characters is determined by the
13692: locale you are using. In the default @code{C} locale all non-ASCII
13693: characters are matched case-sensitively.
13694: 
13695: @item system prompt:
13696: @cindex system prompt
13697: @cindex prompt
13698: @code{ ok} in interpret state, @code{ compiled} in compile state.
13699: 
13700: @item division rounding:
13701: @cindex division rounding
13702: The ordinary division words @code{/ mod /mod */ */mod} perform floored
13703: division (with the default installation of Gforth).  You can check
13704: this with @code{s" floored" environment? drop .}.  If you write
13705: programs that need a specific division rounding, best use
13706: @code{fm/mod} or @code{sm/rem} for portability.
13707: 
13708: @item values of @code{STATE} when true:
13709: @cindex @code{STATE} values
13710: -1.
13711: 
13712: @item values returned after arithmetic overflow:
13713: On two's complement machines, arithmetic is performed modulo
13714: 2**bits-per-cell for single arithmetic and 4**bits-per-cell for double
13715: arithmetic (with appropriate mapping for signed types). Division by
13716: zero typically results in a @code{-55 throw} (Floating-point
13717: unidentified fault) or @code{-10 throw} (divide by zero).  Integer
13718: division overflow can result in these throws, or in @code{-11 throw};
13719: in @code{gforth-fast} division overflow and divide by zero may also
13720: result in returning bogus results without producing an exception.
13721: 
13722: @item whether the current definition can be found after @t{DOES>}:
13723: @cindex @t{DOES>}, visibility of current definition
13724: No.
13725: 
13726: @end table
13727: 
13728: @c ---------------------------------------------------------------------
13729: @node core-ambcond, core-other, core-idef, The Core Words
13730: @subsection Ambiguous conditions
13731: @c ---------------------------------------------------------------------
13732: @cindex core words, ambiguous conditions
13733: @cindex ambiguous conditions, core words
13734: 
13735: @table @i
13736: 
13737: @item a name is neither a word nor a number:
13738: @cindex name not found
13739: @cindex undefined word
13740: @code{-13 throw} (Undefined word).
13741: 
13742: @item a definition name exceeds the maximum length allowed:
13743: @cindex word name too long
13744: @code{-19 throw} (Word name too long)
13745: 
13746: @item addressing a region not inside the various data spaces of the forth system:
13747: @cindex Invalid memory address
13748: The stacks, code space and header space are accessible. Machine code space is
13749: typically readable. Accessing other addresses gives results dependent on
13750: the operating system. On decent systems: @code{-9 throw} (Invalid memory
13751: address).
13752: 
13753: @item argument type incompatible with parameter:
13754: @cindex argument type mismatch
13755: This is usually not caught. Some words perform checks, e.g., the control
13756: flow words, and issue a @code{ABORT"} or @code{-12 THROW} (Argument type
13757: mismatch).
13758: 
13759: @item attempting to obtain the execution token of a word with undefined execution semantics:
13760: @cindex Interpreting a compile-only word, for @code{'} etc.
13761: @cindex execution token of words with undefined execution semantics
13762: @code{-14 throw} (Interpreting a compile-only word). In some cases, you
13763: get an execution token for @code{compile-only-error} (which performs a
13764: @code{-14 throw} when executed).
13765: 
13766: @item dividing by zero:
13767: @cindex dividing by zero
13768: @cindex floating point unidentified fault, integer division
13769: On some platforms, this produces a @code{-10 throw} (Division by
13770: zero); on other systems, this typically results in a @code{-55 throw}
13771: (Floating-point unidentified fault).
13772: 
13773: @item insufficient data stack or return stack space:
13774: @cindex insufficient data stack or return stack space
13775: @cindex stack overflow
13776: @cindex address alignment exception, stack overflow
13777: @cindex Invalid memory address, stack overflow
13778: Depending on the operating system, the installation, and the invocation
13779: of Gforth, this is either checked by the memory management hardware, or
13780: it is not checked. If it is checked, you typically get a @code{-3 throw}
13781: (Stack overflow), @code{-5 throw} (Return stack overflow), or @code{-9
13782: throw} (Invalid memory address) (depending on the platform and how you
13783: achieved the overflow) as soon as the overflow happens. If it is not
13784: checked, overflows typically result in mysterious illegal memory
13785: accesses, producing @code{-9 throw} (Invalid memory address) or
13786: @code{-23 throw} (Address alignment exception); they might also destroy
13787: the internal data structure of @code{ALLOCATE} and friends, resulting in
13788: various errors in these words.
13789: 
13790: @item insufficient space for loop control parameters:
13791: @cindex insufficient space for loop control parameters
13792: Like other return stack overflows.
13793: 
13794: @item insufficient space in the dictionary:
13795: @cindex insufficient space in the dictionary
13796: @cindex dictionary overflow
13797: If you try to allot (either directly with @code{allot}, or indirectly
13798: with @code{,}, @code{create} etc.) more memory than available in the
13799: dictionary, you get a @code{-8 throw} (Dictionary overflow). If you try
13800: to access memory beyond the end of the dictionary, the results are
13801: similar to stack overflows.
13802: 
13803: @item interpreting a word with undefined interpretation semantics:
13804: @cindex interpreting a word with undefined interpretation semantics
13805: @cindex Interpreting a compile-only word
13806: For some words, we have defined interpretation semantics. For the
13807: others: @code{-14 throw} (Interpreting a compile-only word).
13808: 
13809: @item modifying the contents of the input buffer or a string literal:
13810: @cindex modifying the contents of the input buffer or a string literal
13811: These are located in writable memory and can be modified.
13812: 
13813: @item overflow of the pictured numeric output string:
13814: @cindex overflow of the pictured numeric output string
13815: @cindex pictured numeric output string, overflow
13816: @code{-17 throw} (Pictured numeric ouput string overflow).
13817: 
13818: @item parsed string overflow:
13819: @cindex parsed string overflow
13820: @code{PARSE} cannot overflow. @code{WORD} does not check for overflow.
13821: 
13822: @item producing a result out of range:
13823: @cindex result out of range
13824: On two's complement machines, arithmetic is performed modulo
13825: 2**bits-per-cell for single arithmetic and 4**bits-per-cell for double
13826: arithmetic (with appropriate mapping for signed types). Division by
13827: zero typically results in a @code{-10 throw} (divide by zero) or
13828: @code{-55 throw} (floating point unidentified fault). Overflow on
13829: division may result in these errors or in @code{-11 throw} (result out
13830: of range).  @code{Gforth-fast} may silently produce bogus results on
13831: division overflow or division by zero.  @code{Convert} and
13832: @code{>number} currently overflow silently.
13833: 
13834: @item reading from an empty data or return stack:
13835: @cindex stack empty
13836: @cindex stack underflow
13837: @cindex return stack underflow
13838: The data stack is checked by the outer (aka text) interpreter after
13839: every word executed. If it has underflowed, a @code{-4 throw} (Stack
13840: underflow) is performed. Apart from that, stacks may be checked or not,
13841: depending on operating system, installation, and invocation. If they are
13842: caught by a check, they typically result in @code{-4 throw} (Stack
13843: underflow), @code{-6 throw} (Return stack underflow) or @code{-9 throw}
13844: (Invalid memory address), depending on the platform and which stack
13845: underflows and by how much. Note that even if the system uses checking
13846: (through the MMU), your program may have to underflow by a significant
13847: number of stack items to trigger the reaction (the reason for this is
13848: that the MMU, and therefore the checking, works with a page-size
13849: granularity).  If there is no checking, the symptoms resulting from an
13850: underflow are similar to those from an overflow.  Unbalanced return
13851: stack errors can result in a variety of symptoms, including @code{-9 throw}
13852: (Invalid memory address) and Illegal Instruction (typically @code{-260
13853: throw}).
13854: 
13855: @item unexpected end of the input buffer, resulting in an attempt to use a zero-length string as a name:
13856: @cindex unexpected end of the input buffer
13857: @cindex zero-length string as a name
13858: @cindex Attempt to use zero-length string as a name
13859: @code{Create} and its descendants perform a @code{-16 throw} (Attempt to
13860: use zero-length string as a name). Words like @code{'} probably will not
13861: find what they search. Note that it is possible to create zero-length
13862: names with @code{nextname} (should it not?).
13863: 
13864: @item @code{>IN} greater than input buffer:
13865: @cindex @code{>IN} greater than input buffer
13866: The next invocation of a parsing word returns a string with length 0.
13867: 
13868: @item @code{RECURSE} appears after @code{DOES>}:
13869: @cindex @code{RECURSE} appears after @code{DOES>}
13870: Compiles a recursive call to the defining word, not to the defined word.
13871: 
13872: @item argument input source different than current input source for @code{RESTORE-INPUT}:
13873: @cindex argument input source different than current input source for @code{RESTORE-INPUT}
13874: @cindex argument type mismatch, @code{RESTORE-INPUT}
13875: @cindex @code{RESTORE-INPUT}, Argument type mismatch
13876: @code{-12 THROW}. Note that, once an input file is closed (e.g., because
13877: the end of the file was reached), its source-id may be
13878: reused. Therefore, restoring an input source specification referencing a
13879: closed file may lead to unpredictable results instead of a @code{-12
13880: THROW}.
13881: 
13882: In the future, Gforth may be able to restore input source specifications
13883: from other than the current input source.
13884: 
13885: @item data space containing definitions gets de-allocated:
13886: @cindex data space containing definitions gets de-allocated
13887: Deallocation with @code{allot} is not checked. This typically results in
13888: memory access faults or execution of illegal instructions.
13889: 
13890: @item data space read/write with incorrect alignment:
13891: @cindex data space read/write with incorrect alignment
13892: @cindex alignment faults
13893: @cindex address alignment exception
13894: Processor-dependent. Typically results in a @code{-23 throw} (Address
13895: alignment exception). Under Linux-Intel on a 486 or later processor with
13896: alignment turned on, incorrect alignment results in a @code{-9 throw}
13897: (Invalid memory address). There are reportedly some processors with
13898: alignment restrictions that do not report violations.
13899: 
13900: @item data space pointer not properly aligned, @code{,}, @code{C,}:
13901: @cindex data space pointer not properly aligned, @code{,}, @code{C,}
13902: Like other alignment errors.
13903: 
13904: @item less than u+2 stack items (@code{PICK} and @code{ROLL}):
13905: Like other stack underflows.
13906: 
13907: @item loop control parameters not available:
13908: @cindex loop control parameters not available
13909: Not checked. The counted loop words simply assume that the top of return
13910: stack items are loop control parameters and behave accordingly.
13911: 
13912: @item most recent definition does not have a name (@code{IMMEDIATE}):
13913: @cindex most recent definition does not have a name (@code{IMMEDIATE})
13914: @cindex last word was headerless
13915: @code{abort" last word was headerless"}.
13916: 
13917: @item name not defined by @code{VALUE} used by @code{TO}:
13918: @cindex name not defined by @code{VALUE} used by @code{TO}
13919: @cindex @code{TO} on non-@code{VALUE}s
13920: @cindex Invalid name argument, @code{TO}
13921: @code{-32 throw} (Invalid name argument) (unless name is a local or was
13922: defined by @code{CONSTANT}; in the latter case it just changes the constant).
13923: 
13924: @item name not found (@code{'}, @code{POSTPONE}, @code{[']}, @code{[COMPILE]}):
13925: @cindex name not found (@code{'}, @code{POSTPONE}, @code{[']}, @code{[COMPILE]})
13926: @cindex undefined word, @code{'}, @code{POSTPONE}, @code{[']}, @code{[COMPILE]}
13927: @code{-13 throw} (Undefined word)
13928: 
13929: @item parameters are not of the same type (@code{DO}, @code{?DO}, @code{WITHIN}):
13930: @cindex parameters are not of the same type (@code{DO}, @code{?DO}, @code{WITHIN})
13931: Gforth behaves as if they were of the same type. I.e., you can predict
13932: the behaviour by interpreting all parameters as, e.g., signed.
13933: 
13934: @item @code{POSTPONE} or @code{[COMPILE]} applied to @code{TO}:
13935: @cindex @code{POSTPONE} or @code{[COMPILE]} applied to @code{TO}
13936: Assume @code{: X POSTPONE TO ; IMMEDIATE}. @code{X} performs the
13937: compilation semantics of @code{TO}.
13938: 
13939: @item String longer than a counted string returned by @code{WORD}:
13940: @cindex string longer than a counted string returned by @code{WORD}
13941: @cindex @code{WORD}, string overflow
13942: Not checked. The string will be ok, but the count will, of course,
13943: contain only the least significant bits of the length.
13944: 
13945: @item u greater than or equal to the number of bits in a cell (@code{LSHIFT}, @code{RSHIFT}):
13946: @cindex @code{LSHIFT}, large shift counts
13947: @cindex @code{RSHIFT}, large shift counts
13948: Processor-dependent. Typical behaviours are returning 0 and using only
13949: the low bits of the shift count.
13950: 
13951: @item word not defined via @code{CREATE}:
13952: @cindex @code{>BODY} of non-@code{CREATE}d words
13953: @code{>BODY} produces the PFA of the word no matter how it was defined.
13954: 
13955: @cindex @code{DOES>} of non-@code{CREATE}d words
13956: @code{DOES>} changes the execution semantics of the last defined word no
13957: matter how it was defined. E.g., @code{CONSTANT DOES>} is equivalent to
13958: @code{CREATE , DOES>}.
13959: 
13960: @item words improperly used outside @code{<#} and @code{#>}:
13961: Not checked. As usual, you can expect memory faults.
13962: 
13963: @end table
13964: 
13965: 
13966: @c ---------------------------------------------------------------------
13967: @node core-other,  , core-ambcond, The Core Words
13968: @subsection Other system documentation
13969: @c ---------------------------------------------------------------------
13970: @cindex other system documentation, core words
13971: @cindex core words, other system documentation
13972: 
13973: @table @i
13974: @item nonstandard words using @code{PAD}:
13975: @cindex @code{PAD} use by nonstandard words
13976: None.
13977: 
13978: @item operator's terminal facilities available:
13979: @cindex operator's terminal facilities available
13980: After processing the OS's command line, Gforth goes into interactive mode,
13981: and you can give commands to Gforth interactively. The actual facilities
13982: available depend on how you invoke Gforth.
13983: 
13984: @item program data space available:
13985: @cindex program data space available
13986: @cindex data space available
13987: @code{UNUSED .} gives the remaining dictionary space. The total
13988: dictionary space can be specified with the @code{-m} switch
13989: (@pxref{Invoking Gforth}) when Gforth starts up.
13990: 
13991: @item return stack space available:
13992: @cindex return stack space available
13993: You can compute the total return stack space in cells with
13994: @code{s" RETURN-STACK-CELLS" environment? drop .}. You can specify it at
13995: startup time with the @code{-r} switch (@pxref{Invoking Gforth}).
13996: 
13997: @item stack space available:
13998: @cindex stack space available
13999: You can compute the total data stack space in cells with
14000: @code{s" STACK-CELLS" environment? drop .}. You can specify it at
14001: startup time with the @code{-d} switch (@pxref{Invoking Gforth}).
14002: 
14003: @item system dictionary space required, in address units:
14004: @cindex system dictionary space required, in address units
14005: Type @code{here forthstart - .} after startup. At the time of this
14006: writing, this gives 80080 (bytes) on a 32-bit system.
14007: @end table
14008: 
14009: 
14010: @c =====================================================================
14011: @node The optional Block word set, The optional Double Number word set, The Core Words, ANS conformance
14012: @section The optional Block word set
14013: @c =====================================================================
14014: @cindex system documentation, block words
14015: @cindex block words, system documentation
14016: 
14017: @menu
14018: * block-idef::                  Implementation Defined Options
14019: * block-ambcond::               Ambiguous Conditions               
14020: * block-other::                 Other System Documentation                 
14021: @end menu
14022: 
14023: 
14024: @c ---------------------------------------------------------------------
14025: @node block-idef, block-ambcond, The optional Block word set, The optional Block word set
14026: @subsection Implementation Defined Options
14027: @c ---------------------------------------------------------------------
14028: @cindex implementation-defined options, block words
14029: @cindex block words, implementation-defined options
14030: 
14031: @table @i
14032: @item the format for display by @code{LIST}:
14033: @cindex @code{LIST} display format
14034: First the screen number is displayed, then 16 lines of 64 characters,
14035: each line preceded by the line number.
14036: 
14037: @item the length of a line affected by @code{\}:
14038: @cindex length of a line affected by @code{\}
14039: @cindex @code{\}, line length in blocks
14040: 64 characters.
14041: @end table
14042: 
14043: 
14044: @c ---------------------------------------------------------------------
14045: @node block-ambcond, block-other, block-idef, The optional Block word set
14046: @subsection Ambiguous conditions
14047: @c ---------------------------------------------------------------------
14048: @cindex block words, ambiguous conditions
14049: @cindex ambiguous conditions, block words
14050: 
14051: @table @i
14052: @item correct block read was not possible:
14053: @cindex block read not possible
14054: Typically results in a @code{throw} of some OS-derived value (between
14055: -512 and -2048). If the blocks file was just not long enough, blanks are
14056: supplied for the missing portion.
14057: 
14058: @item I/O exception in block transfer:
14059: @cindex I/O exception in block transfer
14060: @cindex block transfer, I/O exception
14061: Typically results in a @code{throw} of some OS-derived value (between
14062: -512 and -2048).
14063: 
14064: @item invalid block number:
14065: @cindex invalid block number
14066: @cindex block number invalid
14067: @code{-35 throw} (Invalid block number)
14068: 
14069: @item a program directly alters the contents of @code{BLK}:
14070: @cindex @code{BLK}, altering @code{BLK}
14071: The input stream is switched to that other block, at the same
14072: position. If the storing to @code{BLK} happens when interpreting
14073: non-block input, the system will get quite confused when the block ends.
14074: 
14075: @item no current block buffer for @code{UPDATE}:
14076: @cindex @code{UPDATE}, no current block buffer
14077: @code{UPDATE} has no effect.
14078: 
14079: @end table
14080: 
14081: @c ---------------------------------------------------------------------
14082: @node block-other,  , block-ambcond, The optional Block word set
14083: @subsection Other system documentation
14084: @c ---------------------------------------------------------------------
14085: @cindex other system documentation, block words
14086: @cindex block words, other system documentation
14087: 
14088: @table @i
14089: @item any restrictions a multiprogramming system places on the use of buffer addresses:
14090: No restrictions (yet).
14091: 
14092: @item the number of blocks available for source and data:
14093: depends on your disk space.
14094: 
14095: @end table
14096: 
14097: 
14098: @c =====================================================================
14099: @node The optional Double Number word set, The optional Exception word set, The optional Block word set, ANS conformance
14100: @section The optional Double Number word set
14101: @c =====================================================================
14102: @cindex system documentation, double words
14103: @cindex double words, system documentation
14104: 
14105: @menu
14106: * double-ambcond::              Ambiguous Conditions              
14107: @end menu
14108: 
14109: 
14110: @c ---------------------------------------------------------------------
14111: @node double-ambcond,  , The optional Double Number word set, The optional Double Number word set
14112: @subsection Ambiguous conditions
14113: @c ---------------------------------------------------------------------
14114: @cindex double words, ambiguous conditions
14115: @cindex ambiguous conditions, double words
14116: 
14117: @table @i
14118: @item @i{d} outside of range of @i{n} in @code{D>S}:
14119: @cindex @code{D>S}, @i{d} out of range of @i{n} 
14120: The least significant cell of @i{d} is produced.
14121: 
14122: @end table
14123: 
14124: 
14125: @c =====================================================================
14126: @node The optional Exception word set, The optional Facility word set, The optional Double Number word set, ANS conformance
14127: @section The optional Exception word set
14128: @c =====================================================================
14129: @cindex system documentation, exception words
14130: @cindex exception words, system documentation
14131: 
14132: @menu
14133: * exception-idef::              Implementation Defined Options              
14134: @end menu
14135: 
14136: 
14137: @c ---------------------------------------------------------------------
14138: @node exception-idef,  , The optional Exception word set, The optional Exception word set
14139: @subsection Implementation Defined Options
14140: @c ---------------------------------------------------------------------
14141: @cindex implementation-defined options, exception words
14142: @cindex exception words, implementation-defined options
14143: 
14144: @table @i
14145: @item @code{THROW}-codes used in the system:
14146: @cindex @code{THROW}-codes used in the system
14147: The codes -256@minus{}-511 are used for reporting signals. The mapping
14148: from OS signal numbers to throw codes is -256@minus{}@i{signal}. The
14149: codes -512@minus{}-2047 are used for OS errors (for file and memory
14150: allocation operations). The mapping from OS error numbers to throw codes
14151: is -512@minus{}@code{errno}. One side effect of this mapping is that
14152: undefined OS errors produce a message with a strange number; e.g.,
14153: @code{-1000 THROW} results in @code{Unknown error 488} on my system.
14154: @end table
14155: 
14156: @c =====================================================================
14157: @node The optional Facility word set, The optional File-Access word set, The optional Exception word set, ANS conformance
14158: @section The optional Facility word set
14159: @c =====================================================================
14160: @cindex system documentation, facility words
14161: @cindex facility words, system documentation
14162: 
14163: @menu
14164: * facility-idef::               Implementation Defined Options               
14165: * facility-ambcond::            Ambiguous Conditions            
14166: @end menu
14167: 
14168: 
14169: @c ---------------------------------------------------------------------
14170: @node facility-idef, facility-ambcond, The optional Facility word set, The optional Facility word set
14171: @subsection Implementation Defined Options
14172: @c ---------------------------------------------------------------------
14173: @cindex implementation-defined options, facility words
14174: @cindex facility words, implementation-defined options
14175: 
14176: @table @i
14177: @item encoding of keyboard events (@code{EKEY}):
14178: @cindex keyboard events, encoding in @code{EKEY}
14179: @cindex @code{EKEY}, encoding of keyboard events
14180: Keys corresponding to ASCII characters are encoded as ASCII characters.
14181: Other keys are encoded with the constants @code{k-left}, @code{k-right},
14182: @code{k-up}, @code{k-down}, @code{k-home}, @code{k-end}, @code{k1},
14183: @code{k2}, @code{k3}, @code{k4}, @code{k5}, @code{k6}, @code{k7},
14184: @code{k8}, @code{k9}, @code{k10}, @code{k11}, @code{k12}.
14185: 
14186: 
14187: @item duration of a system clock tick:
14188: @cindex duration of a system clock tick
14189: @cindex clock tick duration
14190: System dependent. With respect to @code{MS}, the time is specified in
14191: microseconds. How well the OS and the hardware implement this, is
14192: another question.
14193: 
14194: @item repeatability to be expected from the execution of @code{MS}:
14195: @cindex repeatability to be expected from the execution of @code{MS}
14196: @cindex @code{MS}, repeatability to be expected
14197: System dependent. On Unix, a lot depends on load. If the system is
14198: lightly loaded, and the delay is short enough that Gforth does not get
14199: swapped out, the performance should be acceptable. Under MS-DOS and
14200: other single-tasking systems, it should be good.
14201: 
14202: @end table
14203: 
14204: 
14205: @c ---------------------------------------------------------------------
14206: @node facility-ambcond,  , facility-idef, The optional Facility word set
14207: @subsection Ambiguous conditions
14208: @c ---------------------------------------------------------------------
14209: @cindex facility words, ambiguous conditions
14210: @cindex ambiguous conditions, facility words
14211: 
14212: @table @i
14213: @item @code{AT-XY} can't be performed on user output device:
14214: @cindex @code{AT-XY} can't be performed on user output device
14215: Largely terminal dependent. No range checks are done on the arguments.
14216: No errors are reported. You may see some garbage appearing, you may see
14217: simply nothing happen.
14218: 
14219: @end table
14220: 
14221: 
14222: @c =====================================================================
14223: @node The optional File-Access word set, The optional Floating-Point word set, The optional Facility word set, ANS conformance
14224: @section The optional File-Access word set
14225: @c =====================================================================
14226: @cindex system documentation, file words
14227: @cindex file words, system documentation
14228: 
14229: @menu
14230: * file-idef::                   Implementation Defined Options
14231: * file-ambcond::                Ambiguous Conditions                
14232: @end menu
14233: 
14234: @c ---------------------------------------------------------------------
14235: @node file-idef, file-ambcond, The optional File-Access word set, The optional File-Access word set
14236: @subsection Implementation Defined Options
14237: @c ---------------------------------------------------------------------
14238: @cindex implementation-defined options, file words
14239: @cindex file words, implementation-defined options
14240: 
14241: @table @i
14242: @item file access methods used:
14243: @cindex file access methods used
14244: @code{R/O}, @code{R/W} and @code{BIN} work as you would
14245: expect. @code{W/O} translates into the C file opening mode @code{w} (or
14246: @code{wb}): The file is cleared, if it exists, and created, if it does
14247: not (with both @code{open-file} and @code{create-file}).  Under Unix
14248: @code{create-file} creates a file with 666 permissions modified by your
14249: umask.
14250: 
14251: @item file exceptions:
14252: @cindex file exceptions
14253: The file words do not raise exceptions (except, perhaps, memory access
14254: faults when you pass illegal addresses or file-ids).
14255: 
14256: @item file line terminator:
14257: @cindex file line terminator
14258: System-dependent. Gforth uses C's newline character as line
14259: terminator. What the actual character code(s) of this are is
14260: system-dependent.
14261: 
14262: @item file name format:
14263: @cindex file name format
14264: System dependent. Gforth just uses the file name format of your OS.
14265: 
14266: @item information returned by @code{FILE-STATUS}:
14267: @cindex @code{FILE-STATUS}, returned information
14268: @code{FILE-STATUS} returns the most powerful file access mode allowed
14269: for the file: Either @code{R/O}, @code{W/O} or @code{R/W}. If the file
14270: cannot be accessed, @code{R/O BIN} is returned. @code{BIN} is applicable
14271: along with the returned mode.
14272: 
14273: @item input file state after an exception when including source:
14274: @cindex exception when including source
14275: All files that are left via the exception are closed.
14276: 
14277: @item @i{ior} values and meaning:
14278: @cindex @i{ior} values and meaning
14279: @cindex @i{wior} values and meaning
14280: The @i{ior}s returned by the file and memory allocation words are
14281: intended as throw codes. They typically are in the range
14282: -512@minus{}-2047 of OS errors.  The mapping from OS error numbers to
14283: @i{ior}s is -512@minus{}@i{errno}.
14284: 
14285: @item maximum depth of file input nesting:
14286: @cindex maximum depth of file input nesting
14287: @cindex file input nesting, maximum depth
14288: limited by the amount of return stack, locals/TIB stack, and the number
14289: of open files available. This should not give you troubles.
14290: 
14291: @item maximum size of input line:
14292: @cindex maximum size of input line
14293: @cindex input line size, maximum
14294: @code{/line}. Currently 255.
14295: 
14296: @item methods of mapping block ranges to files:
14297: @cindex mapping block ranges to files
14298: @cindex files containing blocks
14299: @cindex blocks in files
14300: By default, blocks are accessed in the file @file{blocks.fb} in the
14301: current working directory. The file can be switched with @code{USE}.
14302: 
14303: @item number of string buffers provided by @code{S"}:
14304: @cindex @code{S"}, number of string buffers
14305: 1
14306: 
14307: @item size of string buffer used by @code{S"}:
14308: @cindex @code{S"}, size of string buffer
14309: @code{/line}. currently 255.
14310: 
14311: @end table
14312: 
14313: @c ---------------------------------------------------------------------
14314: @node file-ambcond,  , file-idef, The optional File-Access word set
14315: @subsection Ambiguous conditions
14316: @c ---------------------------------------------------------------------
14317: @cindex file words, ambiguous conditions
14318: @cindex ambiguous conditions, file words
14319: 
14320: @table @i
14321: @item attempting to position a file outside its boundaries:
14322: @cindex @code{REPOSITION-FILE}, outside the file's boundaries
14323: @code{REPOSITION-FILE} is performed as usual: Afterwards,
14324: @code{FILE-POSITION} returns the value given to @code{REPOSITION-FILE}.
14325: 
14326: @item attempting to read from file positions not yet written:
14327: @cindex reading from file positions not yet written
14328: End-of-file, i.e., zero characters are read and no error is reported.
14329: 
14330: @item @i{file-id} is invalid (@code{INCLUDE-FILE}):
14331: @cindex @code{INCLUDE-FILE}, @i{file-id} is invalid 
14332: An appropriate exception may be thrown, but a memory fault or other
14333: problem is more probable.
14334: 
14335: @item I/O exception reading or closing @i{file-id} (@code{INCLUDE-FILE}, @code{INCLUDED}):
14336: @cindex @code{INCLUDE-FILE}, I/O exception reading or closing @i{file-id}
14337: @cindex @code{INCLUDED}, I/O exception reading or closing @i{file-id}
14338: The @i{ior} produced by the operation, that discovered the problem, is
14339: thrown.
14340: 
14341: @item named file cannot be opened (@code{INCLUDED}):
14342: @cindex @code{INCLUDED}, named file cannot be opened
14343: The @i{ior} produced by @code{open-file} is thrown.
14344: 
14345: @item requesting an unmapped block number:
14346: @cindex unmapped block numbers
14347: There are no unmapped legal block numbers. On some operating systems,
14348: writing a block with a large number may overflow the file system and
14349: have an error message as consequence.
14350: 
14351: @item using @code{source-id} when @code{blk} is non-zero:
14352: @cindex @code{SOURCE-ID}, behaviour when @code{BLK} is non-zero
14353: @code{source-id} performs its function. Typically it will give the id of
14354: the source which loaded the block. (Better ideas?)
14355: 
14356: @end table
14357: 
14358: 
14359: @c =====================================================================
14360: @node  The optional Floating-Point word set, The optional Locals word set, The optional File-Access word set, ANS conformance
14361: @section The optional Floating-Point word set
14362: @c =====================================================================
14363: @cindex system documentation, floating-point words
14364: @cindex floating-point words, system documentation
14365: 
14366: @menu
14367: * floating-idef::               Implementation Defined Options
14368: * floating-ambcond::            Ambiguous Conditions            
14369: @end menu
14370: 
14371: 
14372: @c ---------------------------------------------------------------------
14373: @node floating-idef, floating-ambcond, The optional Floating-Point word set, The optional Floating-Point word set
14374: @subsection Implementation Defined Options
14375: @c ---------------------------------------------------------------------
14376: @cindex implementation-defined options, floating-point words
14377: @cindex floating-point words, implementation-defined options
14378: 
14379: @table @i
14380: @item format and range of floating point numbers:
14381: @cindex format and range of floating point numbers
14382: @cindex floating point numbers, format and range
14383: System-dependent; the @code{double} type of C.
14384: 
14385: @item results of @code{REPRESENT} when @i{float} is out of range:
14386: @cindex  @code{REPRESENT}, results when @i{float} is out of range
14387: System dependent; @code{REPRESENT} is implemented using the C library
14388: function @code{ecvt()} and inherits its behaviour in this respect.
14389: 
14390: @item rounding or truncation of floating-point numbers:
14391: @cindex rounding of floating-point numbers
14392: @cindex truncation of floating-point numbers
14393: @cindex floating-point numbers, rounding or truncation
14394: System dependent; the rounding behaviour is inherited from the hosting C
14395: compiler. IEEE-FP-based (i.e., most) systems by default round to
14396: nearest, and break ties by rounding to even (i.e., such that the last
14397: bit of the mantissa is 0).
14398: 
14399: @item size of floating-point stack:
14400: @cindex floating-point stack size
14401: @code{s" FLOATING-STACK" environment? drop .} gives the total size of
14402: the floating-point stack (in floats). You can specify this on startup
14403: with the command-line option @code{-f} (@pxref{Invoking Gforth}).
14404: 
14405: @item width of floating-point stack:
14406: @cindex floating-point stack width 
14407: @code{1 floats}.
14408: 
14409: @end table
14410: 
14411: 
14412: @c ---------------------------------------------------------------------
14413: @node floating-ambcond,  , floating-idef, The optional Floating-Point word set
14414: @subsection Ambiguous conditions
14415: @c ---------------------------------------------------------------------
14416: @cindex floating-point words, ambiguous conditions
14417: @cindex ambiguous conditions, floating-point words
14418: 
14419: @table @i
14420: @item @code{df@@} or @code{df!} used with an address that is not double-float  aligned:
14421: @cindex @code{df@@} or @code{df!} used with an address that is not double-float  aligned
14422: System-dependent. Typically results in a @code{-23 THROW} like other
14423: alignment violations.
14424: 
14425: @item @code{f@@} or @code{f!} used with an address that is not float  aligned:
14426: @cindex @code{f@@} used with an address that is not float aligned
14427: @cindex @code{f!} used with an address that is not float aligned
14428: System-dependent. Typically results in a @code{-23 THROW} like other
14429: alignment violations.
14430: 
14431: @item floating-point result out of range:
14432: @cindex floating-point result out of range
14433: System-dependent. Can result in a @code{-43 throw} (floating point
14434: overflow), @code{-54 throw} (floating point underflow), @code{-41 throw}
14435: (floating point inexact result), @code{-55 THROW} (Floating-point
14436: unidentified fault), or can produce a special value representing, e.g.,
14437: Infinity.
14438: 
14439: @item @code{sf@@} or @code{sf!} used with an address that is not single-float  aligned:
14440: @cindex @code{sf@@} or @code{sf!} used with an address that is not single-float  aligned
14441: System-dependent. Typically results in an alignment fault like other
14442: alignment violations.
14443: 
14444: @item @code{base} is not decimal (@code{REPRESENT}, @code{F.}, @code{FE.}, @code{FS.}):
14445: @cindex @code{base} is not decimal (@code{REPRESENT}, @code{F.}, @code{FE.}, @code{FS.})
14446: The floating-point number is converted into decimal nonetheless.
14447: 
14448: @item Both arguments are equal to zero (@code{FATAN2}):
14449: @cindex @code{FATAN2}, both arguments are equal to zero
14450: System-dependent. @code{FATAN2} is implemented using the C library
14451: function @code{atan2()}.
14452: 
14453: @item Using @code{FTAN} on an argument @i{r1} where cos(@i{r1}) is zero:
14454: @cindex @code{FTAN} on an argument @i{r1} where cos(@i{r1}) is zero
14455: System-dependent. Anyway, typically the cos of @i{r1} will not be zero
14456: because of small errors and the tan will be a very large (or very small)
14457: but finite number.
14458: 
14459: @item @i{d} cannot be presented precisely as a float in @code{D>F}:
14460: @cindex @code{D>F}, @i{d} cannot be presented precisely as a float
14461: The result is rounded to the nearest float.
14462: 
14463: @item dividing by zero:
14464: @cindex dividing by zero, floating-point
14465: @cindex floating-point dividing by zero
14466: @cindex floating-point unidentified fault, FP divide-by-zero
14467: Platform-dependent; can produce an Infinity, NaN, @code{-42 throw}
14468: (floating point divide by zero) or @code{-55 throw} (Floating-point
14469: unidentified fault).
14470: 
14471: @item exponent too big for conversion (@code{DF!}, @code{DF@@}, @code{SF!}, @code{SF@@}):
14472: @cindex exponent too big for conversion (@code{DF!}, @code{DF@@}, @code{SF!}, @code{SF@@})
14473: System dependent. On IEEE-FP based systems the number is converted into
14474: an infinity.
14475: 
14476: @item @i{float}<1 (@code{FACOSH}):
14477: @cindex @code{FACOSH}, @i{float}<1
14478: @cindex floating-point unidentified fault, @code{FACOSH}
14479: Platform-dependent; on IEEE-FP systems typically produces a NaN.
14480: 
14481: @item @i{float}=<-1 (@code{FLNP1}):
14482: @cindex @code{FLNP1}, @i{float}=<-1
14483: @cindex floating-point unidentified fault, @code{FLNP1}
14484: Platform-dependent; on IEEE-FP systems typically produces a NaN (or a
14485: negative infinity for @i{float}=-1).
14486: 
14487: @item @i{float}=<0 (@code{FLN}, @code{FLOG}):
14488: @cindex @code{FLN}, @i{float}=<0
14489: @cindex @code{FLOG}, @i{float}=<0
14490: @cindex floating-point unidentified fault, @code{FLN} or @code{FLOG}
14491: Platform-dependent; on IEEE-FP systems typically produces a NaN (or a
14492: negative infinity for @i{float}=0).
14493: 
14494: @item @i{float}<0 (@code{FASINH}, @code{FSQRT}):
14495: @cindex @code{FASINH}, @i{float}<0
14496: @cindex @code{FSQRT}, @i{float}<0
14497: @cindex floating-point unidentified fault, @code{FASINH} or @code{FSQRT}
14498: Platform-dependent; for @code{fsqrt} this typically gives a NaN, for
14499: @code{fasinh} some platforms produce a NaN, others a number (bug in the
14500: C library?).
14501: 
14502: @item |@i{float}|>1 (@code{FACOS}, @code{FASIN}, @code{FATANH}):
14503: @cindex @code{FACOS}, |@i{float}|>1
14504: @cindex @code{FASIN}, |@i{float}|>1
14505: @cindex @code{FATANH}, |@i{float}|>1
14506: @cindex floating-point unidentified fault, @code{FACOS}, @code{FASIN} or @code{FATANH}
14507: Platform-dependent; IEEE-FP systems typically produce a NaN.
14508: 
14509: @item integer part of float cannot be represented by @i{d} in @code{F>D}:
14510: @cindex @code{F>D}, integer part of float cannot be represented by @i{d}
14511: @cindex floating-point unidentified fault, @code{F>D}
14512: Platform-dependent; typically, some double number is produced and no
14513: error is reported.
14514: 
14515: @item string larger than pictured numeric output area (@code{f.}, @code{fe.}, @code{fs.}):
14516: @cindex string larger than pictured numeric output area (@code{f.}, @code{fe.}, @code{fs.})
14517: @code{Precision} characters of the numeric output area are used.  If
14518: @code{precision} is too high, these words will smash the data or code
14519: close to @code{here}.
14520: @end table
14521: 
14522: @c =====================================================================
14523: @node  The optional Locals word set, The optional Memory-Allocation word set, The optional Floating-Point word set, ANS conformance
14524: @section The optional Locals word set
14525: @c =====================================================================
14526: @cindex system documentation, locals words
14527: @cindex locals words, system documentation
14528: 
14529: @menu
14530: * locals-idef::                 Implementation Defined Options                 
14531: * locals-ambcond::              Ambiguous Conditions              
14532: @end menu
14533: 
14534: 
14535: @c ---------------------------------------------------------------------
14536: @node locals-idef, locals-ambcond, The optional Locals word set, The optional Locals word set
14537: @subsection Implementation Defined Options
14538: @c ---------------------------------------------------------------------
14539: @cindex implementation-defined options, locals words
14540: @cindex locals words, implementation-defined options
14541: 
14542: @table @i
14543: @item maximum number of locals in a definition:
14544: @cindex maximum number of locals in a definition
14545: @cindex locals, maximum number in a definition
14546: @code{s" #locals" environment? drop .}. Currently 15. This is a lower
14547: bound, e.g., on a 32-bit machine there can be 41 locals of up to 8
14548: characters. The number of locals in a definition is bounded by the size
14549: of locals-buffer, which contains the names of the locals.
14550: 
14551: @end table
14552: 
14553: 
14554: @c ---------------------------------------------------------------------
14555: @node locals-ambcond,  , locals-idef, The optional Locals word set
14556: @subsection Ambiguous conditions
14557: @c ---------------------------------------------------------------------
14558: @cindex locals words, ambiguous conditions
14559: @cindex ambiguous conditions, locals words
14560: 
14561: @table @i
14562: @item executing a named local in interpretation state:
14563: @cindex local in interpretation state
14564: @cindex Interpreting a compile-only word, for a local
14565: Locals have no interpretation semantics. If you try to perform the
14566: interpretation semantics, you will get a @code{-14 throw} somewhere
14567: (Interpreting a compile-only word). If you perform the compilation
14568: semantics, the locals access will be compiled (irrespective of state).
14569: 
14570: @item @i{name} not defined by @code{VALUE} or @code{(LOCAL)} (@code{TO}):
14571: @cindex name not defined by @code{VALUE} or @code{(LOCAL)} used by @code{TO}
14572: @cindex @code{TO} on non-@code{VALUE}s and non-locals
14573: @cindex Invalid name argument, @code{TO}
14574: @code{-32 throw} (Invalid name argument)
14575: 
14576: @end table
14577: 
14578: 
14579: @c =====================================================================
14580: @node  The optional Memory-Allocation word set, The optional Programming-Tools word set, The optional Locals word set, ANS conformance
14581: @section The optional Memory-Allocation word set
14582: @c =====================================================================
14583: @cindex system documentation, memory-allocation words
14584: @cindex memory-allocation words, system documentation
14585: 
14586: @menu
14587: * memory-idef::                 Implementation Defined Options                 
14588: @end menu
14589: 
14590: 
14591: @c ---------------------------------------------------------------------
14592: @node memory-idef,  , The optional Memory-Allocation word set, The optional Memory-Allocation word set
14593: @subsection Implementation Defined Options
14594: @c ---------------------------------------------------------------------
14595: @cindex implementation-defined options, memory-allocation words
14596: @cindex memory-allocation words, implementation-defined options
14597: 
14598: @table @i
14599: @item values and meaning of @i{ior}:
14600: @cindex  @i{ior} values and meaning
14601: The @i{ior}s returned by the file and memory allocation words are
14602: intended as throw codes. They typically are in the range
14603: -512@minus{}-2047 of OS errors.  The mapping from OS error numbers to
14604: @i{ior}s is -512@minus{}@i{errno}.
14605: 
14606: @end table
14607: 
14608: @c =====================================================================
14609: @node  The optional Programming-Tools word set, The optional Search-Order word set, The optional Memory-Allocation word set, ANS conformance
14610: @section The optional Programming-Tools word set
14611: @c =====================================================================
14612: @cindex system documentation, programming-tools words
14613: @cindex programming-tools words, system documentation
14614: 
14615: @menu
14616: * programming-idef::            Implementation Defined Options            
14617: * programming-ambcond::         Ambiguous Conditions         
14618: @end menu
14619: 
14620: 
14621: @c ---------------------------------------------------------------------
14622: @node programming-idef, programming-ambcond, The optional Programming-Tools word set, The optional Programming-Tools word set
14623: @subsection Implementation Defined Options
14624: @c ---------------------------------------------------------------------
14625: @cindex implementation-defined options, programming-tools words
14626: @cindex programming-tools words, implementation-defined options
14627: 
14628: @table @i
14629: @item ending sequence for input following @code{;CODE} and @code{CODE}:
14630: @cindex @code{;CODE} ending sequence
14631: @cindex @code{CODE} ending sequence
14632: @code{END-CODE}
14633: 
14634: @item manner of processing input following @code{;CODE} and @code{CODE}:
14635: @cindex @code{;CODE}, processing input
14636: @cindex @code{CODE}, processing input
14637: The @code{ASSEMBLER} vocabulary is pushed on the search order stack, and
14638: the input is processed by the text interpreter, (starting) in interpret
14639: state.
14640: 
14641: @item search order capability for @code{EDITOR} and @code{ASSEMBLER}:
14642: @cindex @code{ASSEMBLER}, search order capability
14643: The ANS Forth search order word set.
14644: 
14645: @item source and format of display by @code{SEE}:
14646: @cindex @code{SEE}, source and format of output
14647: The source for @code{see} is the executable code used by the inner
14648: interpreter.  The current @code{see} tries to output Forth source code
14649: (and on some platforms, assembly code for primitives) as well as
14650: possible.
14651: 
14652: @end table
14653: 
14654: @c ---------------------------------------------------------------------
14655: @node programming-ambcond,  , programming-idef, The optional Programming-Tools word set
14656: @subsection Ambiguous conditions
14657: @c ---------------------------------------------------------------------
14658: @cindex programming-tools words, ambiguous conditions
14659: @cindex ambiguous conditions, programming-tools words
14660: 
14661: @table @i
14662: 
14663: @item deleting the compilation word list (@code{FORGET}):
14664: @cindex @code{FORGET}, deleting the compilation word list
14665: Not implemented (yet).
14666: 
14667: @item fewer than @i{u}+1 items on the control-flow stack (@code{CS-PICK}, @code{CS-ROLL}):
14668: @cindex @code{CS-PICK}, fewer than @i{u}+1 items on the control flow-stack
14669: @cindex @code{CS-ROLL}, fewer than @i{u}+1 items on the control flow-stack
14670: @cindex control-flow stack underflow
14671: This typically results in an @code{abort"} with a descriptive error
14672: message (may change into a @code{-22 throw} (Control structure mismatch)
14673: in the future). You may also get a memory access error. If you are
14674: unlucky, this ambiguous condition is not caught.
14675: 
14676: @item @i{name} can't be found (@code{FORGET}):
14677: @cindex @code{FORGET}, @i{name} can't be found
14678: Not implemented (yet).
14679: 
14680: @item @i{name} not defined via @code{CREATE}:
14681: @cindex @code{;CODE}, @i{name} not defined via @code{CREATE}
14682: @code{;CODE} behaves like @code{DOES>} in this respect, i.e., it changes
14683: the execution semantics of the last defined word no matter how it was
14684: defined.
14685: 
14686: @item @code{POSTPONE} applied to @code{[IF]}:
14687: @cindex @code{POSTPONE} applied to @code{[IF]}
14688: @cindex @code{[IF]} and @code{POSTPONE}
14689: After defining @code{: X POSTPONE [IF] ; IMMEDIATE}. @code{X} is
14690: equivalent to @code{[IF]}.
14691: 
14692: @item reaching the end of the input source before matching @code{[ELSE]} or @code{[THEN]}:
14693: @cindex @code{[IF]}, end of the input source before matching @code{[ELSE]} or @code{[THEN]}
14694: Continue in the same state of conditional compilation in the next outer
14695: input source. Currently there is no warning to the user about this.
14696: 
14697: @item removing a needed definition (@code{FORGET}):
14698: @cindex @code{FORGET}, removing a needed definition
14699: Not implemented (yet).
14700: 
14701: @end table
14702: 
14703: 
14704: @c =====================================================================
14705: @node  The optional Search-Order word set,  , The optional Programming-Tools word set, ANS conformance
14706: @section The optional Search-Order word set
14707: @c =====================================================================
14708: @cindex system documentation, search-order words
14709: @cindex search-order words, system documentation
14710: 
14711: @menu
14712: * search-idef::                 Implementation Defined Options                 
14713: * search-ambcond::              Ambiguous Conditions              
14714: @end menu
14715: 
14716: 
14717: @c ---------------------------------------------------------------------
14718: @node search-idef, search-ambcond, The optional Search-Order word set, The optional Search-Order word set
14719: @subsection Implementation Defined Options
14720: @c ---------------------------------------------------------------------
14721: @cindex implementation-defined options, search-order words
14722: @cindex search-order words, implementation-defined options
14723: 
14724: @table @i
14725: @item maximum number of word lists in search order:
14726: @cindex maximum number of word lists in search order
14727: @cindex search order, maximum depth
14728: @code{s" wordlists" environment? drop .}. Currently 16.
14729: 
14730: @item minimum search order:
14731: @cindex minimum search order
14732: @cindex search order, minimum
14733: @code{root root}.
14734: 
14735: @end table
14736: 
14737: @c ---------------------------------------------------------------------
14738: @node search-ambcond,  , search-idef, The optional Search-Order word set
14739: @subsection Ambiguous conditions
14740: @c ---------------------------------------------------------------------
14741: @cindex search-order words, ambiguous conditions
14742: @cindex ambiguous conditions, search-order words
14743: 
14744: @table @i
14745: @item changing the compilation word list (during compilation):
14746: @cindex changing the compilation word list (during compilation)
14747: @cindex compilation word list, change before definition ends
14748: The word is entered into the word list that was the compilation word list
14749: at the start of the definition. Any changes to the name field (e.g.,
14750: @code{immediate}) or the code field (e.g., when executing @code{DOES>})
14751: are applied to the latest defined word (as reported by @code{latest} or
14752: @code{latestxt}), if possible, irrespective of the compilation word list.
14753: 
14754: @item search order empty (@code{previous}):
14755: @cindex @code{previous}, search order empty
14756: @cindex vocstack empty, @code{previous}
14757: @code{abort" Vocstack empty"}.
14758: 
14759: @item too many word lists in search order (@code{also}):
14760: @cindex @code{also}, too many word lists in search order
14761: @cindex vocstack full, @code{also}
14762: @code{abort" Vocstack full"}.
14763: 
14764: @end table
14765: 
14766: @c ***************************************************************
14767: @node Standard vs Extensions, Model, ANS conformance, Top
14768: @chapter Should I use Gforth extensions?
14769: @cindex Gforth extensions
14770: 
14771: As you read through the rest of this manual, you will see documentation
14772: for @i{Standard} words, and documentation for some appealing Gforth
14773: @i{extensions}. You might ask yourself the question: @i{``Should I
14774: restrict myself to the standard, or should I use the extensions?''}
14775: 
14776: The answer depends on the goals you have for the program you are working
14777: on:
14778: 
14779: @itemize @bullet
14780: 
14781: @item Is it just for yourself or do you want to share it with others?
14782: 
14783: @item
14784: If you want to share it, do the others all use Gforth?
14785: 
14786: @item
14787: If it is just for yourself, do you want to restrict yourself to Gforth?
14788: 
14789: @end itemize
14790: 
14791: If restricting the program to Gforth is ok, then there is no reason not
14792: to use extensions.  It is still a good idea to keep to the standard
14793: where it is easy, in case you want to reuse these parts in another
14794: program that you want to be portable.
14795: 
14796: If you want to be able to port the program to other Forth systems, there
14797: are the following points to consider:
14798: 
14799: @itemize @bullet
14800: 
14801: @item
14802: Most Forth systems that are being maintained support the ANS Forth
14803: standard.  So if your program complies with the standard, it will be
14804: portable among many systems.
14805: 
14806: @item
14807: A number of the Gforth extensions can be implemented in ANS Forth using
14808: public-domain files provided in the @file{compat/} directory. These are
14809: mentioned in the text in passing.  There is no reason not to use these
14810: extensions, your program will still be ANS Forth compliant; just include
14811: the appropriate compat files with your program.
14812: 
14813: @item
14814: The tool @file{ans-report.fs} (@pxref{ANS Report}) makes it easy to
14815: analyse your program and determine what non-Standard words it relies
14816: upon.  However, it does not check whether you use standard words in a
14817: non-standard way.
14818: 
14819: @item
14820: Some techniques are not standardized by ANS Forth, and are hard or
14821: impossible to implement in a standard way, but can be implemented in
14822: most Forth systems easily, and usually in similar ways (e.g., accessing
14823: word headers).  Forth has a rich historical precedent for programmers
14824: taking advantage of implementation-dependent features of their tools
14825: (for example, relying on a knowledge of the dictionary
14826: structure). Sometimes these techniques are necessary to extract every
14827: last bit of performance from the hardware, sometimes they are just a
14828: programming shorthand.
14829: 
14830: @item
14831: Does using a Gforth extension save more work than the porting this part
14832: to other Forth systems (if any) will cost?
14833: 
14834: @item
14835: Is the additional functionality worth the reduction in portability and
14836: the additional porting problems?
14837: 
14838: @end itemize
14839: 
14840: In order to perform these consideratios, you need to know what's
14841: standard and what's not.  This manual generally states if something is
14842: non-standard, but the authoritative source is the
14843: @uref{http://www.taygeta.com/forth/dpans.html,standard document}.
14844: Appendix A of the Standard (@var{Rationale}) provides a valuable insight
14845: into the thought processes of the technical committee.
14846: 
14847: Note also that portability between Forth systems is not the only
14848: portability issue; there is also the issue of portability between
14849: different platforms (processor/OS combinations).
14850: 
14851: @c ***************************************************************
14852: @node Model, Integrating Gforth, Standard vs Extensions, Top
14853: @chapter Model
14854: 
14855: This chapter has yet to be written. It will contain information, on
14856: which internal structures you can rely.
14857: 
14858: @c ***************************************************************
14859: @node Integrating Gforth, Emacs and Gforth, Model, Top
14860: @chapter Integrating Gforth into C programs
14861: 
14862: This is not yet implemented.
14863: 
14864: Several people like to use Forth as scripting language for applications
14865: that are otherwise written in C, C++, or some other language.
14866: 
14867: The Forth system ATLAST provides facilities for embedding it into
14868: applications; unfortunately it has several disadvantages: most
14869: importantly, it is not based on ANS Forth, and it is apparently dead
14870: (i.e., not developed further and not supported). The facilities
14871: provided by Gforth in this area are inspired by ATLAST's facilities, so
14872: making the switch should not be hard.
14873: 
14874: We also tried to design the interface such that it can easily be
14875: implemented by other Forth systems, so that we may one day arrive at a
14876: standardized interface. Such a standard interface would allow you to
14877: replace the Forth system without having to rewrite C code.
14878: 
14879: You embed the Gforth interpreter by linking with the library
14880: @code{libgforth.a} (give the compiler the option @code{-lgforth}).  All
14881: global symbols in this library that belong to the interface, have the
14882: prefix @code{forth_}. (Global symbols that are used internally have the
14883: prefix @code{gforth_}).
14884: 
14885: You can include the declarations of Forth types and the functions and
14886: variables of the interface with @code{#include <forth.h>}.
14887: 
14888: Types.
14889: 
14890: Variables.
14891: 
14892: Data and FP Stack pointer. Area sizes.
14893: 
14894: functions.
14895: 
14896: forth_init(imagefile)
14897: forth_evaluate(string) exceptions?
14898: forth_goto(address) (or forth_execute(xt)?)
14899: forth_continue() (a corountining mechanism)
14900: 
14901: Adding primitives.
14902: 
14903: No checking.
14904: 
14905: Signals?
14906: 
14907: Accessing the Stacks
14908: 
14909: @c ******************************************************************
14910: @node Emacs and Gforth, Image Files, Integrating Gforth, Top
14911: @chapter Emacs and Gforth
14912: @cindex Emacs and Gforth
14913: 
14914: @cindex @file{gforth.el}
14915: @cindex @file{forth.el}
14916: @cindex Rydqvist, Goran
14917: @cindex Kuehling, David
14918: @cindex comment editing commands
14919: @cindex @code{\}, editing with Emacs
14920: @cindex debug tracer editing commands
14921: @cindex @code{~~}, removal with Emacs
14922: @cindex Forth mode in Emacs
14923: 
14924: Gforth comes with @file{gforth.el}, an improved version of
14925: @file{forth.el} by Goran Rydqvist (included in the TILE package). The
14926: improvements are:
14927: 
14928: @itemize @bullet
14929: @item
14930: A better handling of indentation.
14931: @item
14932: A custom hilighting engine for Forth-code.
14933: @item
14934: Comment paragraph filling (@kbd{M-q})
14935: @item
14936: Commenting (@kbd{C-x \}) and uncommenting (@kbd{C-u C-x \}) of regions
14937: @item
14938: Removal of debugging tracers (@kbd{C-x ~}, @pxref{Debugging}).
14939: @item
14940: Support of the @code{info-lookup} feature for looking up the
14941: documentation of a word.
14942: @item
14943: Support for reading and writing blocks files.
14944: @end itemize
14945: 
14946: To get a basic description of these features, enter Forth mode and
14947: type @kbd{C-h m}.
14948: 
14949: @cindex source location of error or debugging output in Emacs
14950: @cindex error output, finding the source location in Emacs
14951: @cindex debugging output, finding the source location in Emacs
14952: In addition, Gforth supports Emacs quite well: The source code locations
14953: given in error messages, debugging output (from @code{~~}) and failed
14954: assertion messages are in the right format for Emacs' compilation mode
14955: (@pxref{Compilation, , Running Compilations under Emacs, emacs, Emacs
14956: Manual}) so the source location corresponding to an error or other
14957: message is only a few keystrokes away (@kbd{C-x `} for the next error,
14958: @kbd{C-c C-c} for the error under the cursor).
14959: 
14960: @cindex viewing the documentation of a word in Emacs
14961: @cindex context-sensitive help
14962: Moreover, for words documented in this manual, you can look up the
14963: glossary entry quickly by using @kbd{C-h TAB}
14964: (@code{info-lookup-symbol}, @pxref{Documentation, ,Documentation
14965: Commands, emacs, Emacs Manual}).  This feature requires Emacs 20.3 or
14966: later and does not work for words containing @code{:}.
14967: 
14968: @menu
14969: * Installing gforth.el::        Making Emacs aware of Forth.
14970: * Emacs Tags::                  Viewing the source of a word in Emacs.
14971: * Hilighting::                  Making Forth code look prettier.
14972: * Auto-Indentation::            Customizing auto-indentation.
14973: * Blocks Files::                Reading and writing blocks files.
14974: @end menu
14975: 
14976: @c ----------------------------------
14977: @node Installing gforth.el, Emacs Tags, Emacs and Gforth, Emacs and Gforth
14978: @section Installing gforth.el
14979: @cindex @file{.emacs}
14980: @cindex @file{gforth.el}, installation
14981: To make the features from @file{gforth.el} available in Emacs, add
14982: the following lines to your @file{.emacs} file:
14983: 
14984: @example
14985: (autoload 'forth-mode "gforth.el")
14986: (setq auto-mode-alist (cons '("\\.fs\\'" . forth-mode) 
14987: 			    auto-mode-alist))
14988: (autoload 'forth-block-mode "gforth.el")
14989: (setq auto-mode-alist (cons '("\\.fb\\'" . forth-block-mode) 
14990: 			    auto-mode-alist))
14991: (add-hook 'forth-mode-hook (function (lambda ()
14992:    ;; customize variables here:
14993:    (setq forth-indent-level 4)
14994:    (setq forth-minor-indent-level 2)
14995:    (setq forth-hilight-level 3)
14996:    ;;; ...
14997: )))
14998: @end example
14999: 
15000: @c ----------------------------------
15001: @node Emacs Tags, Hilighting, Installing gforth.el, Emacs and Gforth
15002: @section Emacs Tags
15003: @cindex @file{TAGS} file
15004: @cindex @file{etags.fs}
15005: @cindex viewing the source of a word in Emacs
15006: @cindex @code{require}, placement in files
15007: @cindex @code{include}, placement in files
15008: If you @code{require} @file{etags.fs}, a new @file{TAGS} file will be
15009: produced (@pxref{Tags, , Tags Tables, emacs, Emacs Manual}) that
15010: contains the definitions of all words defined afterwards. You can then
15011: find the source for a word using @kbd{M-.}. Note that Emacs can use
15012: several tags files at the same time (e.g., one for the Gforth sources
15013: and one for your program, @pxref{Select Tags Table,,Selecting a Tags
15014: Table,emacs, Emacs Manual}). The TAGS file for the preloaded words is
15015: @file{$(datadir)/gforth/$(VERSION)/TAGS} (e.g.,
15016: @file{/usr/local/share/gforth/0.2.0/TAGS}).  To get the best behaviour
15017: with @file{etags.fs}, you should avoid putting definitions both before
15018: and after @code{require} etc., otherwise you will see the same file
15019: visited several times by commands like @code{tags-search}.
15020: 
15021: @c ----------------------------------
15022: @node Hilighting, Auto-Indentation, Emacs Tags, Emacs and Gforth
15023: @section Hilighting
15024: @cindex hilighting Forth code in Emacs
15025: @cindex highlighting Forth code in Emacs
15026: @file{gforth.el} comes with a custom source hilighting engine.  When
15027: you open a file in @code{forth-mode}, it will be completely parsed,
15028: assigning faces to keywords, comments, strings etc.  While you edit
15029: the file, modified regions get parsed and updated on-the-fly. 
15030: 
15031: Use the variable `forth-hilight-level' to change the level of
15032: decoration from 0 (no hilighting at all) to 3 (the default).  Even if
15033: you set the hilighting level to 0, the parser will still work in the
15034: background, collecting information about whether regions of text are
15035: ``compiled'' or ``interpreted''.  Those information are required for
15036: auto-indentation to work properly.  Set `forth-disable-parser' to
15037: non-nil if your computer is too slow to handle parsing.  This will
15038: have an impact on the smartness of the auto-indentation engine,
15039: though.
15040: 
15041: Sometimes Forth sources define new features that should be hilighted,
15042: new control structures, defining-words etc.  You can use the variable
15043: `forth-custom-words' to make @code{forth-mode} hilight additional
15044: words and constructs.  See the docstring of `forth-words' for details
15045: (in Emacs, type @kbd{C-h v forth-words}).
15046: 
15047: `forth-custom-words' is meant to be customized in your
15048: @file{.emacs} file.  To customize hilighing in a file-specific manner,
15049: set `forth-local-words' in a local-variables section at the end of
15050: your source file (@pxref{Local Variables in Files,, Variables, emacs, Emacs Manual}).
15051: 
15052: Example:
15053: @example
15054: 0 [IF]
15055:    Local Variables:
15056:    forth-local-words:
15057:       ((("t:") definition-starter (font-lock-keyword-face . 1)
15058:         "[ \t\n]" t name (font-lock-function-name-face . 3))
15059:        ((";t") definition-ender (font-lock-keyword-face . 1)))
15060:    End:
15061: [THEN]
15062: @end example
15063: 
15064: @c ----------------------------------
15065: @node Auto-Indentation, Blocks Files, Hilighting, Emacs and Gforth
15066: @section Auto-Indentation
15067: @cindex auto-indentation of Forth code in Emacs
15068: @cindex indentation of Forth code in Emacs
15069: @code{forth-mode} automatically tries to indent lines in a smart way,
15070: whenever you type @key{TAB} or break a line with @kbd{C-m}.
15071: 
15072: Simple customization can be achieved by setting
15073: `forth-indent-level' and `forth-minor-indent-level' in your
15074: @file{.emacs} file. For historical reasons @file{gforth.el} indents
15075: per default by multiples of 4 columns.  To use the more traditional
15076: 3-column indentation, add the following lines to your @file{.emacs}:
15077: 
15078: @example
15079: (add-hook 'forth-mode-hook (function (lambda ()
15080:    ;; customize variables here:
15081:    (setq forth-indent-level 3)
15082:    (setq forth-minor-indent-level 1)
15083: )))
15084: @end example
15085: 
15086: If you want indentation to recognize non-default words, customize it
15087: by setting `forth-custom-indent-words' in your @file{.emacs}.  See the
15088: docstring of `forth-indent-words' for details (in Emacs, type @kbd{C-h
15089: v forth-indent-words}).
15090: 
15091: To customize indentation in a file-specific manner, set
15092: `forth-local-indent-words' in a local-variables section at the end of
15093: your source file (@pxref{Local Variables in Files, Variables,,emacs,
15094: Emacs Manual}).
15095: 
15096: Example:
15097: @example
15098: 0 [IF]
15099:    Local Variables:
15100:    forth-local-indent-words:
15101:       ((("t:") (0 . 2) (0 . 2))
15102:        ((";t") (-2 . 0) (0 . -2)))
15103:    End:
15104: [THEN]
15105: @end example
15106: 
15107: @c ----------------------------------
15108: @node Blocks Files,  , Auto-Indentation, Emacs and Gforth
15109: @section Blocks Files
15110: @cindex blocks files, use with Emacs
15111: @code{forth-mode} Autodetects blocks files by checking whether the
15112: length of the first line exceeds 1023 characters.  It then tries to
15113: convert the file into normal text format.  When you save the file, it
15114: will be written to disk as normal stream-source file.
15115: 
15116: If you want to write blocks files, use @code{forth-blocks-mode}.  It
15117: inherits all the features from @code{forth-mode}, plus some additions:
15118: 
15119: @itemize @bullet
15120: @item
15121: Files are written to disk in blocks file format.
15122: @item
15123: Screen numbers are displayed in the mode line (enumerated beginning
15124: with the value of `forth-block-base')
15125: @item
15126: Warnings are displayed when lines exceed 64 characters.
15127: @item
15128: The beginning of the currently edited block is marked with an
15129: overlay-arrow. 
15130: @end itemize
15131: 
15132: There are some restrictions you should be aware of.  When you open a
15133: blocks file that contains tabulator or newline characters, these
15134: characters will be translated into spaces when the file is written
15135: back to disk.  If tabs or newlines are encountered during blocks file
15136: reading, an error is output to the echo area. So have a look at the
15137: `*Messages*' buffer, when Emacs' bell rings during reading.
15138: 
15139: Please consult the docstring of @code{forth-blocks-mode} for more
15140: information by typing @kbd{C-h v forth-blocks-mode}).
15141: 
15142: @c ******************************************************************
15143: @node Image Files, Engine, Emacs and Gforth, Top
15144: @chapter Image Files
15145: @cindex image file
15146: @cindex @file{.fi} files
15147: @cindex precompiled Forth code
15148: @cindex dictionary in persistent form
15149: @cindex persistent form of dictionary
15150: 
15151: An image file is a file containing an image of the Forth dictionary,
15152: i.e., compiled Forth code and data residing in the dictionary.  By
15153: convention, we use the extension @code{.fi} for image files.
15154: 
15155: @menu
15156: * Image Licensing Issues::      Distribution terms for images.
15157: * Image File Background::       Why have image files?
15158: * Non-Relocatable Image Files::  don't always work.
15159: * Data-Relocatable Image Files::  are better.
15160: * Fully Relocatable Image Files::  better yet.
15161: * Stack and Dictionary Sizes::  Setting the default sizes for an image.
15162: * Running Image Files::         @code{gforth -i @i{file}} or @i{file}.
15163: * Modifying the Startup Sequence::  and turnkey applications.
15164: @end menu
15165: 
15166: @node Image Licensing Issues, Image File Background, Image Files, Image Files
15167: @section Image Licensing Issues
15168: @cindex license for images
15169: @cindex image license
15170: 
15171: An image created with @code{gforthmi} (@pxref{gforthmi}) or
15172: @code{savesystem} (@pxref{Non-Relocatable Image Files}) includes the
15173: original image; i.e., according to copyright law it is a derived work of
15174: the original image.
15175: 
15176: Since Gforth is distributed under the GNU GPL, the newly created image
15177: falls under the GNU GPL, too. In particular, this means that if you
15178: distribute the image, you have to make all of the sources for the image
15179: available, including those you wrote.  For details see @ref{Copying, ,
15180: GNU General Public License (Section 3)}.
15181: 
15182: If you create an image with @code{cross} (@pxref{cross.fs}), the image
15183: contains only code compiled from the sources you gave it; if none of
15184: these sources is under the GPL, the terms discussed above do not apply
15185: to the image. However, if your image needs an engine (a gforth binary)
15186: that is under the GPL, you should make sure that you distribute both in
15187: a way that is at most a @emph{mere aggregation}, if you don't want the
15188: terms of the GPL to apply to the image.
15189: 
15190: @node Image File Background, Non-Relocatable Image Files, Image Licensing Issues, Image Files
15191: @section Image File Background
15192: @cindex image file background
15193: 
15194: Gforth consists not only of primitives (in the engine), but also of
15195: definitions written in Forth. Since the Forth compiler itself belongs to
15196: those definitions, it is not possible to start the system with the
15197: engine and the Forth source alone. Therefore we provide the Forth
15198: code as an image file in nearly executable form. When Gforth starts up,
15199: a C routine loads the image file into memory, optionally relocates the
15200: addresses, then sets up the memory (stacks etc.) according to
15201: information in the image file, and (finally) starts executing Forth
15202: code.
15203: 
15204: The default image file is @file{gforth.fi} (in the @code{GFORTHPATH}).
15205: You can use a different image by using the @code{-i},
15206: @code{--image-file} or @code{--appl-image} options (@pxref{Invoking
15207: Gforth}), e.g.:
15208: 
15209: @example
15210: gforth-fast -i myimage.fi
15211: @end example
15212: 
15213: There are different variants of image files, and they represent
15214: different compromises between the goals of making it easy to generate
15215: image files and making them portable.
15216: 
15217: @cindex relocation at run-time
15218: Win32Forth 3.4 and Mitch Bradley's @code{cforth} use relocation at
15219: run-time. This avoids many of the complications discussed below (image
15220: files are data relocatable without further ado), but costs performance
15221: (one addition per memory access) and makes it difficult to pass
15222: addresses between Forth and library calls or other programs.
15223: 
15224: @cindex relocation at load-time
15225: By contrast, the Gforth loader performs relocation at image load time. The
15226: loader also has to replace tokens that represent primitive calls with the
15227: appropriate code-field addresses (or code addresses in the case of
15228: direct threading).
15229: 
15230: There are three kinds of image files, with different degrees of
15231: relocatability: non-relocatable, data-relocatable, and fully relocatable
15232: image files.
15233: 
15234: @cindex image file loader
15235: @cindex relocating loader
15236: @cindex loader for image files
15237: These image file variants have several restrictions in common; they are
15238: caused by the design of the image file loader:
15239: 
15240: @itemize @bullet
15241: @item
15242: There is only one segment; in particular, this means, that an image file
15243: cannot represent @code{ALLOCATE}d memory chunks (and pointers to
15244: them). The contents of the stacks are not represented, either.
15245: 
15246: @item
15247: The only kinds of relocation supported are: adding the same offset to
15248: all cells that represent data addresses; and replacing special tokens
15249: with code addresses or with pieces of machine code.
15250: 
15251: If any complex computations involving addresses are performed, the
15252: results cannot be represented in the image file. Several applications that
15253: use such computations come to mind:
15254: 
15255: @itemize @minus
15256: @item
15257: Hashing addresses (or data structures which contain addresses) for table
15258: lookup. If you use Gforth's @code{table}s or @code{wordlist}s for this
15259: purpose, you will have no problem, because the hash tables are
15260: recomputed automatically when the system is started. If you use your own
15261: hash tables, you will have to do something similar.
15262: 
15263: @item
15264: There's a cute implementation of doubly-linked lists that uses
15265: @code{XOR}ed addresses. You could represent such lists as singly-linked
15266: in the image file, and restore the doubly-linked representation on
15267: startup.@footnote{In my opinion, though, you should think thrice before
15268: using a doubly-linked list (whatever implementation).}
15269: 
15270: @item
15271: The code addresses of run-time routines like @code{docol:} cannot be
15272: represented in the image file (because their tokens would be replaced by
15273: machine code in direct threaded implementations). As a workaround,
15274: compute these addresses at run-time with @code{>code-address} from the
15275: executions tokens of appropriate words (see the definitions of
15276: @code{docol:} and friends in @file{kernel/getdoers.fs}).
15277: 
15278: @item
15279: On many architectures addresses are represented in machine code in some
15280: shifted or mangled form. You cannot put @code{CODE} words that contain
15281: absolute addresses in this form in a relocatable image file. Workarounds
15282: are representing the address in some relative form (e.g., relative to
15283: the CFA, which is present in some register), or loading the address from
15284: a place where it is stored in a non-mangled form.
15285: @end itemize
15286: @end itemize
15287: 
15288: @node  Non-Relocatable Image Files, Data-Relocatable Image Files, Image File Background, Image Files
15289: @section Non-Relocatable Image Files
15290: @cindex non-relocatable image files
15291: @cindex image file, non-relocatable
15292: 
15293: These files are simple memory dumps of the dictionary. They are
15294: specific to the executable (i.e., @file{gforth} file) they were
15295: created with. What's worse, they are specific to the place on which
15296: the dictionary resided when the image was created. Now, there is no
15297: guarantee that the dictionary will reside at the same place the next
15298: time you start Gforth, so there's no guarantee that a non-relocatable
15299: image will work the next time (Gforth will complain instead of
15300: crashing, though).  Indeed, on OSs with (enabled) address-space
15301: randomization non-relocatable images are unlikely to work.
15302: 
15303: You can create a non-relocatable image file with @code{savesystem}, e.g.:
15304: 
15305: @example
15306: gforth app.fs -e "savesystem app.fi bye"
15307: @end example
15308: 
15309: doc-savesystem
15310: 
15311: 
15312: @node Data-Relocatable Image Files, Fully Relocatable Image Files, Non-Relocatable Image Files, Image Files
15313: @section Data-Relocatable Image Files
15314: @cindex data-relocatable image files
15315: @cindex image file, data-relocatable
15316: 
15317: These files contain relocatable data addresses, but fixed code
15318: addresses (instead of tokens). They are specific to the executable
15319: (i.e., @file{gforth} file) they were created with.  Also, they disable
15320: dynamic native code generation (typically a factor of 2 in speed).
15321: You get a data-relocatable image, if you pass the engine you want to
15322: use through the @code{GFORTHD} environment variable to @file{gforthmi}
15323: (@pxref{gforthmi}), e.g.
15324: 
15325: @example
15326: GFORTHD="/usr/bin/gforth-fast --no-dynamic" gforthmi myimage.fi source.fs
15327: @end example
15328: 
15329: Note that the @code{--no-dynamic} is required here for the image to
15330: work (otherwise it will contain references to dynamically generated
15331: code that is not saved in the image).
15332: 
15333: 
15334: @node Fully Relocatable Image Files, Stack and Dictionary Sizes, Data-Relocatable Image Files, Image Files
15335: @section Fully Relocatable Image Files
15336: @cindex fully relocatable image files
15337: @cindex image file, fully relocatable
15338: 
15339: @cindex @file{kern*.fi}, relocatability
15340: @cindex @file{gforth.fi}, relocatability
15341: These image files have relocatable data addresses, and tokens for code
15342: addresses. They can be used with different binaries (e.g., with and
15343: without debugging) on the same machine, and even across machines with
15344: the same data formats (byte order, cell size, floating point format),
15345: and they work with dynamic native code generation.  However, they are
15346: usually specific to the version of Gforth they were created with. The
15347: files @file{gforth.fi} and @file{kernl*.fi} are fully relocatable.
15348: 
15349: There are two ways to create a fully relocatable image file:
15350: 
15351: @menu
15352: * gforthmi::                    The normal way
15353: * cross.fs::                    The hard way
15354: @end menu
15355: 
15356: @node gforthmi, cross.fs, Fully Relocatable Image Files, Fully Relocatable Image Files
15357: @subsection @file{gforthmi}
15358: @cindex @file{comp-i.fs}
15359: @cindex @file{gforthmi}
15360: 
15361: You will usually use @file{gforthmi}. If you want to create an
15362: image @i{file} that contains everything you would load by invoking
15363: Gforth with @code{gforth @i{options}}, you simply say:
15364: @example
15365: gforthmi @i{file} @i{options}
15366: @end example
15367: 
15368: E.g., if you want to create an image @file{asm.fi} that has the file
15369: @file{asm.fs} loaded in addition to the usual stuff, you could do it
15370: like this:
15371: 
15372: @example
15373: gforthmi asm.fi asm.fs
15374: @end example
15375: 
15376: @file{gforthmi} is implemented as a sh script and works like this: It
15377: produces two non-relocatable images for different addresses and then
15378: compares them. Its output reflects this: first you see the output (if
15379: any) of the two Gforth invocations that produce the non-relocatable image
15380: files, then you see the output of the comparing program: It displays the
15381: offset used for data addresses and the offset used for code addresses;
15382: moreover, for each cell that cannot be represented correctly in the
15383: image files, it displays a line like this:
15384: 
15385: @example
15386:      78DC         BFFFFA50         BFFFFA40
15387: @end example
15388: 
15389: This means that at offset $78dc from @code{forthstart}, one input image
15390: contains $bffffa50, and the other contains $bffffa40. Since these cells
15391: cannot be represented correctly in the output image, you should examine
15392: these places in the dictionary and verify that these cells are dead
15393: (i.e., not read before they are written).
15394: 
15395: @cindex --application, @code{gforthmi} option
15396: If you insert the option @code{--application} in front of the image file
15397: name, you will get an image that uses the @code{--appl-image} option
15398: instead of the @code{--image-file} option (@pxref{Invoking
15399: Gforth}). When you execute such an image on Unix (by typing the image
15400: name as command), the Gforth engine will pass all options to the image
15401: instead of trying to interpret them as engine options.
15402: 
15403: If you type @file{gforthmi} with no arguments, it prints some usage
15404: instructions.
15405: 
15406: @cindex @code{savesystem} during @file{gforthmi}
15407: @cindex @code{bye} during @file{gforthmi}
15408: @cindex doubly indirect threaded code
15409: @cindex environment variables
15410: @cindex @code{GFORTHD} -- environment variable
15411: @cindex @code{GFORTH} -- environment variable
15412: @cindex @code{gforth-ditc}
15413: There are a few wrinkles: After processing the passed @i{options}, the
15414: words @code{savesystem} and @code{bye} must be visible. A special
15415: doubly indirect threaded version of the @file{gforth} executable is
15416: used for creating the non-relocatable images; you can pass the exact
15417: filename of this executable through the environment variable
15418: @code{GFORTHD} (default: @file{gforth-ditc}); if you pass a version
15419: that is not doubly indirect threaded, you will not get a fully
15420: relocatable image, but a data-relocatable image
15421: (@pxref{Data-Relocatable Image Files}), because there is no code
15422: address offset). The normal @file{gforth} executable is used for
15423: creating the relocatable image; you can pass the exact filename of
15424: this executable through the environment variable @code{GFORTH}.
15425: 
15426: @node cross.fs,  , gforthmi, Fully Relocatable Image Files
15427: @subsection @file{cross.fs}
15428: @cindex @file{cross.fs}
15429: @cindex cross-compiler
15430: @cindex metacompiler
15431: @cindex target compiler
15432: 
15433: You can also use @code{cross}, a batch compiler that accepts a Forth-like
15434: programming language (@pxref{Cross Compiler}).
15435: 
15436: @code{cross} allows you to create image files for machines with
15437: different data sizes and data formats than the one used for generating
15438: the image file. You can also use it to create an application image that
15439: does not contain a Forth compiler. These features are bought with
15440: restrictions and inconveniences in programming. E.g., addresses have to
15441: be stored in memory with special words (@code{A!}, @code{A,}, etc.) in
15442: order to make the code relocatable.
15443: 
15444: 
15445: @node Stack and Dictionary Sizes, Running Image Files, Fully Relocatable Image Files, Image Files
15446: @section Stack and Dictionary Sizes
15447: @cindex image file, stack and dictionary sizes
15448: @cindex dictionary size default
15449: @cindex stack size default
15450: 
15451: If you invoke Gforth with a command line flag for the size
15452: (@pxref{Invoking Gforth}), the size you specify is stored in the
15453: dictionary. If you save the dictionary with @code{savesystem} or create
15454: an image with @file{gforthmi}, this size will become the default
15455: for the resulting image file. E.g., the following will create a
15456: fully relocatable version of @file{gforth.fi} with a 1MB dictionary:
15457: 
15458: @example
15459: gforthmi gforth.fi -m 1M
15460: @end example
15461: 
15462: In other words, if you want to set the default size for the dictionary
15463: and the stacks of an image, just invoke @file{gforthmi} with the
15464: appropriate options when creating the image.
15465: 
15466: @cindex stack size, cache-friendly
15467: Note: For cache-friendly behaviour (i.e., good performance), you should
15468: make the sizes of the stacks modulo, say, 2K, somewhat different. E.g.,
15469: the default stack sizes are: data: 16k (mod 2k=0); fp: 15.5k (mod
15470: 2k=1.5k); return: 15k(mod 2k=1k); locals: 14.5k (mod 2k=0.5k).
15471: 
15472: @node Running Image Files, Modifying the Startup Sequence, Stack and Dictionary Sizes, Image Files
15473: @section Running Image Files
15474: @cindex running image files
15475: @cindex invoking image files
15476: @cindex image file invocation
15477: 
15478: @cindex -i, invoke image file
15479: @cindex --image file, invoke image file
15480: You can invoke Gforth with an image file @i{image} instead of the
15481: default @file{gforth.fi} with the @code{-i} flag (@pxref{Invoking Gforth}):
15482: @example
15483: gforth -i @i{image}
15484: @end example
15485: 
15486: @cindex executable image file
15487: @cindex image file, executable
15488: If your operating system supports starting scripts with a line of the
15489: form @code{#! ...}, you just have to type the image file name to start
15490: Gforth with this image file (note that the file extension @code{.fi} is
15491: just a convention). I.e., to run Gforth with the image file @i{image},
15492: you can just type @i{image} instead of @code{gforth -i @i{image}}.
15493: This works because every @code{.fi} file starts with a line of this
15494: format:
15495: 
15496: @example
15497: #! /usr/local/bin/gforth-0.4.0 -i
15498: @end example
15499: 
15500: The file and pathname for the Gforth engine specified on this line is
15501: the specific Gforth executable that it was built against; i.e. the value
15502: of the environment variable @code{GFORTH} at the time that
15503: @file{gforthmi} was executed.
15504: 
15505: You can make use of the same shell capability to make a Forth source
15506: file into an executable. For example, if you place this text in a file:
15507: 
15508: @example
15509: #! /usr/local/bin/gforth
15510: 
15511: ." Hello, world" CR
15512: bye
15513: @end example
15514: 
15515: @noindent
15516: and then make the file executable (chmod +x in Unix), you can run it
15517: directly from the command line. The sequence @code{#!} is used in two
15518: ways; firstly, it is recognised as a ``magic sequence'' by the operating
15519: system@footnote{The Unix kernel actually recognises two types of files:
15520: executable files and files of data, where the data is processed by an
15521: interpreter that is specified on the ``interpreter line'' -- the first
15522: line of the file, starting with the sequence #!. There may be a small
15523: limit (e.g., 32) on the number of characters that may be specified on
15524: the interpreter line.} secondly it is treated as a comment character by
15525: Gforth. Because of the second usage, a space is required between
15526: @code{#!} and the path to the executable (moreover, some Unixes
15527: require the sequence @code{#! /}).
15528: 
15529: The disadvantage of this latter technique, compared with using
15530: @file{gforthmi}, is that it is slightly slower; the Forth source code is
15531: compiled on-the-fly, each time the program is invoked.
15532: 
15533: doc-#!
15534: 
15535: 
15536: @node Modifying the Startup Sequence,  , Running Image Files, Image Files
15537: @section Modifying the Startup Sequence
15538: @cindex startup sequence for image file
15539: @cindex image file initialization sequence
15540: @cindex initialization sequence of image file
15541: 
15542: You can add your own initialization to the startup sequence of an image
15543: through the deferred word @code{'cold}. @code{'cold} is invoked just
15544: before the image-specific command line processing (i.e., loading files
15545: and evaluating (@code{-e}) strings) starts.
15546: 
15547: A sequence for adding your initialization usually looks like this:
15548: 
15549: @example
15550: :noname
15551:     Defers 'cold \ do other initialization stuff (e.g., rehashing wordlists)
15552:     ... \ your stuff
15553: ; IS 'cold
15554: @end example
15555: 
15556: After @code{'cold}, Gforth processes the image options
15557: (@pxref{Invoking Gforth}), and then it performs @code{bootmessage},
15558: another deferred word.  This normally prints Gforth's startup message
15559: and does nothing else.
15560: 
15561: @cindex turnkey image files
15562: @cindex image file, turnkey applications
15563: So, if you want to make a turnkey image (i.e., an image for an
15564: application instead of an extended Forth system), you can do this in
15565: two ways:
15566: 
15567: @itemize @bullet
15568: 
15569: @item
15570: If you want to do your interpretation of the OS command-line
15571: arguments, hook into @code{'cold}.  In that case you probably also
15572: want to build the image with @code{gforthmi --application}
15573: (@pxref{gforthmi}) to keep the engine from processing OS command line
15574: options.  You can then do your own command-line processing with
15575: @code{next-arg} 
15576: 
15577: @item
15578: If you want to have the normal Gforth processing of OS command-line
15579: arguments, hook into @code{bootmessage}.
15580: 
15581: @end itemize
15582: 
15583: In either case, you probably do not want the word that you execute in
15584: these hooks to exit normally, but use @code{bye} or @code{throw}.
15585: Otherwise the Gforth startup process would continue and eventually
15586: present the Forth command line to the user.
15587: 
15588: doc-'cold
15589: doc-bootmessage
15590: 
15591: @c ******************************************************************
15592: @node Engine, Cross Compiler, Image Files, Top
15593: @chapter Engine
15594: @cindex engine
15595: @cindex virtual machine
15596: 
15597: Reading this chapter is not necessary for programming with Gforth. It
15598: may be helpful for finding your way in the Gforth sources.
15599: 
15600: The ideas in this section have also been published in the following
15601: papers: Bernd Paysan, @cite{ANS fig/GNU/??? Forth} (in German),
15602: Forth-Tagung '93; M. Anton Ertl,
15603: @cite{@uref{http://www.complang.tuwien.ac.at/papers/ertl93.ps.Z, A
15604: Portable Forth Engine}}, EuroForth '93; M. Anton Ertl,
15605: @cite{@uref{http://www.complang.tuwien.ac.at/papers/ertl02.ps.gz,
15606: Threaded code variations and optimizations (extended version)}},
15607: Forth-Tagung '02.
15608: 
15609: @menu
15610: * Portability::                 
15611: * Threading::                   
15612: * Primitives::                  
15613: * Performance::                 
15614: @end menu
15615: 
15616: @node Portability, Threading, Engine, Engine
15617: @section Portability
15618: @cindex engine portability
15619: 
15620: An important goal of the Gforth Project is availability across a wide
15621: range of personal machines. fig-Forth, and, to a lesser extent, F83,
15622: achieved this goal by manually coding the engine in assembly language
15623: for several then-popular processors. This approach is very
15624: labor-intensive and the results are short-lived due to progress in
15625: computer architecture.
15626: 
15627: @cindex C, using C for the engine
15628: Others have avoided this problem by coding in C, e.g., Mitch Bradley
15629: (cforth), Mikael Patel (TILE) and Dirk Zoller (pfe). This approach is
15630: particularly popular for UNIX-based Forths due to the large variety of
15631: architectures of UNIX machines. Unfortunately an implementation in C
15632: does not mix well with the goals of efficiency and with using
15633: traditional techniques: Indirect or direct threading cannot be expressed
15634: in C, and switch threading, the fastest technique available in C, is
15635: significantly slower. Another problem with C is that it is very
15636: cumbersome to express double integer arithmetic.
15637: 
15638: @cindex GNU C for the engine
15639: @cindex long long
15640: Fortunately, there is a portable language that does not have these
15641: limitations: GNU C, the version of C processed by the GNU C compiler
15642: (@pxref{C Extensions, , Extensions to the C Language Family, gcc.info,
15643: GNU C Manual}). Its labels as values feature (@pxref{Labels as Values, ,
15644: Labels as Values, gcc.info, GNU C Manual}) makes direct and indirect
15645: threading possible, its @code{long long} type (@pxref{Long Long, ,
15646: Double-Word Integers, gcc.info, GNU C Manual}) corresponds to Forth's
15647: double numbers on many systems.  GNU C is freely available on all
15648: important (and many unimportant) UNIX machines, VMS, 80386s running
15649: MS-DOS, the Amiga, and the Atari ST, so a Forth written in GNU C can run
15650: on all these machines.
15651: 
15652: Writing in a portable language has the reputation of producing code that
15653: is slower than assembly. For our Forth engine we repeatedly looked at
15654: the code produced by the compiler and eliminated most compiler-induced
15655: inefficiencies by appropriate changes in the source code.
15656: 
15657: @cindex explicit register declarations
15658: @cindex --enable-force-reg, configuration flag
15659: @cindex -DFORCE_REG
15660: However, register allocation cannot be portably influenced by the
15661: programmer, leading to some inefficiencies on register-starved
15662: machines. We use explicit register declarations (@pxref{Explicit Reg
15663: Vars, , Variables in Specified Registers, gcc.info, GNU C Manual}) to
15664: improve the speed on some machines. They are turned on by using the
15665: configuration flag @code{--enable-force-reg} (@code{gcc} switch
15666: @code{-DFORCE_REG}). Unfortunately, this feature not only depends on the
15667: machine, but also on the compiler version: On some machines some
15668: compiler versions produce incorrect code when certain explicit register
15669: declarations are used. So by default @code{-DFORCE_REG} is not used.
15670: 
15671: @node Threading, Primitives, Portability, Engine
15672: @section Threading
15673: @cindex inner interpreter implementation
15674: @cindex threaded code implementation
15675: 
15676: @cindex labels as values
15677: GNU C's labels as values extension (available since @code{gcc-2.0},
15678: @pxref{Labels as Values, , Labels as Values, gcc.info, GNU C Manual})
15679: makes it possible to take the address of @i{label} by writing
15680: @code{&&@i{label}}.  This address can then be used in a statement like
15681: @code{goto *@i{address}}. I.e., @code{goto *&&x} is the same as
15682: @code{goto x}.
15683: 
15684: @cindex @code{NEXT}, indirect threaded
15685: @cindex indirect threaded inner interpreter
15686: @cindex inner interpreter, indirect threaded
15687: With this feature an indirect threaded @code{NEXT} looks like:
15688: @example
15689: cfa = *ip++;
15690: ca = *cfa;
15691: goto *ca;
15692: @end example
15693: @cindex instruction pointer
15694: For those unfamiliar with the names: @code{ip} is the Forth instruction
15695: pointer; the @code{cfa} (code-field address) corresponds to ANS Forths
15696: execution token and points to the code field of the next word to be
15697: executed; The @code{ca} (code address) fetched from there points to some
15698: executable code, e.g., a primitive or the colon definition handler
15699: @code{docol}.
15700: 
15701: @cindex @code{NEXT}, direct threaded
15702: @cindex direct threaded inner interpreter
15703: @cindex inner interpreter, direct threaded
15704: Direct threading is even simpler:
15705: @example
15706: ca = *ip++;
15707: goto *ca;
15708: @end example
15709: 
15710: Of course we have packaged the whole thing neatly in macros called
15711: @code{NEXT} and @code{NEXT1} (the part of @code{NEXT} after fetching the cfa).
15712: 
15713: @menu
15714: * Scheduling::                  
15715: * Direct or Indirect Threaded?::  
15716: * Dynamic Superinstructions::   
15717: * DOES>::                       
15718: @end menu
15719: 
15720: @node Scheduling, Direct or Indirect Threaded?, Threading, Threading
15721: @subsection Scheduling
15722: @cindex inner interpreter optimization
15723: 
15724: There is a little complication: Pipelined and superscalar processors,
15725: i.e., RISC and some modern CISC machines can process independent
15726: instructions while waiting for the results of an instruction. The
15727: compiler usually reorders (schedules) the instructions in a way that
15728: achieves good usage of these delay slots. However, on our first tries
15729: the compiler did not do well on scheduling primitives. E.g., for
15730: @code{+} implemented as
15731: @example
15732: n=sp[0]+sp[1];
15733: sp++;
15734: sp[0]=n;
15735: NEXT;
15736: @end example
15737: the @code{NEXT} comes strictly after the other code, i.e., there is
15738: nearly no scheduling. After a little thought the problem becomes clear:
15739: The compiler cannot know that @code{sp} and @code{ip} point to different
15740: addresses (and the version of @code{gcc} we used would not know it even
15741: if it was possible), so it could not move the load of the cfa above the
15742: store to the TOS. Indeed the pointers could be the same, if code on or
15743: very near the top of stack were executed. In the interest of speed we
15744: chose to forbid this probably unused ``feature'' and helped the compiler
15745: in scheduling: @code{NEXT} is divided into several parts:
15746: @code{NEXT_P0}, @code{NEXT_P1} and @code{NEXT_P2}). @code{+} now looks
15747: like:
15748: @example
15749: NEXT_P0;
15750: n=sp[0]+sp[1];
15751: sp++;
15752: NEXT_P1;
15753: sp[0]=n;
15754: NEXT_P2;
15755: @end example
15756: 
15757: There are various schemes that distribute the different operations of
15758: NEXT between these parts in several ways; in general, different schemes
15759: perform best on different processors.  We use a scheme for most
15760: architectures that performs well for most processors of this
15761: architecture; in the future we may switch to benchmarking and chosing
15762: the scheme on installation time.
15763: 
15764: 
15765: @node Direct or Indirect Threaded?, Dynamic Superinstructions, Scheduling, Threading
15766: @subsection Direct or Indirect Threaded?
15767: @cindex threading, direct or indirect?
15768: 
15769: Threaded forth code consists of references to primitives (simple machine
15770: code routines like @code{+}) and to non-primitives (e.g., colon
15771: definitions, variables, constants); for a specific class of
15772: non-primitives (e.g., variables) there is one code routine (e.g.,
15773: @code{dovar}), but each variable needs a separate reference to its data.
15774: 
15775: Traditionally Forth has been implemented as indirect threaded code,
15776: because this allows to use only one cell to reference a non-primitive
15777: (basically you point to the data, and find the code address there).
15778: 
15779: @cindex primitive-centric threaded code
15780: However, threaded code in Gforth (since 0.6.0) uses two cells for
15781: non-primitives, one for the code address, and one for the data address;
15782: the data pointer is an immediate argument for the virtual machine
15783: instruction represented by the code address.  We call this
15784: @emph{primitive-centric} threaded code, because all code addresses point
15785: to simple primitives.  E.g., for a variable, the code address is for
15786: @code{lit} (also used for integer literals like @code{99}).
15787: 
15788: Primitive-centric threaded code allows us to use (faster) direct
15789: threading as dispatch method, completely portably (direct threaded code
15790: in Gforth before 0.6.0 required architecture-specific code).  It also
15791: eliminates the performance problems related to I-cache consistency that
15792: 386 implementations have with direct threaded code, and allows
15793: additional optimizations.
15794: 
15795: @cindex hybrid direct/indirect threaded code
15796: There is a catch, however: the @var{xt} parameter of @code{execute} can
15797: occupy only one cell, so how do we pass non-primitives with their code
15798: @emph{and} data addresses to them?  Our answer is to use indirect
15799: threaded dispatch for @code{execute} and other words that use a
15800: single-cell xt.  So, normal threaded code in colon definitions uses
15801: direct threading, and @code{execute} and similar words, which dispatch
15802: to xts on the data stack, use indirect threaded code.  We call this
15803: @emph{hybrid direct/indirect} threaded code.
15804: 
15805: @cindex engines, gforth vs. gforth-fast vs. gforth-itc
15806: @cindex gforth engine
15807: @cindex gforth-fast engine
15808: The engines @command{gforth} and @command{gforth-fast} use hybrid
15809: direct/indirect threaded code.  This means that with these engines you
15810: cannot use @code{,} to compile an xt.  Instead, you have to use
15811: @code{compile,}.
15812: 
15813: @cindex gforth-itc engine
15814: If you want to compile xts with @code{,}, use @command{gforth-itc}.
15815: This engine uses plain old indirect threaded code.  It still compiles in
15816: a primitive-centric style, so you cannot use @code{compile,} instead of
15817: @code{,} (e.g., for producing tables of xts with @code{] word1 word2
15818: ... [}).  If you want to do that, you have to use @command{gforth-itc}
15819: and execute @code{' , is compile,}.  Your program can check if it is
15820: running on a hybrid direct/indirect threaded engine or a pure indirect
15821: threaded engine with @code{threading-method} (@pxref{Threading Words}).
15822: 
15823: 
15824: @node Dynamic Superinstructions, DOES>, Direct or Indirect Threaded?, Threading
15825: @subsection Dynamic Superinstructions
15826: @cindex Dynamic superinstructions with replication
15827: @cindex Superinstructions
15828: @cindex Replication
15829: 
15830: The engines @command{gforth} and @command{gforth-fast} use another
15831: optimization: Dynamic superinstructions with replication.  As an
15832: example, consider the following colon definition:
15833: 
15834: @example
15835: : squared ( n1 -- n2 )
15836:   dup * ;
15837: @end example
15838: 
15839: Gforth compiles this into the threaded code sequence
15840: 
15841: @example
15842: dup
15843: *
15844: ;s
15845: @end example
15846: 
15847: In normal direct threaded code there is a code address occupying one
15848: cell for each of these primitives.  Each code address points to a
15849: machine code routine, and the interpreter jumps to this machine code in
15850: order to execute the primitive.  The routines for these three
15851: primitives are (in @command{gforth-fast} on the 386):
15852: 
15853: @example
15854: Code dup  
15855: ( $804B950 )  add     esi , # -4  \ $83 $C6 $FC 
15856: ( $804B953 )  add     ebx , # 4  \ $83 $C3 $4 
15857: ( $804B956 )  mov     dword ptr 4 [esi] , ecx  \ $89 $4E $4 
15858: ( $804B959 )  jmp     dword ptr FC [ebx]  \ $FF $63 $FC 
15859: end-code
15860: Code *  
15861: ( $804ACC4 )  mov     eax , dword ptr 4 [esi]  \ $8B $46 $4 
15862: ( $804ACC7 )  add     esi , # 4  \ $83 $C6 $4 
15863: ( $804ACCA )  add     ebx , # 4  \ $83 $C3 $4 
15864: ( $804ACCD )  imul    ecx , eax  \ $F $AF $C8 
15865: ( $804ACD0 )  jmp     dword ptr FC [ebx]  \ $FF $63 $FC 
15866: end-code
15867: Code ;s  
15868: ( $804A693 )  mov     eax , dword ptr [edi]  \ $8B $7 
15869: ( $804A695 )  add     edi , # 4  \ $83 $C7 $4 
15870: ( $804A698 )  lea     ebx , dword ptr 4 [eax]  \ $8D $58 $4 
15871: ( $804A69B )  jmp     dword ptr FC [ebx]  \ $FF $63 $FC 
15872: end-code
15873: @end example
15874: 
15875: With dynamic superinstructions and replication the compiler does not
15876: just lay down the threaded code, but also copies the machine code
15877: fragments, usually without the jump at the end.
15878: 
15879: @example
15880: ( $4057D27D )  add     esi , # -4  \ $83 $C6 $FC 
15881: ( $4057D280 )  add     ebx , # 4  \ $83 $C3 $4 
15882: ( $4057D283 )  mov     dword ptr 4 [esi] , ecx  \ $89 $4E $4 
15883: ( $4057D286 )  mov     eax , dword ptr 4 [esi]  \ $8B $46 $4 
15884: ( $4057D289 )  add     esi , # 4  \ $83 $C6 $4 
15885: ( $4057D28C )  add     ebx , # 4  \ $83 $C3 $4 
15886: ( $4057D28F )  imul    ecx , eax  \ $F $AF $C8 
15887: ( $4057D292 )  mov     eax , dword ptr [edi]  \ $8B $7 
15888: ( $4057D294 )  add     edi , # 4  \ $83 $C7 $4 
15889: ( $4057D297 )  lea     ebx , dword ptr 4 [eax]  \ $8D $58 $4 
15890: ( $4057D29A )  jmp     dword ptr FC [ebx]  \ $FF $63 $FC 
15891: @end example
15892: 
15893: Only when a threaded-code control-flow change happens (e.g., in
15894: @code{;s}), the jump is appended.  This optimization eliminates many of
15895: these jumps and makes the rest much more predictable.  The speedup
15896: depends on the processor and the application; on the Athlon and Pentium
15897: III this optimization typically produces a speedup by a factor of 2.
15898: 
15899: The code addresses in the direct-threaded code are set to point to the
15900: appropriate points in the copied machine code, in this example like
15901: this:
15902: 
15903: @example
15904: primitive  code address
15905:    dup       $4057D27D
15906:    *         $4057D286
15907:    ;s        $4057D292
15908: @end example
15909: 
15910: Thus there can be threaded-code jumps to any place in this piece of
15911: code.  This also simplifies decompilation quite a bit.
15912: 
15913: @cindex --no-dynamic command-line option
15914: @cindex --no-super command-line option
15915: You can disable this optimization with @option{--no-dynamic}.  You can
15916: use the copying without eliminating the jumps (i.e., dynamic
15917: replication, but without superinstructions) with @option{--no-super};
15918: this gives the branch prediction benefit alone; the effect on
15919: performance depends on the CPU; on the Athlon and Pentium III the
15920: speedup is a little less than for dynamic superinstructions with
15921: replication.
15922: 
15923: @cindex patching threaded code
15924: One use of these options is if you want to patch the threaded code.
15925: With superinstructions, many of the dispatch jumps are eliminated, so
15926: patching often has no effect.  These options preserve all the dispatch
15927: jumps.
15928: 
15929: @cindex --dynamic command-line option
15930: On some machines dynamic superinstructions are disabled by default,
15931: because it is unsafe on these machines.  However, if you feel
15932: adventurous, you can enable it with @option{--dynamic}.
15933: 
15934: @node DOES>,  , Dynamic Superinstructions, Threading
15935: @subsection DOES>
15936: @cindex @code{DOES>} implementation
15937: 
15938: @cindex @code{dodoes} routine
15939: @cindex @code{DOES>}-code
15940: One of the most complex parts of a Forth engine is @code{dodoes}, i.e.,
15941: the chunk of code executed by every word defined by a
15942: @code{CREATE}...@code{DOES>} pair; actually with primitive-centric code,
15943: this is only needed if the xt of the word is @code{execute}d. The main
15944: problem here is: How to find the Forth code to be executed, i.e. the
15945: code after the @code{DOES>} (the @code{DOES>}-code)? There are two
15946: solutions:
15947: 
15948: In fig-Forth the code field points directly to the @code{dodoes} and the
15949: @code{DOES>}-code address is stored in the cell after the code address
15950: (i.e. at @code{@i{CFA} cell+}). It may seem that this solution is
15951: illegal in the Forth-79 and all later standards, because in fig-Forth
15952: this address lies in the body (which is illegal in these
15953: standards). However, by making the code field larger for all words this
15954: solution becomes legal again.  We use this approach.  Leaving a cell
15955: unused in most words is a bit wasteful, but on the machines we are
15956: targeting this is hardly a problem.
15957: 
15958: 
15959: @node Primitives, Performance, Threading, Engine
15960: @section Primitives
15961: @cindex primitives, implementation
15962: @cindex virtual machine instructions, implementation
15963: 
15964: @menu
15965: * Automatic Generation::        
15966: * TOS Optimization::            
15967: * Produced code::               
15968: @end menu
15969: 
15970: @node Automatic Generation, TOS Optimization, Primitives, Primitives
15971: @subsection Automatic Generation
15972: @cindex primitives, automatic generation
15973: 
15974: @cindex @file{prims2x.fs}
15975: 
15976: Since the primitives are implemented in a portable language, there is no
15977: longer any need to minimize the number of primitives. On the contrary,
15978: having many primitives has an advantage: speed. In order to reduce the
15979: number of errors in primitives and to make programming them easier, we
15980: provide a tool, the primitive generator (@file{prims2x.fs} aka Vmgen,
15981: @pxref{Top, Vmgen, Introduction, vmgen, Vmgen}), that automatically
15982: generates most (and sometimes all) of the C code for a primitive from
15983: the stack effect notation.  The source for a primitive has the following
15984: form:
15985: 
15986: @cindex primitive source format
15987: @format
15988: @i{Forth-name}  ( @i{stack-effect} )        @i{category}    [@i{pronounc.}]
15989: [@code{""}@i{glossary entry}@code{""}]
15990: @i{C code}
15991: [@code{:}
15992: @i{Forth code}]
15993: @end format
15994: 
15995: The items in brackets are optional. The category and glossary fields
15996: are there for generating the documentation, the Forth code is there
15997: for manual implementations on machines without GNU C. E.g., the source
15998: for the primitive @code{+} is:
15999: @example
16000: +    ( n1 n2 -- n )   core    plus
16001: n = n1+n2;
16002: @end example
16003: 
16004: This looks like a specification, but in fact @code{n = n1+n2} is C
16005: code. Our primitive generation tool extracts a lot of information from
16006: the stack effect notations@footnote{We use a one-stack notation, even
16007: though we have separate data and floating-point stacks; The separate
16008: notation can be generated easily from the unified notation.}: The number
16009: of items popped from and pushed on the stack, their type, and by what
16010: name they are referred to in the C code. It then generates a C code
16011: prelude and postlude for each primitive. The final C code for @code{+}
16012: looks like this:
16013: 
16014: @example
16015: I_plus: /* + ( n1 n2 -- n ) */  /* label, stack effect */
16016: /*  */                          /* documentation */
16017: NAME("+")                       /* debugging output (with -DDEBUG) */
16018: @{
16019: DEF_CA                          /* definition of variable ca (indirect threading) */
16020: Cell n1;                        /* definitions of variables */
16021: Cell n2;
16022: Cell n;
16023: NEXT_P0;                        /* NEXT part 0 */
16024: n1 = (Cell) sp[1];              /* input */
16025: n2 = (Cell) TOS;
16026: sp += 1;                        /* stack adjustment */
16027: @{
16028: n = n1+n2;                      /* C code taken from the source */
16029: @}
16030: NEXT_P1;                        /* NEXT part 1 */
16031: TOS = (Cell)n;                  /* output */
16032: NEXT_P2;                        /* NEXT part 2 */
16033: @}
16034: @end example
16035: 
16036: This looks long and inefficient, but the GNU C compiler optimizes quite
16037: well and produces optimal code for @code{+} on, e.g., the R3000 and the
16038: HP RISC machines: Defining the @code{n}s does not produce any code, and
16039: using them as intermediate storage also adds no cost.
16040: 
16041: There are also other optimizations that are not illustrated by this
16042: example: assignments between simple variables are usually for free (copy
16043: propagation). If one of the stack items is not used by the primitive
16044: (e.g.  in @code{drop}), the compiler eliminates the load from the stack
16045: (dead code elimination). On the other hand, there are some things that
16046: the compiler does not do, therefore they are performed by
16047: @file{prims2x.fs}: The compiler does not optimize code away that stores
16048: a stack item to the place where it just came from (e.g., @code{over}).
16049: 
16050: While programming a primitive is usually easy, there are a few cases
16051: where the programmer has to take the actions of the generator into
16052: account, most notably @code{?dup}, but also words that do not (always)
16053: fall through to @code{NEXT}.
16054: 
16055: For more information
16056: 
16057: @node TOS Optimization, Produced code, Automatic Generation, Primitives
16058: @subsection TOS Optimization
16059: @cindex TOS optimization for primitives
16060: @cindex primitives, keeping the TOS in a register
16061: 
16062: An important optimization for stack machine emulators, e.g., Forth
16063: engines, is keeping  one or more of the top stack items in
16064: registers.  If a word has the stack effect @i{in1}...@i{inx} @code{--}
16065: @i{out1}...@i{outy}, keeping the top @i{n} items in registers
16066: @itemize @bullet
16067: @item
16068: is better than keeping @i{n-1} items, if @i{x>=n} and @i{y>=n},
16069: due to fewer loads from and stores to the stack.
16070: @item is slower than keeping @i{n-1} items, if @i{x<>y} and @i{x<n} and
16071: @i{y<n}, due to additional moves between registers.
16072: @end itemize
16073: 
16074: @cindex -DUSE_TOS
16075: @cindex -DUSE_NO_TOS
16076: In particular, keeping one item in a register is never a disadvantage,
16077: if there are enough registers. Keeping two items in registers is a
16078: disadvantage for frequent words like @code{?branch}, constants,
16079: variables, literals and @code{i}. Therefore our generator only produces
16080: code that keeps zero or one items in registers. The generated C code
16081: covers both cases; the selection between these alternatives is made at
16082: C-compile time using the switch @code{-DUSE_TOS}. @code{TOS} in the C
16083: code for @code{+} is just a simple variable name in the one-item case,
16084: otherwise it is a macro that expands into @code{sp[0]}. Note that the
16085: GNU C compiler tries to keep simple variables like @code{TOS} in
16086: registers, and it usually succeeds, if there are enough registers.
16087: 
16088: @cindex -DUSE_FTOS
16089: @cindex -DUSE_NO_FTOS
16090: The primitive generator performs the TOS optimization for the
16091: floating-point stack, too (@code{-DUSE_FTOS}). For floating-point
16092: operations the benefit of this optimization is even larger:
16093: floating-point operations take quite long on most processors, but can be
16094: performed in parallel with other operations as long as their results are
16095: not used. If the FP-TOS is kept in a register, this works. If
16096: it is kept on the stack, i.e., in memory, the store into memory has to
16097: wait for the result of the floating-point operation, lengthening the
16098: execution time of the primitive considerably.
16099: 
16100: The TOS optimization makes the automatic generation of primitives a
16101: bit more complicated. Just replacing all occurrences of @code{sp[0]} by
16102: @code{TOS} is not sufficient. There are some special cases to
16103: consider:
16104: @itemize @bullet
16105: @item In the case of @code{dup ( w -- w w )} the generator must not
16106: eliminate the store to the original location of the item on the stack,
16107: if the TOS optimization is turned on.
16108: @item Primitives with stack effects of the form @code{--}
16109: @i{out1}...@i{outy} must store the TOS to the stack at the start.
16110: Likewise, primitives with the stack effect @i{in1}...@i{inx} @code{--}
16111: must load the TOS from the stack at the end. But for the null stack
16112: effect @code{--} no stores or loads should be generated.
16113: @end itemize
16114: 
16115: @node Produced code,  , TOS Optimization, Primitives
16116: @subsection Produced code
16117: @cindex primitives, assembly code listing
16118: 
16119: @cindex @file{engine.s}
16120: To see what assembly code is produced for the primitives on your machine
16121: with your compiler and your flag settings, type @code{make engine.s} and
16122: look at the resulting file @file{engine.s}.  Alternatively, you can also
16123: disassemble the code of primitives with @code{see} on some architectures.
16124: 
16125: @node  Performance,  , Primitives, Engine
16126: @section Performance
16127: @cindex performance of some Forth interpreters
16128: @cindex engine performance
16129: @cindex benchmarking Forth systems
16130: @cindex Gforth performance
16131: 
16132: On RISCs the Gforth engine is very close to optimal; i.e., it is usually
16133: impossible to write a significantly faster threaded-code engine.
16134: 
16135: On register-starved machines like the 386 architecture processors
16136: improvements are possible, because @code{gcc} does not utilize the
16137: registers as well as a human, even with explicit register declarations;
16138: e.g., Bernd Beuster wrote a Forth system fragment in assembly language
16139: and hand-tuned it for the 486; this system is 1.19 times faster on the
16140: Sieve benchmark on a 486DX2/66 than Gforth compiled with
16141: @code{gcc-2.6.3} with @code{-DFORCE_REG}.  The situation has improved
16142: with gcc-2.95 and gforth-0.4.9; now the most important virtual machine
16143: registers fit in real registers (and we can even afford to use the TOS
16144: optimization), resulting in a speedup of 1.14 on the sieve over the
16145: earlier results.  And dynamic superinstructions provide another speedup
16146: (but only around a factor 1.2 on the 486).
16147: 
16148: @cindex Win32Forth performance
16149: @cindex NT Forth performance
16150: @cindex eforth performance
16151: @cindex ThisForth performance
16152: @cindex PFE performance
16153: @cindex TILE performance
16154: The potential advantage of assembly language implementations is not
16155: necessarily realized in complete Forth systems: We compared Gforth-0.5.9
16156: (direct threaded, compiled with @code{gcc-2.95.1} and
16157: @code{-DFORCE_REG}) with Win32Forth 1.2093 (newer versions are
16158: reportedly much faster), LMI's NT Forth (Beta, May 1994) and Eforth
16159: (with and without peephole (aka pinhole) optimization of the threaded
16160: code); all these systems were written in assembly language. We also
16161: compared Gforth with three systems written in C: PFE-0.9.14 (compiled
16162: with @code{gcc-2.6.3} with the default configuration for Linux:
16163: @code{-O2 -fomit-frame-pointer -DUSE_REGS -DUNROLL_NEXT}), ThisForth
16164: Beta (compiled with @code{gcc-2.6.3 -O3 -fomit-frame-pointer}; ThisForth
16165: employs peephole optimization of the threaded code) and TILE (compiled
16166: with @code{make opt}). We benchmarked Gforth, PFE, ThisForth and TILE on
16167: a 486DX2/66 under Linux. Kenneth O'Heskin kindly provided the results
16168: for Win32Forth and NT Forth on a 486DX2/66 with similar memory
16169: performance under Windows NT. Marcel Hendrix ported Eforth to Linux,
16170: then extended it to run the benchmarks, added the peephole optimizer,
16171: ran the benchmarks and reported the results.
16172: 
16173: We used four small benchmarks: the ubiquitous Sieve; bubble-sorting and
16174: matrix multiplication come from the Stanford integer benchmarks and have
16175: been translated into Forth by Martin Fraeman; we used the versions
16176: included in the TILE Forth package, but with bigger data set sizes; and
16177: a recursive Fibonacci number computation for benchmarking calling
16178: performance. The following table shows the time taken for the benchmarks
16179: scaled by the time taken by Gforth (in other words, it shows the speedup
16180: factor that Gforth achieved over the other systems).
16181: 
16182: @example
16183: relative       Win32-    NT       eforth       This-      
16184: time     Gforth Forth Forth eforth  +opt   PFE Forth  TILE
16185: sieve      1.00  2.16  1.78   2.16  1.32  2.46  4.96 13.37
16186: bubble     1.00  1.93  2.07   2.18  1.29  2.21        5.70
16187: matmul     1.00  1.92  1.76   1.90  0.96  2.06        5.32
16188: fib        1.00  2.32  2.03   1.86  1.31  2.64  4.55  6.54
16189: @end example
16190: 
16191: You may be quite surprised by the good performance of Gforth when
16192: compared with systems written in assembly language. One important reason
16193: for the disappointing performance of these other systems is probably
16194: that they are not written optimally for the 486 (e.g., they use the
16195: @code{lods} instruction). In addition, Win32Forth uses a comfortable,
16196: but costly method for relocating the Forth image: like @code{cforth}, it
16197: computes the actual addresses at run time, resulting in two address
16198: computations per @code{NEXT} (@pxref{Image File Background}).
16199: 
16200: The speedup of Gforth over PFE, ThisForth and TILE can be easily
16201: explained with the self-imposed restriction of the latter systems to
16202: standard C, which makes efficient threading impossible (however, the
16203: measured implementation of PFE uses a GNU C extension: @pxref{Global Reg
16204: Vars, , Defining Global Register Variables, gcc.info, GNU C Manual}).
16205: Moreover, current C compilers have a hard time optimizing other aspects
16206: of the ThisForth and the TILE source.
16207: 
16208: The performance of Gforth on 386 architecture processors varies widely
16209: with the version of @code{gcc} used. E.g., @code{gcc-2.5.8} failed to
16210: allocate any of the virtual machine registers into real machine
16211: registers by itself and would not work correctly with explicit register
16212: declarations, giving a significantly slower engine (on a 486DX2/66
16213: running the Sieve) than the one measured above.
16214: 
16215: Note that there have been several releases of Win32Forth since the
16216: release presented here, so the results presented above may have little
16217: predictive value for the performance of Win32Forth today (results for
16218: the current release on an i486DX2/66 are welcome).
16219: 
16220: @cindex @file{Benchres}
16221: In
16222: @cite{@uref{http://www.complang.tuwien.ac.at/papers/ertl&maierhofer95.ps.gz,
16223: Translating Forth to Efficient C}} by M. Anton Ertl and Martin
16224: Maierhofer (presented at EuroForth '95), an indirect threaded version of
16225: Gforth is compared with Win32Forth, NT Forth, PFE, ThisForth, and
16226: several native code systems; that version of Gforth is slower on a 486
16227: than the version used here. You can find a newer version of these
16228: measurements at
16229: @uref{http://www.complang.tuwien.ac.at/forth/performance.html}. You can
16230: find numbers for Gforth on various machines in @file{Benchres}.
16231: 
16232: @c ******************************************************************
16233: @c @node Binding to System Library, Cross Compiler, Engine, Top
16234: @c @chapter Binding to System Library
16235: 
16236: @c ****************************************************************
16237: @node Cross Compiler, Bugs, Engine, Top
16238: @chapter Cross Compiler
16239: @cindex @file{cross.fs}
16240: @cindex cross-compiler
16241: @cindex metacompiler
16242: @cindex target compiler
16243: 
16244: The cross compiler is used to bootstrap a Forth kernel. Since Gforth is
16245: mostly written in Forth, including crucial parts like the outer
16246: interpreter and compiler, it needs compiled Forth code to get
16247: started. The cross compiler allows to create new images for other
16248: architectures, even running under another Forth system.
16249: 
16250: @menu
16251: * Using the Cross Compiler::    
16252: * How the Cross Compiler Works::  
16253: @end menu
16254: 
16255: @node Using the Cross Compiler, How the Cross Compiler Works, Cross Compiler, Cross Compiler
16256: @section Using the Cross Compiler
16257: 
16258: The cross compiler uses a language that resembles Forth, but isn't. The
16259: main difference is that you can execute Forth code after definition,
16260: while you usually can't execute the code compiled by cross, because the
16261: code you are compiling is typically for a different computer than the
16262: one you are compiling on.
16263: 
16264: @c anton: This chapter is somewhat different from waht I would expect: I
16265: @c would expect an explanation of the cross language and how to create an
16266: @c application image with it.  The section explains some aspects of
16267: @c creating a Gforth kernel.
16268: 
16269: The Makefile is already set up to allow you to create kernels for new
16270: architectures with a simple make command. The generic kernels using the
16271: GCC compiled virtual machine are created in the normal build process
16272: with @code{make}. To create a embedded Gforth executable for e.g. the
16273: 8086 processor (running on a DOS machine), type
16274: 
16275: @example
16276: make kernl-8086.fi
16277: @end example
16278: 
16279: This will use the machine description from the @file{arch/8086}
16280: directory to create a new kernel. A machine file may look like that:
16281: 
16282: @example
16283: \ Parameter for target systems                         06oct92py
16284: 
16285:     4 Constant cell             \ cell size in bytes
16286:     2 Constant cell<<           \ cell shift to bytes
16287:     5 Constant cell>bit         \ cell shift to bits
16288:     8 Constant bits/char        \ bits per character
16289:     8 Constant bits/byte        \ bits per byte [default: 8]
16290:     8 Constant float            \ bytes per float
16291:     8 Constant /maxalign        \ maximum alignment in bytes
16292: false Constant bigendian        \ byte order
16293: ( true=big, false=little )
16294: 
16295: include machpc.fs               \ feature list
16296: @end example
16297: 
16298: This part is obligatory for the cross compiler itself, the feature list
16299: is used by the kernel to conditionally compile some features in and out,
16300: depending on whether the target supports these features.
16301: 
16302: There are some optional features, if you define your own primitives,
16303: have an assembler, or need special, nonstandard preparation to make the
16304: boot process work. @code{asm-include} includes an assembler,
16305: @code{prims-include} includes primitives, and @code{>boot} prepares for
16306: booting.
16307: 
16308: @example
16309: : asm-include    ." Include assembler" cr
16310:   s" arch/8086/asm.fs" included ;
16311: 
16312: : prims-include  ." Include primitives" cr
16313:   s" arch/8086/prim.fs" included ;
16314: 
16315: : >boot          ." Prepare booting" cr
16316:   s" ' boot >body into-forth 1+ !" evaluate ;
16317: @end example
16318: 
16319: These words are used as sort of macro during the cross compilation in
16320: the file @file{kernel/main.fs}. Instead of using these macros, it would
16321: be possible --- but more complicated --- to write a new kernel project
16322: file, too.
16323: 
16324: @file{kernel/main.fs} expects the machine description file name on the
16325: stack; the cross compiler itself (@file{cross.fs}) assumes that either
16326: @code{mach-file} leaves a counted string on the stack, or
16327: @code{machine-file} leaves an address, count pair of the filename on the
16328: stack.
16329: 
16330: The feature list is typically controlled using @code{SetValue}, generic
16331: files that are used by several projects can use @code{DefaultValue}
16332: instead. Both functions work like @code{Value}, when the value isn't
16333: defined, but @code{SetValue} works like @code{to} if the value is
16334: defined, and @code{DefaultValue} doesn't set anything, if the value is
16335: defined.
16336: 
16337: @example
16338: \ generic mach file for pc gforth                       03sep97jaw
16339: 
16340: true DefaultValue NIL  \ relocating
16341: 
16342: >ENVIRON
16343: 
16344: true DefaultValue file          \ controls the presence of the
16345:                                 \ file access wordset
16346: true DefaultValue OS            \ flag to indicate a operating system
16347: 
16348: true DefaultValue prims         \ true: primitives are c-code
16349: 
16350: true DefaultValue floating      \ floating point wordset is present
16351: 
16352: true DefaultValue glocals       \ gforth locals are present
16353:                                 \ will be loaded
16354: true DefaultValue dcomps        \ double number comparisons
16355: 
16356: true DefaultValue hash          \ hashing primitives are loaded/present
16357: 
16358: true DefaultValue xconds        \ used together with glocals,
16359:                                 \ special conditionals supporting gforths'
16360:                                 \ local variables
16361: true DefaultValue header        \ save a header information
16362: 
16363: true DefaultValue backtrace     \ enables backtrace code
16364: 
16365: false DefaultValue ec
16366: false DefaultValue crlf
16367: 
16368: cell 2 = [IF] &32 [ELSE] &256 [THEN] KB DefaultValue kernel-size
16369: 
16370: &16 KB          DefaultValue stack-size
16371: &15 KB &512 +   DefaultValue fstack-size
16372: &15 KB          DefaultValue rstack-size
16373: &14 KB &512 +   DefaultValue lstack-size
16374: @end example
16375: 
16376: @node How the Cross Compiler Works,  , Using the Cross Compiler, Cross Compiler
16377: @section How the Cross Compiler Works
16378: 
16379: @node Bugs, Origin, Cross Compiler, Top
16380: @appendix Bugs
16381: @cindex bug reporting
16382: 
16383: Known bugs are described in the file @file{BUGS} in the Gforth distribution.
16384: 
16385: If you find a bug, please submit a bug report through
16386: @uref{https://savannah.gnu.org/bugs/?func=addbug&group=gforth}.
16387: 
16388: @itemize @bullet
16389: @item
16390: A program (or a sequence of keyboard commands) that reproduces the bug.
16391: @item
16392: A description of what you think constitutes the buggy behaviour.
16393: @item
16394: The Gforth version used (it is announced at the start of an
16395: interactive Gforth session).
16396: @item
16397: The machine and operating system (on Unix
16398: systems @code{uname -a} will report this information).
16399: @item
16400: The installation options (you can find the configure options at the
16401: start of @file{config.status}) and configuration (@code{configure}
16402: output or @file{config.cache}).
16403: @item
16404: A complete list of changes (if any) you (or your installer) have made to the
16405: Gforth sources.
16406: @end itemize
16407: 
16408: For a thorough guide on reporting bugs read @ref{Bug Reporting, , How
16409: to Report Bugs, gcc.info, GNU C Manual}.
16410: 
16411: 
16412: @node Origin, Forth-related information, Bugs, Top
16413: @appendix Authors and Ancestors of Gforth
16414: 
16415: @section Authors and Contributors
16416: @cindex authors of Gforth
16417: @cindex contributors to Gforth
16418: 
16419: The Gforth project was started in mid-1992 by Bernd Paysan and Anton
16420: Ertl. The third major author was Jens Wilke.  Neal Crook contributed a
16421: lot to the manual.  Assemblers and disassemblers were contributed by
16422: Andrew McKewan, Christian Pirker, Bernd Thallner, and Michal Revucky.
16423: Lennart Benschop (who was one of Gforth's first users, in mid-1993)
16424: and Stuart Ramsden inspired us with their continuous feedback. Lennart
16425: Benshop contributed @file{glosgen.fs}, while Stuart Ramsden has been
16426: working on automatic support for calling C libraries. Helpful comments
16427: also came from Paul Kleinrubatscher, Christian Pirker, Dirk Zoller,
16428: Marcel Hendrix, John Wavrik, Barrie Stott, Marc de Groot, Jorge
16429: Acerada, Bruce Hoyt, Robert Epprecht, Dennis Ruffer and David
16430: N. Williams. Since the release of Gforth-0.2.1 there were also helpful
16431: comments from many others; thank you all, sorry for not listing you
16432: here (but digging through my mailbox to extract your names is on my
16433: to-do list).
16434: 
16435: Gforth also owes a lot to the authors of the tools we used (GCC, CVS,
16436: and autoconf, among others), and to the creators of the Internet: Gforth
16437: was developed across the Internet, and its authors did not meet
16438: physically for the first 4 years of development.
16439: 
16440: @section Pedigree
16441: @cindex pedigree of Gforth
16442: 
16443: Gforth descends from bigFORTH (1993) and fig-Forth.  Of course, a
16444: significant part of the design of Gforth was prescribed by ANS Forth.
16445: 
16446: Bernd Paysan wrote bigFORTH, a descendent from TurboForth, an unreleased
16447: 32 bit native code version of VolksForth for the Atari ST, written
16448: mostly by Dietrich Weineck.
16449: 
16450: VolksForth was written by Klaus Schleisiek, Bernd Pennemann, Georg
16451: Rehfeld and Dietrich Weineck for the C64 (called UltraForth there) in
16452: the mid-80s and ported to the Atari ST in 1986.  It descends from fig-Forth.
16453: 
16454: @c Henry Laxen and Mike Perry wrote F83 as a model implementation of the
16455: @c Forth-83 standard. !! Pedigree? When?
16456: 
16457: A team led by Bill Ragsdale implemented fig-Forth on many processors in
16458: 1979. Robert Selzer and Bill Ragsdale developed the original
16459: implementation of fig-Forth for the 6502 based on microForth.
16460: 
16461: The principal architect of microForth was Dean Sanderson. microForth was
16462: FORTH, Inc.'s first off-the-shelf product. It was developed in 1976 for
16463: the 1802, and subsequently implemented on the 8080, the 6800 and the
16464: Z80.
16465: 
16466: All earlier Forth systems were custom-made, usually by Charles Moore,
16467: who discovered (as he puts it) Forth during the late 60s. The first full
16468: Forth existed in 1971.
16469: 
16470: A part of the information in this section comes from
16471: @cite{@uref{http://www.forth.com/Content/History/History1.htm,The
16472: Evolution of Forth}} by Elizabeth D. Rather, Donald R. Colburn and
16473: Charles H. Moore, presented at the HOPL-II conference and preprinted
16474: in SIGPLAN Notices 28(3), 1993.  You can find more historical and
16475: genealogical information about Forth there.  For a more general (and
16476: graphical) Forth family tree look see
16477: @cite{@uref{http://www.complang.tuwien.ac.at/forth/family-tree/},
16478: Forth Family Tree and Timeline}.
16479: 
16480: @c ------------------------------------------------------------------
16481: @node Forth-related information, Licenses, Origin, Top
16482: @appendix Other Forth-related information
16483: @cindex Forth-related information
16484: 
16485: @c anton: I threw most of this stuff out, because it can be found through
16486: @c the FAQ and the FAQ is more likely to be up-to-date.
16487: 
16488: @cindex comp.lang.forth
16489: @cindex frequently asked questions
16490: There is an active news group (comp.lang.forth) discussing Forth
16491: (including Gforth) and Forth-related issues. Its
16492: @uref{http://www.complang.tuwien.ac.at/forth/faq/faq-general-2.html,FAQs}
16493: (frequently asked questions and their answers) contains a lot of
16494: information on Forth.  You should read it before posting to
16495: comp.lang.forth.
16496: 
16497: The ANS Forth standard is most usable in its
16498: @uref{http://www.taygeta.com/forth/dpans.html, HTML form}.
16499: 
16500: @c ---------------------------------------------------
16501: @node  Licenses, Word Index, Forth-related information, Top
16502: @appendix Licenses
16503: 
16504: @menu
16505: * GNU Free Documentation License::  License for copying this manual.
16506: * Copying::                     GPL (for copying this software).
16507: @end menu
16508: 
16509: @node GNU Free Documentation License, Copying, Licenses, Licenses
16510: @appendixsec GNU Free Documentation License
16511: @include fdl.texi
16512: 
16513: @node Copying,  , GNU Free Documentation License, Licenses
16514: @appendixsec GNU GENERAL PUBLIC LICENSE
16515: @include gpl.texi
16516: 
16517: 
16518: 
16519: @c ------------------------------------------------------------------
16520: @node Word Index, Concept Index, Licenses, Top
16521: @unnumbered Word Index
16522: 
16523: This index is a list of Forth words that have ``glossary'' entries
16524: within this manual. Each word is listed with its stack effect and
16525: wordset.
16526: 
16527: @printindex fn
16528: 
16529: @c anton: the name index seems superfluous given the word and concept indices.
16530: 
16531: @c @node Name Index, Concept Index, Word Index, Top
16532: @c @unnumbered Name Index
16533: 
16534: @c This index is a list of Forth words that have ``glossary'' entries
16535: @c within this manual.
16536: 
16537: @c @printindex ky
16538: 
16539: @c -------------------------------------------------------
16540: @node Concept Index,  , Word Index, Top
16541: @unnumbered Concept and Word Index
16542: 
16543: Not all entries listed in this index are present verbatim in the
16544: text. This index also duplicates, in abbreviated form, all of the words
16545: listed in the Word Index (only the names are listed for the words here).
16546: 
16547: @printindex cp
16548: 
16549: @bye
16550: 
16551: 
16552: 

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